0% found this document useful (0 votes)
130 views434 pages

Java Full Notes

Java is an object-oriented programming language and platform. It was developed by Sun Microsystems in 1995 under the name Oak before being renamed to Java. Java runs on a virtual machine and compiles code to bytecode, allowing it to run on any device that supports Java. It is widely used to create desktop applications, web applications, enterprise applications, and mobile applications.

Uploaded by

mk2834787
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
130 views434 pages

Java Full Notes

Java is an object-oriented programming language and platform. It was developed by Sun Microsystems in 1995 under the name Oak before being renamed to Java. Java runs on a virtual machine and compiles code to bytecode, allowing it to run on any device that supports Java. It is widely used to create desktop applications, web applications, enterprise applications, and mobile applications.

Uploaded by

mk2834787
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 434

What is Java?

Java is a programming language and a platform. Java is a high level,


robust, object-oriented and secure programming language.

Java was developed by Sun Microsystems (which is now owned by Oracle ) in


the year 1995. James Gosling is known as the father of Java. Before Java,
its name was Oak.

Platform: Any hardware or software environment in which a program


runs, is known as a platform. Since Java has a runtime environment
(JRE) and API, it is called a platform.

Application

According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus,


etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application

Standalone applications are also known as desktop applications or


window-based applications. These are traditional software that we need
to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
2) Web Application

An application that runs on the server side and creates a dynamic page is
called a web application.

Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications,


etc. is called an enterprise application. It has advantages like high-level
security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile


application. Currently, Android and Java ME are used for creating mobile
applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such


as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It
includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and


enterprise applications. It is built on top of the Java SE platform. It
includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user


interface API.
Features of Java Programming Language

Java has become a popular and useful programming language because of its
excellent features, which play a very important role in contributing to the
popularity of this language. The Java features are called “Java BuzzWords”.
Sun MicroSystems officially describes Java with the following list of features:

 Simple and Familiar  Robust


 Compiled and Interpreted  Secure
 Platform Independent  Distributed
 Portable  Multi-threaded and Interactive
 Architectural Neutral  High Performance
 Object-Oriented  Dynamic and Extensible

Simple and Familiar

Java is simple because:


Its coding style is very clean and easy to understand. It removes complexity
because it doesn’t use complex and difficult features of other languages like C
and C++, which are as follows:

 Concept of Explicit Pointers  Multiple Inheritance


 Storage classes  Operator Overloading
 Preprocessors and header  Goto Statements
files

Apart from the removal of these confusing and ambiguous concepts, there is a
provision of Automatic Garbage Collection, in which there is no need to remove
the unreferenced objects explicitly.
Java is familiar because:
 It has a base of familiar languages like C and C++ and contains many
features of these languages.
 It removes the drawbacks, complexities and confusing elements of C/C++.
So if you have good knowledge of C/C++, you will find Java familiar and easy
to understand.

Compiled and Interpreted

Usually, a computer language can be either compiled or interpreted. Java


integrates the power of Compiled Languages with the flexibility of Interpreted
Languages.
Java compiler (javac) compiles the java source code into the bytecode.

Java Virtual Machine (JVM) then executes this bytecode which is executable on
many operating systems and is portable.

The diagram below shows the above process:

Platform Independent

The most significant feature of Java is that it provides platform independence


which leads to a facility of portability, which ultimately becomes its biggest
strength.

Being platform-independent means a program compiled on one machine can


be executed on any machine in the world without any change. Java achieves
platform independence by using the concept of the BYTE code.

The Java compiler never converts the source code to machine code like that of
the C/C++ compiler.

Instead, it converts the source code into an intermediate code called the byte
code and this byte code is further translated to machine-dependent form
by another layer of software called JVM (Java Virtual Machine).
Therefore, JVM can execute bytecode on any platform or OS on which it is
present, regardless of the fact that on which machine the bytecode was
generated.

This is where the “Write Once, run anywhere” (WORA) slogan for Java comes
in, which means that we can develop applications on one environment (OS)
and run on any other environment without doing any modification in the
code.
Portable
Java is “portable” refers to the SE (Standard Edition) version. The portability
actually comes from architecture-neutrality.
In C/C++, the source code may run slightly differently on different
hardware platforms, but Java simplifies it. You can run Java bytecode on any
hardware that has a compliant JVM which can convert the bytecode according
to that particular machine.
In Java, the size of the primitive data types is machine-independent, which
were dependent in the case of C/C++. So, these provisions make Java programs
portable among different platforms such as Windows, Unix, Solaris, and Mac.
Moreover, any changes and updates made in Operating Systems, Processors
and System resources will not enforce any changes in Java programs.
Architectural Neutral
It is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-run-
everywhere’ (WORE) approach.
Byte-code is not dependent on any machine architecture and Java Virtual
Machine (JVM) can easily translate bytecode into a machine-specific code.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Object-Oriented
Java strongly supports the concepts of Object-Oriented Programming due to
which it is called a pure object-oriented language.
Java supports major Object-Oriented programming features like Encapsulation,
Abstraction, and Inheritance.
Almost everything in Java is an object. All programs and data live within objects
and classes. ‘Objects’ model Java rather than the ‘processes’. Java comes with
an extensible set of classes organized in packages.
For example, we cannot develop an executable program in Java without making
use of the class. This indicates that Java very strictly applies the principle of
Encapsulation.
Robust
Java is robust as it is capable of handling run-time errors, supports automatic
garbage collection and exception handling, and avoids explicit pointer concept.
Java has a strong memory management system. It helps in eliminating errors as
it checks the code during both compile and runtime.
Java is garbage-collected language – JVM automatically deallocates the memory
blocks and programmers do not have to worry about deleting the memory
manually as in case of C/C++.
Java also provides the concept of exception handling which identifies runtime
errors and eliminates them.
In Java, any runtime error encountered by the JVM is never passed directly to
the underlying system rather immediately terminates the program stopping it
from causing any harm to the underlying system.
Secure
Security is an important issue for any programming language as there is a threat
of malicious activities and viruses. Java supports access modifiers to check
memory access and also ensures that no viruses enter an applet.
Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Thus in Java, we can not gain access
to a particular variable if we do not initialize it properly.
Programs run in a virtual machine sandbox – A separate environment that
allows users to execute their applications without affecting the underlying
system.
It has a bytecode verifier that checks the code fragments for any illegal code that
violates the access right.
Distributed

Java is distributed because it encourages users to create distributed


applications.

In Java, we can split a program into many parts and store these parts on
different computers. A Java programmer sitting on a machine can access
another program running on the other machine.

This feature in Java gives the advantage of distributed programming, which is


very helpful when we develop large projects. Java helps us to achieve this by
providing the concept of RMI (Remote Method Invocation) and EJB
(Enterprise JavaBeans).

Java comes with an extensive library of classes for interacting, using TCP/IP
protocols such as HTTP and FTP, which makes creating network connections
much easier than in C/C++.

It also enables multiple programmers at many locations to work together


on a single project.

Multi-threaded and Interactive


A thread is an independent path of execution within a program,
executing concurrently. Multithreaded means handling multiple
tasks simultaneously or executing multiple portions (functions)
of the same program in parallel.
The code of java is divided into smaller parts and Java executes
them in a sequential and timely manner.
Advantages:
 The main advantage of multithreading is that the maximum utilization of
resources is possible.
 It doesn’t occupy memory for each thread. It shares a common memory area.
 There is no need to wait for the application to finish one task before beginning
another one.
 There is a decreased cost of maintenance. Also, It is time-saving.
 It improves the performance of complex applications.

Java is interactive because its code supports effective CUI (Character User
Interface) and GUI (Graphical User Interface) programs. It greatly improves
the interactive performance of graphical applications.

High Performance
The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
Java provides high performance with the use of “JIT – Just In Time compiler”,
in which the compiler compiles the code on-demand basis, that is, it
compiles only that method which is being called. This saves time and makes
it more efficient.
Java architecture is also designed in such a way that it reduces overheads during
runtime. The inclusion of multithreading enhances the overall execution speed
of Java programs.
Bytecodes generated by the Java compiler are highly optimized, so Java
Virtual Machine can execute them much faster.
Dynamic and Extensible
Java is dynamic and extensible means with the help of OOPs, we can add classes
and add new methods to classes, creating new classes through subclasses. This
makes it easier for us to expand our own classes and even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and
objects. It is highly dynamic as it can adapt to its evolving environment.
Java even supports functions written in other languages such as C and C++ to
be written in Java programs. These functions are called “native methods”. These
methods are dynamically linked at runtime.
JDK, JRE and JVM

JDK (Java Development Kit) is a Kit that provides the environment


to develop and execute(run) the Java program. JDK is a kit(or package)
that includes two things

 Development Tools(to provide an environment to develop your java


programs)
 JRE (to execute your java program).

JRE (Java Runtime Environment) 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.

JVM (Java Virtual Machine) 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.
Basic Structure of a Java Program

A Java program consists of different sections. Some of them are mandatory but
some are optional. The optional section can be excluded from the program
depending upon the requirements of the programmer.

Documentation Section
It is used to improve the readability of the program. It consists of comments in
Java which include basic information such as the method’s usage or
functionality to make it easier for the programmer to understand it while
reviewing or debugging the code. A Java comment is not necessarily limited to
a confined space, it can appear anywhere in the code.

The compiler ignores these comments during the time of execution and is solely
meant for improving the readability of the Java program.

There are three types of comments that Java supports

 Single-line Comment
 Multi-line Comment
 Documentation Comment

Single-line (or end-of line) comment:


It starts with a double slash symbol (//) and terminates at the end of the current
line. The compiler ignores everything from // to the end of the line. For example:
// Calculate sum of two numbers

Multi-line Comment:
Java programmer can use C/C++ comment style that begins with delimiter /*
and ends with */. All the text written between the delimiter is ignored by the
compiler. This style of comments can be used on part of a line, a whole line or
more commonly to define multi-line comment. For example.

/* Calculate sum of
two numbers and
it is a multiline comment */

Nested Comment is not possible:


Comments cannot be nested. In other words, you cannot comment a line that
already includes traditional comment. For example:

/* x = y /* initial value */ + z; */ is wrong.

Documentation comments:
This comment style is new in Java. Such comments begin with delimiter /**
and end with */. The compiler also ignores this type of comments just like it
ignores comments that use / * and */. The main purpose of this type of comment
is to automatically generate program documentation. The javadoc tool
reads these comments and uses them to prepare your program's
documentation in HTML format. For example.

/** The text enclosed here will be part of program documentation */

Package Statement
A package is a collection of classes, interfaces and sub-packages. A sub
package contains collection of classes, interfaces and sub-sub packages etc.

java.lang.*; package is imported by default and this package is known as


default package. It must appear as the first statement in the source code file
before any class or interface declaration. This statement is optional.
Example Suppose you write the following package declaration as the first
statement in the source code file.

package institute;

This statement declares that all classes and interfaces defined in this source file
are part of the institute package. Only one package declaration can appear in
the source file.

Import statements
Java contains many predefined classes that are stored into packages. In order
to refer these standard predefined classes in your program, you need to use
fully qualified name (i.e. Packagename.className). But this is a very tedious
task as one need to retype the package path name along with the classname. So
a better alternative is to use an import statement.

An import statement is used for referring classes that are declared in other
packages. The import statement is written after a package statement but before
any class definition. You can import a specific class or all the classes of the
package.

Example If you want to import Date class of java.util package using import
statement then write.

import java.util.Date;

This statement allows the programmer to use the simple classname Date rather
than fully qualified classname java.util.Date in the code.

Unlike package statement, you can specify more than one import statement in
your program.

Example

Import java.util.Date; /* imports only the Date class in java.util package */


import java.applet.*; // imports all the classes in java applet
Interface Section
An interface is similar to a class but contains only constants and method
declarations. Interfaces cannot be instantiated. They can only be
implemented by classes or extended by other interfaces. It is an optional
section and is used when we wish to implement multiple inheritance feature in
the program.

interface stack
{
void push(int item); // Insert item into stack
int pop(); // Delete an item from stack
}

Class Definition:
Java program may contain multiple class definition. Classes are primary
feature of Java program. The classes are used to map real world problems.

class Addition
{
void add(String args[])
{
int a=2, b=3, c;
c=a+b;
System.out.println(c);
}
}

Main Method Class Section:


The Class section describes the information about user-defined classes present
in the program. A class is a collection of fields (data variables) and methods
that operate on the fields. Every program in Java consists of at least one
class, the one that contains the main method. The main () method which is
from where the execution of program actually starts and follow the
statements in the order specified.
The main method can create objects, evaluate expressions, and invoke
other methods and much more. On reaching the end of main, the program
terminates and control passes back to the operating system.
The class section is mandatory.

// Program to display message on the screen


class HelloJava
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Identifiers in Java

Identifiers are the basic building blocks of a Java program. We use identifiers
to give names to the different parts of the program such as variables, objects,
classes, methods, arrays, etc.

The rules for naming identifiers in Java are:


 Identifiers can contain alphabets, digits, and underscore(_) and
dollar($) sign characters.
 They must not be a reserved word or keyword in Java, like true, false,
while, etc.
 Identifiers must not begin with digits
 Identifiers can be of any length
 Java is case sensitive, so uppercase and lowercase identifiers are
treated differently.
 Keywords in Java

Keywords are the reserved words in Java that convey a different meaning to
the compiler. We cannot use the keywords as normal identifier names but only
for a special purpose. In Java, there are 51 keywords.

Some of the keywords in Java are:


abstract, boolean, byte, char, long, short, int, finally, extends, implements,
interface, package, new, while, for, do, break, continue, return, public, private,
this, case, final, default, etc.

Literals in Java

A literal in Java refers to the constants or the data items that have fixed values.
There are different types of Literals in Java. They are Numeric, Floating,
character, strings, boolean, null. They are also divided further into
subcategories. Let’s discuss them separately:

a. Numeric Literals

Numeric literals represent numbers. There are 4 types of numeric literals in


Java:

i. Integer Literals: Integer literals are the whole numbers without fractional
part and they are the number of base 10. For example, 34, 76, 9896, etc.
ii. Binary Literals: Binary literals are the number with base 2. For example,
0101, 0011, 011, etc.
iii. Octal Literals: Octal literals are the numbers with base 8. They must not
contain 8 and 9. For example, 77, 565, 450, etc.
iv. Hexadecimal Literals: Hexadecimal literals are the numbers with base 16.
They can contain the digits from 0 to 9 and alphabets from A to F. For
Example, AC87, 1F7B, 24D6, etc.
b. Floating-point Literals

We can call floating-point literals as real literals. The floating-point literal


specifies the numeric values only with the use of a fractional point(.). They can
be a fractional form or exponential form. For Example, 10.876, 152.4E07, -
15.6, etc.

c. Character Literals in Java

The character-literals deal with characters enclosed in single-quote. They can


contain only a single character within single quotes ‘ ’. They are of following
types:

i. Single quoted character: The single-quoted character encloses all the uni-
length characters within single quotes. Example- ‘z’,’j’, ‘A’, etc.
ii. Escape Sequences: These are the characters that come after backslash and
perform a specific function when printed on the screen such as a tab, creating
a new line, etc. Example: ’\n’, ‘\b’, ‘\t’, etc.
iii. Unicode Representation: We can represent it by specifying the concerned
Unicode value of the character after ‘\u’. For Example- ‘\u0067’, etc.
d. Boolean literals

A boolean literal has only two values: true and false. These values are formed
from ASCII letters. Example: true, false.

e. String Literals

The String-literals are the multiple character constants enclosed within double
quotes “ ”. For example, “java tutorial”, “HelloWorld”, “\abc”, etc.
Java Is a Strongly Typed Language: It is important to state at the outset that
Java is a strongly typed language. Indeed, part of Java's safety and robustness
comes from this fact.
First, every variable has a type, every expression has a type, and every type
is strictly defined. Second, all assignments, whether explicit or via parameter
passing in method calls, are checked for type compatibility. There are no
automatic coercions or conversions of conflicting types as in some languages.
The Java compiler checks all expressions and parameters to ensure that the
types are compatible. Any type mismatches are errors that must be corrected
before the compiler will finish compiling the class.

Data types specify the different sizes and values that can be stored in the
variable.
• There are two types of data types in Java:
 Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
 Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Primitive Data Types
1. Data types are predefined by the Java language.
2. Predefined data types are Reserved keyword so we cannot use them as
variable name inside program/application
3. Primitive values do not share state with other primitive values.
4. Total Number of Primitive Data Types in Java Programming is 8
5. All Primitive Data Types have respective Wrapper Classes i.e Integer is
wrapper class for primitive type int
Data Type and Other Details

boolean Data Type :


1. Boolean is primitive data type in Java.
2. Boolean data type is used for logical values.
3. Boolean data type can have two possible values : true or false.
4. Boolean is the type returned by all relational operators
5. Boolean is the type required by the conditional expressions used in
control statements such as if and for.
6. The size of boolean data type is virtual machine-dependent.
7. Values of type boolean are not converted implicitly or explicitly (with
casts) to any other type.
8. “Boolean” is wrapper class for “boolean” primitive data type.
Example 1:
boolean one = false
Example 2:
boolean b1,b2,b3;
b1 = true; // Assigning Value
b2 = false; // Assigning Value
b3 = b2; // Assigning Variable
Integer Data Type :
1. Integer Data Type is used to store integer value.
2. Integer Data Type is Primitive Data Type in Java Programming Language.
3. Integer Data Type have respective Wrapper Class – “Integer“.
4. Integer Data Type is able to store both unsigned and signed integer
values.

Integer Data Type Can have 4 types of Values these

Name Width Range

–9,223,372,036,854,775,808 to
long 64
9,223,372,036,854,775,807

Int 32 –2,147,483,648 to 2,147,483,647

short 16 –32,768 to 32,767

byte 8 –128 to 127

Example:
byte a = 10, byte b = -20
short s = 10000, short r = -5000
int a = 100000, int b = -200000
long a = 100000L, long b = -200000L
Float Data Type :
1. Floating Data Type is used to store float value.
2. Floating Data Type is Primitive Data Type in Java Programming Language.
3. Floating Data Type have respective Wrapper Class – “Float or Double“.
4. float Data Type Can store 2 types of Values:
1. Float
2. Double
float:
 It occupy 4 bytes in memory.
 Values are represented with approximately 7 decimal digits accuracy
Double:
 It occupy 8 bytes in memory.
 Values are represented with approximately 17 decimal digits accuracy.

Declaring Integer Variable in Java Programming


Class FloatDemo
{
public static void main(String args[])
{
float fval = 10.0f;
System.out.println("Total Number : " + fval);
}
}
Float Type : Some Notes
1. In Java any value declared with decimal point is by default of type double.
2. Suppose we have to assign float value then we must use ‘f’ or ‘F’ literal to
specify that current value is “Float”.
3. Specify “E” or “e” for values which contain exponent.
How to Declare Double Variable
Class FloatDemo
{
public static void main(String args[])
{
double d1 = 10;
System.out.println("Total Number : " + fval);
}
}

How to Declare float Variable


float fval = 10.4F;
Using Exponent In Double Value
float electronMass = 9E-28F;
double lightSpeed = 3.8E8;
Declaring Fix Value
final int meter_in_cm = 100;

Character data Type:


1. In Java, the data type used to store characters is char.
2. Character is 16 bits wide in Java.
3. Java uses Unicode to represent characters.
4. Java support lot of Unicode symbols from many more human languages
for this purpose, it requires 16 bits.
5. The range of a char is 0 to 65,536.
6. There are no negative chars.
What is Unicode?
Unicode defines a fully international character set that can represent all of the
characters found in all human languages.
Integer Value Assigned to Character Data Type
class CharDemo
{
public static void main(String args[])
{
char ch;
ch = 'M';
System.out.println("Character is : " + ch);
}
}
Output :
Character is : M

Integer Value Assigned to Character Data Type


class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;

ch1 = 88; // code for X


ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + "" + ch2);
}
}
Output :
ch1 and ch2: X Y
Incrementing Character Variable

class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'P';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output :
ch1 contains P
ch1 is now Q

Non-primitive Data Types


In java, non-primitive data types are the reference data types or user-created
data types. All non-primitive data types are implemented using object concepts.
Every variable of the non-primitive data type is an object. The non-primitive data
types may use additional methods to perform certain operations. The default
value of non-primitive data type variable is null.
In java, examples of non-primitive data type are String, Arrays, List, Queue,
Stack, Class, Interface, etc.

Primitive Vs Non-primitive Data Types


Primitive Data Type Non-primitive Data Type

These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all


Variables in Java

A variable in Java is a container that holds the value during the execution of Java
program. In other words, Variable is the name of the memory location reserved for storing
value. Each variable in Java has a specific type that determines size of the memory.
The size of the memory reserved depends on the data type.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before use.

How to declare variables?


We can declare variables in java as pictorially depicted below as a visual aid.

From the image, it can be easily perceived that while declaring a variable we need to take
care of two things that while de

Datatype: Type of data that can be stored in this variable.


Dataname: Name given to the variable.

In this way, a name can only be given to a memory location. It can be assigned values in
two ways:
 Variable Initialization
 Assigning value by taking input

How to initialize variables?


It can be perceived with the help of 3 components that are as follows:
 datatype: Type of data that can be stored in this variable.
 variable_name: Name given to the variable.
 value: It is the initial value stored in the variable.

float simpleInterest; // Declaring float variable


int time = 10, speed = 20; // Declaring and
Initializing integer variable
char var = 'h'; // Declaring and Initializing
character variable
Different types of variables:

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.



These variables are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variables only within that block.
 Initialization of the local variable is mandatory before using it in the defined scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor, block, etc.
As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.
3. Static Variables
Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler
will replace the object name with the class name automatically.
 If we access the static variable without the class name, the compiler will
automatically append the class name.

Syntax: Static and instance variables


class GFG
{
static int a; // Static variable
int b; // Instance variable
}
Java Operators
An operator is a symbol used to perform arithmetic and logical operations.
Java provides a rich set of operators.
In java, operators are clasiffied into the following four types.

 Arithmetic Operqators
 Relational (or) Comparision Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators

Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations
like addition, subtraction, multiplication, division, modulus, increment, decrement,
etc.,

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Modulus - Remainder of the Division 5%2=1

++ Increment a++
Example

public class ArithmeticOperators {

public static void main(String[] args) {

int a = 10, b = 20, result;

System.out.println("a = " + a + ", b = " + b);

result = a + b;
System.out.println("Addition : " + a + " + " + b + " = " + result);

result = a - b;
System.out.println("Subtraction : " + a + " - " + b + " = " + result);

result = a * b;
System.out.println("Multiplucation : " + a + " * " + b + " = " + result);

result = b / a;
System.out.println("Division : " + b + " / " + a + " = " + result);

result = b % a;
System.out.println("Modulus : " + b + " % " + a + " = " + result);

result = ++a;
System.out.println("Pre-increment : ++a = " + result);

result = b--;
System.out.println("Post-decrement : b-- = " + result);
}
}

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two
values. That means the relational operators are used to check the
relationship between two values. Every relational operator has two posible
results either true or false. In simple words, the relational operators are
used to define conditions in a program. The following table provides
information about relational operators.

Operator Meaning Example

< Returns TRUE if the first value is smaller than second 10 < 5 is
value otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than second 10 > 5 is
value otherwise returns FALSE TRUE
Operator Meaning Example

<= Returns TRUE if the first value is smaller than or equal 10 <= 5 is
to second value otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal 10 >= 5 is
to second value otherwise returns FALSE TRUE

== Returns TRUE if both values are equal otherwise 10 == 5 is


returns FALSE FALSE

!= Returns TRUE if both values are not equal otherwise 10 != 5 is


returns FALSE TRUE

Example

public class RelationalOperators {

public static void main(String[] args) {


boolean a;

a = 10<5;
System.out.println("10 < 5 is " + a);

a = 10>5;
System.out.println("10 > 5 is " + a);

a = 10<=5;
System.out.println("10 <= 5 is " + a);

a = 10>=5;
System.out.println("10 >= 5 is " + a);

a = 10==5;
System.out.println("10 == 5 is " + a);

a = 10!=5;
System.out.println("10 != 5 is " + a);
}
}
Logical Operators
The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.

Operator Meaning Example

& Logical AND - Returns TRUE if all conditions are TRUE false & true
otherwise returns FALSE => false

| Logical OR - Returns FALSE if all conditions are FALSE false | true


otherwise returns TRUE => true

^ Logical XOR - Returns FALSE if all conditions are same true ^ true =>
otherwise returns TRUE false

! Logical NOT - Returns TRUE if condition is FLASE and !false => true
returns FALSE if it is TRUE

&& short-circuit AND - Similar to Logical AND (&), but false & true
once a decision is finalized it does not evaluate => false
remianing.

|| short-circuit OR - Similar to Logical OR (|), but once a false | true


decision is finalized it does not evaluate remianing. => true

Example

public class LogicalOperators {


public static void main(String[] args) {
int x = 10, y = 20, z = 0;
boolean a = true;
a = x>y && (z=x+y)>15;
System.out.println("a = " + a + ", and z = " + z);
a = x>y & (z=x+y)>15;
System.out.println("a = " + a + ", and z = " + z);
}}
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue)
to the left-hand side variable (Lvalue). The assignment operator is used in
different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable

-= Subtract right-hand side value from left-hand side variable A -= B


value and store the result into left-hand side variable

*= Multiply right-hand side value with left-hand side variable A *= B


value and store the result into left-hand side variable

/= Divide left-hand side variable value with right-hand side A /= B


variable value and store the result into the left-hand side
variable

%= Divide left-hand side variable value with right-hand side A %= B


variable value and store the remainder into the left-hand side
variable

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -


Example

public class AssignmentOperators {

public static void main(String[] args) {

int a = 10, b = 20, c;


boolean x = true;

System.out.println("a = " + a + ", b = " + b);

a += b;
System.out.println("a = " + a);

a -= b;
System.out.println("a = " + a);

a *= b;
System.out.println("a = " + a);

a /= b;
System.out.println("a = " + a);

a %= b;
System.out.println("a = " + a);

x |= (a>b);
System.out.println("x = " + x);

x &= (a>b);
System.out.println("x = " + x);
}
}

Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java
programming language. When we use the bitwise operators, the operations
are performed based on binary values. The following table describes all the
bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0 ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise A|B


it is 1 ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the ~A


bit (Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left A << 2
by the specified number of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions ⇒ 6 (00110)

Example

public class BitwiseOperators {

public static void main(String[] args) {

int a = 25, b = 20;

System.out.println(a + " & " + b + " = " + (a & b));

System.out.println(a + " | " + b + " = " + (a | b));

System.out.println(a + " ^ " + b + " = " + (a ^ b));

System.out.println("~" + a + " = " + ~a);

System.out.println(a + ">>" + 2 + " = " + (a>>2));


System.out.println(a + "<<" + 2 + " = " + (a<<2));

System.out.println(a + ">>>" + 2 + " = " + (a>>>2));


}

Conditional Operators
The conditional operator is also called a ternary operator because it
requires three operands. This operator is used for decision making. In this
operator, first, we verify a condition, then we perform one operation out of
the two operations based on the condition result. If the condition is TRUE
the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.
Syntax

Condition ? TRUE Part : FALSE Part;

Example

public class ConditionalOperator {

public static void main(String[] args) {

int a = 10, b = 20, c;

c = (a>b)? a : b;

System.out.println("c = " + c);


}

}
Control Statements in Java

Conditional control statements in Java. Control statements are also called control
structures or control constructs.

Java supports two kinds of control flow statements:


1. Conditional statements
2. Unconditional statements

A block is a specific kind of statement that encloses a group of statements between braces.
It is represented by an opening brace and closing brace.

The opening brace represents the beginning of block and closing brace specifies the end of
a block. It is used to define the scope of variables and support nesting.

Statements contained within a block is known as embedded statement in java.

Conditional Branching or Conditional Statements in Java

A program that breaks the sequential flow and jumps to another part of the code is called
branching in java. When branching is based on a specific condition, then it is called
conditional branching or conditional statements in Java.

Since the flow of execution is transferred on a particular condition from one part of code to
another part, it is also called conditional execution.

Java supports the following conditional control flow statement:

 if else statement

 do while statement

 while loop

 for loop

 for-each loop

 switch statement
The conditional control flow statement uses the boolean expression for conditional tests. If
there is only a single statement in the conditional control flow statement, braces are
optional.

Braces are mandatory when there is more than one statement within conditional control
flow statement. All conditional control flow statements will be explained in more detail in
the further tutorials.

Unconditional Statements in Java

When the flow of execution jumps to another part of code without carrying out any
conditional test, it is called unconditional statements or unconditional execution in Java.

The following unconditional statements are available in Java:


 break statement
 continue statement
 return statement

If Statement in Java | Example Program

An if statement in Java is the simplest decision-making statement that allows to specify


alternative paths of execution in a program.

It is also called conditional control statement or selection statement in Java.

In other words, if statement executes a set of statements when a condition is true. It is


used to change the flow of the program.

If statement in Java consists of a Boolean expression followed by one or more statements.


The general syntax is as follows:

Here,

a. Condition is a boolean expression that returns a boolean value either true or false.

b. Condition can also include any relational operators to form Boolean expressions that
must be enclosed within parentheses.
c. If the condition is true, then the statement is executed. If the condition is false, then the
statement is bypassed or skipped.

d. If the block of if statement contains more than one statement, must enclose these
statements within a pair of braces ({ }).

Example:

import java.util.Scanner;

class IfStatementTest
{

public static void main(String[] args)


{

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 5) == 0)
{
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}

System.out.println("We are outside the if-block!!!");


}
}

If else in Java

An if else in Java is a two-way conditional statement that decides the execution path
based on whether the condition is true or false.

In other words, if-else statement is used to perform a specific action (task) depending on
whether a specified condition is true or false.

Here, an action signifies a statement or a group of statements.

A one-way if statement executes a statement if and only if the specified condition is true. If
the condition is false, nothing will be done.

But, suppose we want to take alternative actions when the specified condition is false. In
this case, we will use a two-way if-else statement.
Here, each statement represents a single statement or a block of statements enclosed in
curly braces ( { }). The condition is any boolean expression that returns a boolean value.
The else clause is an optional part. It means that we can omit else clause part if not
required. You can follow this convention in all control statements in Java.
Example

import java.util.Scanner;

class IfElseStatementTest
{

public static void main(String[] args)


{

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 2) == 0)
{
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else
{
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}

System.out.println("We are outside the if-block!!!");


}
}

Nested if statement in Java

If an “if statement” is declared inside another if, or if-else statement, it is called nested if
statement in Java. The inner if statement can also have another if statement.
In fact, there is no limit to the depth of the nesting. Nested if statements are very common
in java programming.
The general syntax:
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
}
}

Example:

import java.util.Scanner;

class NestedIfStatementTest
{

public static void main(String[] args)


{

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if (num < 100)


{
System.out.println("\nGiven number is below 100");
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
}
else
System.out.println("Given number is not below 100");

System.out.println("\nWe are outside the if-block!!!");

}
}

if-else if Ladder Statements in Java

if-else if ladder in Java is a multi-way decision structure that is used to decide among three
or more actions.
The general syntax:

if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
statement3;
...
else
statement4;
In the above syntax, there can be multiple else if clauses and the last else clause is
optional.

How if-else if Ladder works

if-else if ladder works in the following steps that are as follows:

1. The first specified condition evaluates to true. If the condition is true, statement1 will
execute and the rest part of else if ladder will bypass.

2. If the specified condition is false, the second if condition evaluates to true. If the second
condition is true, statement2 will execute, and the rest part of the ladder will bypass.

3. If the second condition is false, the third condition and the rest of the conditions (if
required) are evaluated (or tested) until a condition is met or all of the conditions prove to
be false.

4. If all of the conditions are false, the final else statement (i.e. statement4) associated with
the top if statement will be executed.

5. The statement associated with final else acts as a default condition. That is, if all of the
above conditional tests fail, the statement associated with the last else will be executed.

If there is no final else statement and none of the conditions is true, no action will take
place.
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
// Create an object of Scanner class to take the input.
Scanner sc = new Scanner(System.in);

System.out.println("Enter your total marks of 5 subjects:");


int totalMarks = sc.nextInt();

float myPer = totalMarks/5;


System.out.println("Percentage is: " +myPer);

if (myPer >= 90.0)


System.out.print("Grade A");
else if (myPer >= 80.0)
System.out.print("Grade B");
else if (myPer >= 70.0)
System.out.print("Grade C");
else if (myPer >= 60.0)
System.out.print("Grade D");
else
System.out.print("Grade F");
}
}

switch statement in java

A switch statement in Java is a conditional control statement (or multiway decision


statement) that executes one statement from multiple conditions.

It uses the result of an expression to evaluate which statements to execute. It is an


alternative to if-else-if ladder statement.

In other words, a switch statement executes statements based on the value of a variable or
an expression, against a list of case values.

If a match is found, a block of statements corresponding to that case is executed.

Example:
import java.util.Scanner;

class SwitchStatementTest
{

public static void main(String[] args)


{

Scanner read = new Scanner(System.in);


System.out.print("Press any digit: ");

int value = read.nextInt();

switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}

Loops in Java are the processes that execute a block of statements repeatedly until a
termination condition is met.

In simple words, a loop in java is used to execute the same block of statements repeatedly.
Each execution of the loop is called iteration in java.

The block of statements can be executed any number of times, from zero to infinite number
depending on the requirement.

Types of Loops in Java

1. while loop
2. do-while loop
3. for loop
4. foreach loop
While Loop in Java

The while loop in Java is the most fundamental loop statement that repeats a statement
or series of statements as long as the specified conditional expression evaluates to true.

Java while loop is the simplest of all the looping structures. It is an entry-controlled loop
statement.

In the entry-controlled loop, the test condition evaluates first. If the specified condition is
true, then the body of loop executes.

If the conditional expression does not satisfy, then the body of loop will not execute.

Example:

class WhileTest
{

public static void main(String[] args)


{
int num = 1;

while(num <= 10) {


System.out.println(num);
num++;
}

System.out.println("Statement after while!");


}
}
Do While Loop in Java

A do-while loop in Java is a variant form of while loop. It is the same as a while loop,
except that it executes the body of the loop first and then evaluates the loop continuation
condition.

In the while loop statement, the test condition evaluates first before the loop body executes.
If the condition is initially false, the body of loop will not execute at all.

However, sometimes, it might need to execute the body of a loop at least once before the
test performs. We can handle such situations with the help of do-while loop in Java.

The do-while loop always executes its body at least once before the test evaluates because
its test conditional expression is at the bottom of the loop.

Example:

class DoWhileTest
{
public static void main(String[] args)
{
int num = 1;

do
{
System.out.println(num);
num++;
}while(num <= 10);

System.out.println("Statement after do-while!");


}
}
For Loop in Java

The for loop in Java is an entry-controlled loop structure that executes a set of statements
a fixed number of times.

The for statement provides a more concise syntax for creating loops. It executes a block of
statements as long as the condition is true.

In for-statement, the execution begins with the initialization statement. After the
initialization statement, it executes Condition. If the condition is evaluated to true, then
the block of statements executed otherwise it terminates the for-statement. After the block
of statements execution, the modification statement gets executed, followed by condition
again.

Example:

class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}

for-each statement in java

The for each loop in Java (also referred to as enhanced for loop) is an extended feature of
Java language that was introduced with the J2SE 5.0 release.

This feature is specially designed to retrieve elements of the array efficiently rather than
using array indexes.

Java for-each loop can also be used to retrieve elements of a collection. A collection
represents a group of elements as integer values, strings, or objects.

Enhanced for loop repeatedly executes a group of statements for each element of the
collection. It can execute as many times as a number of elements in the collection.

class ForEachTest {

public static void main(String[] args) {

int[] arrayList = {10, 20, 30, 40, 50};

for(int i : arrayList) {
System.out.println("i = " + i);
}

System.out.println("Statement after for-each!");


}

}
Nested For Loop in Java

Nested for loop in Java means one for statement inside another for statement. In other
words, a for loop nested inside another for loop is called nested for loops.

A nested for loops consists of an outer for loop and one or more inner for loops. Each time
the outer for loop repeats, the inner for loop re-enters and starts a new execution.

That is, each time the control will enter inside the inner for loop when the outer for loop
repeats.

Syntax of Nested for loop in Java

The general syntax:


// Outer for loop.
for ( initialization; test-condition; increment )
{
// Inner for loop.
for ( initialization; test-condition; increment )
{
// statement of inner loop
}

// statement of outer loop

Flowchart
Example:

class Tables
{
public static void main(String[] args)
{
System.out.println("Displaying Tables: ");
// Outer for loop.
for(int i = 1; i <= 3; i++)
{
// Inner for loop.
for(int j = 1; j <= 10; j++)
{
System.out.println(i+ " * " +j+" = "+ (i*j));
}
System.out.println(" ");
}
}
}

Java Jump Statements


The java programming language supports jump statements that used to transfer execution
control from one line to another line. The java programming language provides the
following jump statements.

 break statement
 continue statement
 labelled break and continue statements
 return statement

break statement in java


The break statement in java is used to terminate a switch or looping statement. That
means the break statement is used to come out of a switch statement and a looping
statement like while, do-while, for, and for-each.
🔔 Using the break statement outside the switch or loop statement is not allowed.

The floowing picture depictes the execution flow of the break statement.
Example:

public class JavaBreakStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}

continue statement in java


The continue statement is used to move the execution control to the beginning of the
looping statement. When the continue statement is encountered in a looping statement, the
execution control skips the rest of the statements in the looping block and directly jumps
to the beginning of the loop. The continue statement can be used with looping statements
like while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition. When we use continue statement with for
statement the execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.
Example:

public class JavaContinueStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}

Labelled break and continue statement in java


The java programming langauge does not support goto statement, alternatively, the break
and continue statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled
contonue statement takes the execution control to the beginning of a loop with specified
label.

import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {

Scanner read = new Scanner(System.in);

reading: for (int i = 1; i <= 3; i++) {


System.out.print("Enter a even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more
options...");
continue reading;
}
}
}
}

return statement in java


In java, the return statement used to terminate a method with or without a value. The
return statement takes the execution control to the calling function. That means the return
statement transfer the execution control from called function to the calling function by
carrying a value.
🔔 Java allows the use of return-statement with both, with and without return type
methods.

In java, the return statement used with both methods with and without return type. In the
case of a method with the return type, the return statement is mandatory, and it is
optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But,
when it is used without a return type, it does not carry any value. Instead, simply transfers
the execution control.

Eaxmple:
import java.util.Scanner;
public class JavaReturnStatementExample {

int value;

int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt();
}

void showValue(int value) {


for(int i = 0; i <= value; i++) {
if(i == 5)
return;
System.out.println(i);
}
}

public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();

obj.showValue(obj.readValue());

}
}
Scanner Class in Java
In Java, Scanner is a class in java.util package used for obtaining the input
of the primitive types like int, double, etc. and strings. Using the
Scanner class in Java is the easiest way to read input in a Java program,
though not very efficient if you want an input method for scenarios where
time is a constraint like in competitive programming.
Java Scanner Input Types
Scanner class helps to take the standard input stream in Java. So, we need
some methods to extract data from the stream. Methods used for extracting
data are mentioned below:

Method Description

Used for reading Boolean value


nextBoolean()

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value

nextLine() Used for reading Line value

nextLong() Used for reading Long value

nextShort() Used for reading Short value


Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9
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.

In Java, array is an object of a dynamically generated class. Java array


inherits the Object class, and implements the Serializable as well as
Cloneable interfaces.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array.
It doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

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

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization


For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each
loop prints the array elements one by one. It holds an array element in a
variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array)
{
//body of the loop
}

Example:
//Java Program to print the array elements using for-each loop
class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}

Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to


declare the array while passing an array to the method.

Example:
public class TestAnonymousArray
{
//creating a method which receives an array as a parameter
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[])


{
printArray(new int[]{10,22,44,66});//passing anonymous array t
o method
}
}
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

dataType[][] arrayRefVar; (or)


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

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example of Multidimensional Java 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();
}
}
}
What is a class in Java

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

class <class_name>
{
field;
method;
}

Instance variable in Java

A variable which is created inside the class but outside the method is known as
an instance variable. Instance variable doesn't get memory at compile
time. It gets memory at runtime when an object or instance is created. That is
why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behavior of an


object.

Advantage of Method

o Code Reusability
o Code Optimization
new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members
id and name. We are creating the object of the Student class by new keyword
and printing the object's value.

Here, we are creating a main() method inside the class.

class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Output:

0
null

Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is
a better approach than previous one. Let's see a simple example, where we are
having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you
define multiple classes in a single Java source file, it is a good idea to save the
file name with the class name which has main() method.

class Student
{
int id;
String name;
}

class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Output:

0
null

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference variable.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

Output:

101 Sonoo

We can also create multiple objects and store information in it through


reference variable.

class Student
{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}

Output:

101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method.
Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.

class Student
{
int rollno;
String name;

void insertRecord(int r, String n)


{
rollno=r;
name=n;
}

void displayInformation()
{
System.out.println(rollno+" "+name);}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Output:

111 Karan
222 Aryan

As you can see in the above figure, object gets the memory in heap memory
area. The reference variable refers to the object allocated in the heap memory
area. Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.
3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Object and Class Example: Employee

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:

55
45

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.

Anonymous object

Anonymous simply means nameless. An object which has no reference is


known as an anonymous object. It can be used at the time of object creation
only.

If you have to use an object only once, an anonymous object is a good


approach. For example:

new Calculation();//anonymous object

Calling method through a reference:

Calculation c=new Calculation();


c.fact(5);

Calling method through an anonymous object

class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}

Output:

Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

int a=10, b=20;

Initialization of refernce variables:

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see the example:

//Java Program to illustrate the use of Rectangle class which


//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:

55
45
Constructors in Java

Constructor is a block of code that initializes the newly created object.


A constructor resembles an instance method in java but it’s not a
method as it doesn’t have a return type. In short constructor and
method are different.

Rules & Characteristics java constructor

 Constructor name must be same as its class name


 An interface cannot have the constructor.
 Constructors cannot be private.
 A constructor cannot be abstract, static, final, native, strictfp, or
synchronized
 A constructor can be overloaded.
 Constructors cannot return a value.
 Constructors do not have a return type; not even void.
 An abstract class can have the constructor.
 Constructors are automatically called when an object is created.

Example:
Types of Constructors

There are three types of constructors: Default, No-arg constructor and


Parameterized.

Default constructor

If you do not implement any constructor in your class, Java compiler inserts
a default constructor into your code on your behalf. This constructor is
known as default constructor.

no-arg constructor:

Constructor with no arguments is known as no-arg constructor.

Example: no-arg constructor

class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known


as Parameterized constructor.

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}
Output:

Id: 10245 Name: Chaitanya


Id: 92232 Name: Negan

Constructors Overloading in Java

Similar to Java method overloading, we can also create two or more


constructors with different parameters. This is called constructors
overloading.
Example of Constructor Overloading
//Java program to overload constructors
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Java Copy Constructor
A copy constructor is used for copying the values of one object to another
object. Java doesn’t have a concept of copy constructor like C++, however
there are certain ways by which you can copy the values of one object to
another object:

 By creating a parameterized constructor with class reference as


parameter.
 By using clone() method of the Object class.
 By assigning the values from one object to another object.
class JavaExample{
String web;
JavaExample(String w){
web = w;
}

/* This is the Copy Constructor, it


* copies the values of one object
* to the another object (the object
* that invokes this constructor)
*/
JavaExample(JavaExample je){
web = je.web;
}
void disp(){
System.out.println("Website: "+web);
}

public static void main(String args[]){


JavaExample obj1 = new JavaExample("BeginnersBook");

/* Passing the object as an argument to the constructor


* This will invoke the copy constructor
*/
JavaExample obj2 = new JavaExample(obj1);
obj1.disp();
obj2.disp();
}
}
Output:

Website: BeginnersBook
Website: BeginnersBook

Constructor Chaining

When A constructor calls another constructor of same class then this is


called constructor chaining.
Method Overloading in Java

Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input
parameters or type of input parameters, or a mixture of both.
Method overloading is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding in Java. In Method overloading compared
to parent argument, child argument will get the highest priority.

Example:

Output :
30
60
31.0
Different Ways of Method Overloading in Java
 Changing the Number of Parameters.
 Changing Data Types of the Arguments.
 Changing the Order of the Parameters of Methods

1. Changing Number of parameters.


For example: This is a valid case of overloading
add(int, int)
add(int, int, int)

2. Changing Data Types of the Arguments.


For example:
add(int, int)
add(int, float)
3. Changing the Order of the Parameters of Methods
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
Parameters list doesn’t mean the return type of the method, for example if
two methods have same name, same parameters and have different return
type, then this is not a valid method overloading example. This will throw a
compilation error.

int add(int, int)


float add(int, int)
Static Keyword in Java

In Java, static is a keyword that is used for memory management mainly. Static means
single copy storage for variables or methods. The members that are declared with the
static keyword inside a class are called static members in java.
These members can be accessed even if no instance of the class exists because static
members are not tied to a particular instance. They are shared across all instances of
the class.

Features of Static Keyword in Java

There are several important features of static keyword in java.

 Static keyword in Java can be applied with variables, methods, inner classes, and
blocks.
 We cannot declare a class with static keyword but the inner class can be declared as
static.
 It belongs to the class than an instance of the class.
 One basic rule of working with static keyword is that we cannot directly call instance
members within the static area because the static members are linked with the class.
 Static members get memory once when the class is loaded into the memory. But
instance members get the memory after the object creation of the class.

Use of Static Keyword in Java

There are mainly two uses of java static keyword that are as follows:

 The main purpose of using static keyword is that we can access the data, method, or
block of the class without any object creation.
 It is used to make the programs more memory efficient.

Static Variable (Class variable) in Java

If we declare any instance variable with a static modifier, it is known as static variable in
Java. A static variable is also known as class variable in Java. It stores the value for a
variable in a common memory location.

The static variable can be declared in Java as follows:

For example:

1. static int num; // Default access modifier.

2. private static int age; // Private access modifier.

When we declare an instance variable in java, a separate copy will be created for every
object. But in the case of a static variable, a single copy is created at the class level and
shared by all objects of that class.
Key point: A local variable cannot be declared as static. JVM will display modifier error at
compile time.

How to Access Static variable in Java?

There are two ways to access a static variable in Java. They are as follows:
1. A static variable can be accessed inside any other class using the class name. The
general syntax to access a static variable is as follows:
A.x; // A is the class name and "x " is a static variable declared in that class.

2. Static variables can also be accessed by the object reference but an instance variable can
only be accessed by the object reference. For example, We have a class named Student. We
can create the object of the Student class like this:
Student s = new Student();
s.x;

Example:

class Student
{
static int id = 20;

public static void main(String[] args)


{
Student s = new Student();
int x = s.id;

System.out.println(x);
System.out.println(Student.id);
}
}
Output:
20
20

Static Variable Initialization

There are the following important points to keep in mind about static variable initialization
in Java. They are:

 When a class is loaded into the memory at runtime, the static variable is created and
initialized into the common memory location only once. In other words, it gets loaded
into the memory at the time of class loading.

 Static variables in a class are initialized before the creation of any instance of that
class.

 Static variables in a class are initialized before the execution of any static method of
the class. Therefore, we cannot change the initialized value of the static variable
inside the static method.
 If any object changes the value of the static variable, it will retain its value and
increments by 1 for every object creation.

class Counter
{
static int x = 0; // It will get memory only once and retain its value.

Counter()
{
x++; // It will increment the static variable by 1 for each object creation.
}

void display()
{
System.out.println(x);
}

public static void main(String[] args)


{
Counter c1 = new Counter();
c1.display();
Counter c2 = new Counter();
c2.display();
Counter c3 = new Counter();
c3.display();
}
}

Output:
1
2
3
The flow of execution of the above program is shown in the below figure.
Uses of Static Variable in Java with Example

The most common use of a static variable in a class is to hold predefined constant or
unchanging values that are the same for all the instances of the class and will never
change during the execution of the program.

class Employee
{
// Declare instance variables.
String name;
int id;
// Declare a static variable companyName of data type String and assign value IBM which is
common for all the objects.
static String companyName = "IBM";

// Declare a two parameters constructor with parameters named n and i.


Employee(String n, int i)
{
name = n;
id = i;
}
// Declare an instance method display and print the output on the cons ole.
void display()
{
System.out.println("Name: "+name+ " " +"Id = "+id+ " " +"Company Name:"+ " "
+companyName);
}
public static void main(String[] args)
{
// Create the first object of the class and pass two argument values to its constructor.
Employee e = new Employee("Shubh", 123);

// Call the display method using reference variable e.


e.display();

// Similarly, create the second object of the class and pass the two arguments.
Employee e1 = new Employee("Deep", 321);
e1.display();
}
}

Output:
Name: Shubh
Id = 123
Company Name: IBM
Name: Deep
Id = 321
Company Name: IBM

Can we access Instance Members from Static Area Directly?

Instance members (non-static members) can be accessed only from instance area directly.
But we cannot access it from the static area directly.

Can we access Static Variables from Instance and Static Methods?

Yes, static members (static variables) can be accessed from both instance and static area
(i.e. instance and static methods) directly using the class name or without the class name.
But outside the class, we can call only using class name.

How to access Static Variable from another Class?

We can access a static variable in Java by using class name from another class.

How to change value of Static Variable?

We can change the value of the static variable in Java by using a constructor and static
block but not inside a static method.

class Demo
{
static int a = 20;
static int b = 50;
static int c = 100;

Demo()
{
a = 3; // Changed value of variable.
}

static
{
b = 10;
}

void m1()
{
System.out.println(a);
System.out.println(b);
System.out.println(c); // It will print 100.
}

static void m2()


{
c = 200;
}
void m3()
{
c = 200;
}

public static void main(String[] args)


{
Demo d = new Demo();
d.m1();
}

Output:
3
10
100

Advantage of Static variable

Class variable makes program memory efficient. That is, it saves memory. All static
variables are stored in PermGen space of the heap memory.
Static Method in Java | Example Program

When a method is declared with the keyword ‘static’, it is called static method in java.

Like a static variable, static method is also tied to the class, not to an object of class.
Therefore, it can be called and executed without creating objects of the class.

Static method can be called or accessed directly using class name. The syntax to call a
static method in Java is as follows:

className.methodName(); // Here, className is the name of a class.

For example:

Student.add(); // Student is the name of class and add is a method.

A static method is also known as class method in java because it belongs to a class rather
than an individual instance of a class.

Declaration of Static method in Java

The general syntax to declare the static method ( or class method) in java is as follows:
Access_modifier static void methodName()
{ // block start
. . . . . . . . . .
// Method body.
. . . . . . . . . .
} // block end.
The different forms of declaration of a static method with or without return type are shown
in the below figure.
Features of Static method (Class method)

There are several important features of a static method in java that must keep in mind.
They are as follows:
1. A static method in a class can directly access other static members of the class. We do
not need to create an object of class for accessing other static members. It can be called
directly within the same class and outside the class using the class name.
2. It cannot access instance (i.e. non-static) members of a class. The relationship between
instance and static members are summarized in the below figure:

From the figure, it is clear that:

 An instance method can call an instance or static method. It can also access
instance or static data variable.

 A static method can call a static method only. It can only access a static data
variable inside the static method.

 A static method cannot invoke an instance method or access an instance variable.

3. We cannot declare a static method and instance method with the same signature in the
same class hierarchy.

4. When we create a static method in the class, only one copy of the method is created in
the memory and shared by all objects of the class. Whether you create 100 objects or 1
object.

5. A static method in java is also loaded into the memory before the object creation.

6. The static method is always bound with compile time.

7. It cannot refer to this or super in any way.

8. Static methods can be overloaded in Java but cannot be overridden because they are
bound with class, not instance.
9. Static (variable, method, and inner class) are stored in Permanent generation memory
(class memory).

Why Instance variable is not available to Static method?

When we declare a static method in Java, JVM first executes the static method, and then it
creates objects of the class. Since objects are not available at the time of calling the static
method.

Therefore, instance variables are also not available to a static method. Due to which a
static method cannot access an instance variable in the class.

class StaticTest
{
// Instance Area.
static int x = 20; // static variable
int y = 30; // instance variable
// Declare an instance method.
void display()
{
// Instance area. So we can directly call instance variable without using object
reference variable.
System.out.println(x); // Since we can access static member within instance
area. Therefore, we can call the static variable directly.
System.out.println(y);
}
// Declare a static method.
static void show()
{
// Static Area. So we can call S.V. directly inside th e S.M.
System.out.println(x);
// System.out.println(y); // compile time error because instance variable cannot
access inside S.M.
}
public static void main(String[] args)
{
// Create the object of the class.
StaticTest st = new StaticTest();
// Call instance method using reference variable st.
st.display();

// Call static method.


show();
}
}

Output:
20
30
20
The static method can be accessed by nullable reference as:
StaticMethod s1 = null;

s1.show();

class StaticMethod
{
static int a = 10;
void display()
{
System.out.println("This is an instance method");
}
static void show()
{
System.out.println("This is a Static method");
}
public static void main(String[] args)
{
StaticMethod sm = new StaticMethod();
sm.display();
StaticMethod s = null;
s.show();
int c = s.a;
System.out.println(c);
}
}

Output:
This is an Instance method
This is a Static method

How to change value of static variable inside static method?

Static method can access a static variable and can also change its value.
Let’s write a program where we will change the value of static variable inside static method.
Look at the following source code.
Program source code 3:
class ValueChange
{
static int a = 10;
static int change()
{
int a = 20;
return a;
}
public static void main(String[] args)
{
// Call static method using the class name. Since it will return an integer value.
So we will store it by using a changeValue variable.
int changeValue = ValueChange.change();
System.out.println(changeValue);
}
}

Output:
20

Let’s take another program where we will calculate the square and cube of a given number
by using static method.
Program source code 4:
class SquareAndCube
{
static int x = 15;
static int y = 20;
static int square(int x)
{ // Here, x is a local variable.
int a = x * x;
return a;
}
static int cube(int y){ // Here, y is a local variable.
int b = y*y*y;
return b;
}
public static void main(String[] args)
{
int sq = square(5);
int CB = cube(10);
System.out.println(sq);
System.out.println(cb);
}
}

Output:
25
1000

Can we use this or super keyword in static method in Java?

In entire core java, this and super keywords are not allowed inside the static method or
static area.
Super Keyword in Java

The super keyword in Java is a reference variable that is used to refer to parent
class objects. An understanding of Inheritance and Polymorphism is needed in
order to understand the Java super keyword. The keyword “super” came into the
picture with the concept of Inheritance.
Characteristics of super Keyword in Java
In Java, the super keyword is used to refer to the parent class of a subclass. Here
are some of its characteristics:
 super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent class.
 super is used to call a superclass method: A subclass can call a method defined
in its parent class using the super keyword. This is useful when the subclass
wants to invoke the parent class’s implementation of the method in addition to
its own.
 super is used to access a superclass field: A subclass can access a field defined
in its parent class using the super keyword. This is useful when the subclass
wants to reference the parent class’s version of a field.
 super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the
constructor of the subclass.
 super cannot be used in a static context: The super keyword cannot be used in
a static context, such as in a static method or a static variable initializer.
 super is not required to call a superclass method: While it is possible to use the
super keyword to call a method in the parent class, it is not required. If a
method is not overridden in the subclass, then calling it without the super
keyword will invoke the parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
Use of super Keyword in Java
It is majorly used in the following contexts as mentioned below:
 Use of super with variables
 Use of super with methods
 Use of super with constructors
1. Use of super with Variables
This scenario occurs when a derived class and base class has the same data
members. In that case, there is a possibility of ambiguity for the JVM.
We can understand it more clearly using the following example:
Example
Output
Maximum Speed: 120
In the above example, both the base class and subclass have a member maxSpeed.
We could access maxSpeed of base class in subclass using super keyword.
2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent
and child class have the same-named methods then to resolve ambiguity we use the
super keyword.
This code snippet helps to understand the said usage of the super keyword.
Example
Output
This is student class
This is person class

In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of the super keyword, message()
of the superclass could also be invoked.
3. Use of super with constructors
The super keyword can also be used to access the parent class constructor. One
more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending on the situation.
Following is the code snippet to explain the above concept:
Example 1
Output
Person class Constructor
Student class Constructor
In the above example, we have called the superclass constructor using the keyword
‘super’ via subclass constructor.
Example 2
Output
false
Advantages of Using Java super keyword
The super keyword in Java provides several advantages in object-oriented
programming:
 Enables reuse of code: Using the super keyword allows subclasses to inherit
functionality from their parent classes, which promotes the reuse of code and
reduces duplication.
 Supports polymorphism: Because subclasses can override methods and
access fields from their parent classes using super, polymorphism is possible.
This allows for more flexible and extensible code.
 Provides access to parent class behavior: Subclasses can access and use
methods and fields defined in their parent classes through the super keyword,
which allows them to take advantage of existing behavior without having to
reimplement it.
 Allows for customization of behavior: By overriding methods and using
super to call the parent implementation, subclasses can customize and
extend the behavior of their parent classes.
 Facilitates abstraction and encapsulation: The use of super promotes
encapsulation and abstraction by allowing subclasses to focus on their own
behavior while relying on the parent class to handle lower-level details.
Overall, the super keyword is a key feature of inheritance and polymorphism in
Java, and it provides several benefits for developers seeking to write reusable,
extensible, and well-organized code.
Important Points to Remember while using Super Keyword
 Call to super() must be the first statement in the Derived(Student) Class
constructor because if you think about it, it makes sense that the superclass
has no knowledge of any subclass, so any initialization it needs to perform is
separate from and possibly prerequisite to any initialization performed by the
subclass. Therefore, it needs to complete its execution first.
 If a constructor does not explicitly invoke a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass. If the superclass does not have a no-argument constructor, you
will get a compile-time error. The object does have such a constructor, so if
the Object is the only superclass, there is no problem.
Inheritance is a process where child class acquired all the properties and
behaviors of the parent class. Inheritance is used when one object is based
on another object. Here parent class also called a superclass and child class
called a subclass.

For Example, Person is Parent class and Employee is a subclass of Person.


which acquired all the properties and behavior of Person class.

Advantage of inheritance

 Code Reusability
 Runtime Polymorphism/ Method Overriding

Syntax of Inheritance Declaration

class Subclass-name extends Superclass-name


{
//fields
//methods
}

In java, extends keyword is used to inherit a class where a new class derived
properties and methods of an existing class. The class that inherited is
called a Parent/Superclass, and a new derived class is called a
child/subclass.

What You Can Do in a Subclass?

A subclass inherits all of the public and protected members(fields, methods


and nested classes) of its parent class, no matter what package the subclass
is in. If the subclass is in the same package as its parent, it also inherits the
private members of the parent class.

Constructors are not members of the class, so they are not inherited by
child class, but the constructor of the parent class can be invoked from the
child class by using super.
These inherited members can use as-is, replace them, hide them, or
supplement them with new members:

 Parent class inherited fields can be used directly, just like any other
class field.
 You can declare a field in the child class with the same name as the one
in the parent class, thus hiding it (not recommended).
 You can declare new fields in the child class that are not in the parent
class.
 The inherited parent class methods can be used directly as they are.
 You can write a methods in child class that has the same signature as
the one in the parent class. i.e Method Overriding.
 You can write a new static method in the child class with the same
signature as on the parent class, thus hiding it.
 You can declare new methods in the child class that are not in the
parent class.
 You can write a child class constructor that invokes the constructor of
the parent class, either implicitly or by using the keyword super.

Types of inheritance :

 Single Inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Hybrid Inheritance

Single Inheritance

Single inheritance is damn easy to understand. When a class


extends another one class only then we call it a single
inheritance. The below flow diagram shows that class B extends
only one class which is A. Here A is a parent class of B and B
would be a child class of A.
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();
}
}

Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class
extending (Or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base
class or parent. The problem with “multiple inheritance”
is that the derived class will have to manage the
dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in
software projects. Using Multiple inheritance often leads
to problems in the hierarchy. This results in unwanted complexity
when further extending the class.

Note 2: Most of the new OO languages like Small Talk, Java, C# do


not support Multiple inheritance. Multiple Inheritance is supported
in C++.
By using interfaces, we can achieve multiple inheritance in an indirect
way in java

Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology


where one can inherit from a derived class, thereby making this
derived class the base class for the new class. As you can see in
flow diagram C is subclass or child class of B and B is a child
class of A.

class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:

Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub


classes. In below example class B,C and D inherits the same
class A. A is parent class (or base class) of B,C & D.

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:

method of Class A
method of Class A
method of Class A

5) Hybrid Inheritance

In simple terms you can say that Hybrid


inheritance is a combination
of Single and Multiple inheritance. A typical
flow diagram would look like below. A hybrid
inheritance can be achieved in the java in a same
way as multiple inheritance can be!! Using
interfaces. yes you heard it right. By
using interfaces you can have multiple as well
as hybrid inheritance in Java.

class C
{
public void disp()
{
System.out.println("C");
}
}

class A extends C
{
public void disp()
{
System.out.println("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}
Output:

D
Abstract Class in Java

An abstract class in Java is one that is declared with the abstract


keyword. It may have both abstract and non-abstract methods(methods
with bodies). An abstract is a java modifier applicable for classes and
methods in java but not for Variables.

What is Abstract class in Java?

Java abstract class is a class that cannot be initiated by itself, it needs to


be subclassed by another class to use its properties.

Illustration of Abstract class

abstract class Shape


{
int color;
// An abstract function
abstract void draw();
}

In Java, the following some important observations about abstract classes


are as follows:

1. An instance of an abstract class cannot be created.

2. Constructors are allowed.

3. We can have an abstract class without any abstract method.

4. There can be a final method in abstract class but any abstract


method in class(abstract class) can not be declared as final or in
simpler terms final method can not be abstract itself as it will yield an
error: “Illegal combination of modifiers: abstract and final”

5. We can define static methods in an abstract class

6. We can use the abstract keyword for declaring top-level classes


(Outer class) as well as inner classes as abstract

7. If a class contains at least one abstract method then compulsory


should declare a class as abstract

8. If the Child class is unable to provide implementation to all abstract


methods of the Parent class then we should declare that Child class
as abstract so that the next level Child class should provide
implementation to the remaining abstract method
Example

Output
avinash
21
222.2

Properties of Abstract class

Observation 1

In Java, just like in C++ an instance of an abstract class cannot be created,


we can have references to abstract class type though. It is as shown below
via the clean java program.

Example
Output

Derived fun() called

Observation 2

Like C++, an abstract class can contain constructors in Java. And a


constructor of an abstract class is called when an instance of an inherited
class is created. It is as shown in the program below as follows:

Example:
}

Output

Base Constructor Called

Derived Constructor Called

Derived fun() called

Observation 3

In Java, we can have an abstract class without any abstract method.


This allows us to create classes that cannot be instantiated but can
only be inherited. It is as shown below as follows with help of a clean java
program.
Example:

Output

Function of Base class is called

Observation 4

Abstract classes can also have final methods (methods that cannot be
overridden)

Example:
Output

Base fun() called

Observation 5

For any abstract java class we are not allowed to create an object i.e., for an
abstract class instantiation is not possible.
Observation 6

Similar to the interface we can define static methods in an abstract


class that can be called independently without an object.

Output

Geeks for Geeks


Observation 7

We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract

Output

Inside abstract method implementation

Observation 8

If a class contains at least one abstract method then compulsory that


we should declare the class as abstract otherwise we will get a compile-
time error ,If a class contains at least one abstract method then,
implementation is not complete for that class, and hence it is not
recommended to create an object so in order to restrict object creation for
such partial classes we use abstract keyword.

Output

Hello

Observation 9

If the Child class is unable to provide implementation to all abstract


methods of the Parent class then we should declare that Child class as
abstract so that the next level Child class should provide implementation to
the remaining abstract method.
Output

Inside m1

Inside m2

Inside m3

In C++, if a class has at least one pure virtual function, then the class
becomes abstract. Unlike C++, in Java, a separate keyword abstract is used
to make a class abstract.
Packages in Java
A package is a collection of similar types of Java entities such as classes,
interfaces, subclasses, exceptions, errors, and enums. A package can also
contain sub-packages.

Advantages:
There are several advantages of using Java Packages, some of them, are as
follows

 Make easy searching or locating of classes and interfaces.


 Avoid naming conflicts. For example, there can be two classes with the
name Student in two packages, university.csdept.Student and
college.itdept.Student
 Implement data encapsulation (or data-hiding).
 Provide controlled access: The access specifiers protected and default
have access control on package level. A member declared as protected is
accessible by classes within the same package and its subclasses. A
member without any access specifier that is default specifier is accessible
only by classes in the same package.
 Reuse the classes contained in the packages of other programs.
 Uniquely compare the classes in other packages.

Types of Packages in Java

They can be divided into two categories:

 Java API packages or built-in packages and


 User-defined packages.

Predefined Packages in Java (Built-in Packages)


Predefined packages in java are those which are developed by Sun
Microsystem. They are also called built-in packages in java.
These packages consist of a large number of predefined classes, interfaces,
and methods that are used by the programmer to perform any task in his
programs.
Java APIs contains the following predefined packages, as shown in the below
figure:
Core packages:

1. Java.lang: lang stands for language. The Java language package consists
of java classes and interfaces that form the core of the Java language and
the JVM. It is a fundamental package that is useful for writing and
executing all Java programs.

Examples are classes, objects, String, Thread, predefined data types, etc. It
is imported automatically into the Java programs.

2. Java.io: io stands for input and output. It provides a set of I/O streams
that are used to read and write data to files. A stream represents a flow of
data from one place to another place.

3. Java util: util stands for utility. It contains a collection of useful utility
classes and related interfaces that implement data structures like
LinkedList, Dictionary, HashTable, stack, vector, Calender, data utility, etc.

4. Java.net: net stands for network. It contains networking classes and


interfaces for networking operations. The programming related to client-
server can be done by using this package.

Window Toolkit and Applet:

1. Java.awt: awt stands for abstract window toolkit. The Abstract window
toolkit packages contain the GUI(Graphical User Interface) elements such as
buttons, lists, menus, and text areas. Programmers can develop programs
with colorful screens, paintings, and images, etc using this package.

2. Java.awt.image: It contains classes and interfaces for creating images


and colors.

3. Java.applet: It is used for creating applets. Applets are programs that are
executed from the server into the client machine on a network.

4. Java.text: This package contains two important classes such as


DateFormat and NumberFormat. The class DateFormat is used to format
dates and times. The NumberFormat is used to format numeric values.

5. Java.sql: SQL stands for the structured query language. This package is
used in a Java program to connect databases like Oracle or Sybase and
retrieve the data from them.

Importing packages in Java

There are three approaches to import one package into another package in
Java.

1. import package.*;

2. import package.classname;

3. Using fully qualified name.

1. Using package.*

An import is a keyword that is used to make the classes and interfaces of


other packages accessible to the current package. If we use package.*, all
the classes and interfaces of this package can be accessed (imported) from
outside the packages.

Example:

import java.util.*;

2. By using a particular class name after the import statement, we can


access that particular class package but not the sub-packages.

Example:

import java.util.vector;
3. Using a Fully qualified name means we can access the declared class of
different packages without using the import statement.
Example:

Example:

import java.util.*;
public class Add
{
int s;
public void sum()
{
System.out.print("Enter the first number: ");
Scanner scan=new Scanner(System.in);
int x=scan.nextInt();
System.out.print("Enter the second number: ");
Scanner scan1=new Scanner(System.in);
int y=scan1.nextInt();
s=x+y;
System.out.println("sum="+s);
}
}
User-defined Packages

User-defined packages are those packages that are designed or created by


the developer to categorize classes and packages. They are much similar to
the built-in that java offers. It can be imported into other classes and used
the same as we use built-in packages. But If we omit the package statement,
the class names are put into the default package, which has no name.

To create a package, we’re supposed to use the package keyword.

Syntax:

package package-name;

Steps to create User-defined Packages

Step 1: Creating a package in java class. The format is very simple and
easy. Just write a package by following its name.

package example1;

Step 2: Include class in java package, But remember that class only has one
package declaration.

package example1;

class gfg {

public static void main(Strings[] args){

-------function--------

Step 3: Now the user-defined package is successfully created, we can import


it into other packages and use its functions it.

Example:
Output:

Hello geeks!! How are you?

Example 2:

In the below-mentioned example, we’ll import the user-defined package


“example” created in the above example. And use the function to print
messages.

Output:

Hello geeks!! How are you?


Access Protection
What is ‘this’ Keyword in Java?
● Java this keyword returns a reference to the current Object.
● We can access object variable, call the method or constructor of the current
object using this keyword.
● Java ‘this’ keyword can be used to refer to any member of the current object
from within an instance method or a constructor.
● this keyword is mostly used to avoid the confusion between a class attribute
and a parameter. For example, if a parameter of a member function has the
same name as that of an object variable, then the functionality may not
work properly.
1. Using ‘this’ keyword to refer current class instance variables

Output:
a = 10 b = 20

2. Using this() to invoke current class constructor

Output:
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
Output :
Inside show funcion
Inside display function
Output : Value of x in Class B : 5
What is ‘this’ Keyword in Java?
● Java this keyword returns a reference to the current Object.
● We can access object variable, call the method or constructor of the current
object using this keyword.
● Java ‘this’ keyword can be used to refer to any member of the current object
from within an instance method or a constructor.
● this keyword is mostly used to avoid the confusion between a class attribute
and a parameter. For example, if a parameter of a member function has the
same name as that of an object variable, then the functionality may not
work properly.
1. Using ‘this’ keyword to refer current class instance variables

Output:
a = 10 b = 20

2. Using this() to invoke current class constructor

Output:
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
Output :
Inside show funcion
Inside display function
Output : Value of x in Class B : 5
What is Method Overriding

When the child class(subclass) has the method which has the same name, same
parameters and same return type (or covariant return type) as a method in its
parent class(or super-class), then the child method has overridden the parent class
method.

Runtime polymorphism can be achieved through method overriding.

Example of Method Overriding

class Parent {
public void display() {
System.out.println("parent method is executed");
}
}

//Derived or Inherited class


class Child extends Parent {

//Below method overrides the Parent display() method


@Override
public void display() {
System.out.println("child method is executed");
}
}

//Driver class
public class MethodOverriding1 {
public static void main(String args[])
{
// If a Parent type reference refers to a Parent object, then Parent's
// display() is called
Parent parentObject = new Parent();
parentObject.display();

// If a Parent type reference refers to a Child object Child's display()


// is called. This is called RUN TIME POLYMORPHISM.
Parent childObject = new Child();
childObject.display();
}
}

Output :
parent method is executed
child method is executed
Rules for Method Overriding in Java
1. Access Modifiers and Overriding

The access level can't be more restrictive than the overridden method. The access
level can be less restrictive than that of the overridden method.

For example, a protected instance method in the parent class(superclass) can be


made public but not private in the child class(subclass). If you try to make a child
class private then it will give the compile-time error.

Example:
//Base class
class Parent {
//Access modifier of parent's display() method is protected
protected void display() {
System.out.println("parent method is executed");
}
}

//Derived class
class Child extends Parent {

//Below method overrides the Parent display() method


//Access modifier public is less restrictive than protected
@Override
public void display() {
System.out.println("child method is executed");
}
}
//Driver class
public class MethodOverriding2 {
public static void main(String args[])
{
Parent parentObject = new Parent();
parentObject.display();

Parent childObject = new Child();


childObject.display();
}
}

Output :
parent method is executed
child method is executed

2. Private methods can not be overridden

Another rule regarding access modifiers is you can not override private methods
in the parent class. If subclass tries to override the private method of a parent
class then the program will throw a compile-time error as shown below.
//Base class or Superclass
class Parent {
//Access modifier of parent method is private
// This method can not override the child class method
private void display() {
System.out.println("parent method is executed");
}
}

//Derived class or Subclass


class Child extends Parent {

//Below method can not overrides the Parent display() method


//This method is unique to the child class
private void display() {
System.out.println("child method is executed");
}
}
//Driver class
public class MethodOverriding3 {
public static void main(String args[])
{
Parent parentObject = new Parent();
parentObject.display(); // this line when execute will throw compiler error

Parent childObject = new Child();


childObject.display(); // this line when execute will throw compiler error
}
}

3. Final methods can not be overridden in Java


You can not override a method marked final. It will throw a compile-time error if you
try to do so.

// Simple Java program showing final methods cannot be overridden


//Parent class or Superclass
class Parent
{
// Can't be overridden
final void display() { }
}
//Child class or Subclass
class Child extends Parent
{
// This would produce compile time error
void display() { }
}

Output :
/Main.java:13: error: display() in Child cannot override display() in Parent
void display() { }
^
overridden method is final
1 error
4. Static methods can not be overridden
You can not override a method mark static. If you define a static method in the
subclass (child class) with the same method signature as the superclass(parent
class) then it is called method hiding.

//Base class or SuperClass


class Parent {

static void display() {


System.out.println("parent static method is executed");
}

void show() {
System.out.println("parent non-static (instance) method is executed");
}
}

//Derived class or SubClass


class Child extends Parent {

//This method hides the Parent display() method


static void display() {
System.out.println("child static method is executed");
}
// This method overrides the Parent show() method
void show() {
System.out.println("child non-static (instance) method is executed");
}
}

//Driver Class
public class MethodOverriding4 {
public static void main(String args[])
{
Parent childObject = new Child();
// static method can not be overridden,
// so below line calls parent display() method
childObject.display();
// Expected child method will run
childObject.show();
}
}

Output:
parent static method is executed
child non-static (instance) method is executed

5. Invoking a superclass (Parent class) version of overridden method


It's easy to call the superclass(Parent class) version of overridden method by using
the super keyword.
// Invoking SuperClass version of Overridden Method Example

//Base class or SuperClass


class Parent {

void display() {
System.out.println("parent method is executed");
}
}

//Derived class or SubClass


class Child extends Parent {

//This method overrides the Parent display() method


@Override
void display() {
super.display();
System.out.println("child method is executed");
}
}

public class MethodOverriding5 {


public static void main(String args[])
{
Parent childObject = new Child();
childObject.display();
}
}

Output :
parent method is executed
child method is executed

6. Constructor and Overriding


You can not override the constructor as the constructor name of the base class and
child class can never be the same. (Constructor name is always the same as the
class name).
Thread in Java

A thread in Java simply represents a single independent path of execution of a


group of statements. It is the flow of execution, from beginning to end, of a task.
When we write a group of statements in a program, these statements are
executed by JVM one by one. This execution process is called thread in Java.
There is always at least one thread running internally in every program and this
thread is used by JVM to execute statements in the program.
When a program contains a single flow of control, it is called single-threaded
program. In a single thread program, there is a beginning, a body, and an end,
and execute commands sequentially.
We can also create more than one execution thread in a program that can be
used to perform multiple tasks simultaneously.
When we create more than one thread in a program, each thread has its own
path of execution and all the threads share the same memory address space,
data, and code in a program.

What is Process in Java?


Thread in Java is the smallest unit of executable code in a program. It helps to
divide a program into multiple parts to speed up the process.
A process is a program that executes as a single thread. In other words, when
an executable program is loaded into memory, it is called process.
When we will create a new thread in a program, it shares the same memory
address space with other threads in a program whereas every individual
process has its own separate memory address space.
Therefore, creating a thread takes fewer resources than creating a new process.

.
As you can see in the above figure, the thread is executed inside a process and
one process can have also multiple threads. There can be multiple processes
inside the operating system.
Multiple Threads are independent of each other. At a time, only one thread is
executed. If an exception occurs in one thread, it doesn’t affect other threads.
Why Java threads are lightweight process?
Java Threads are also known as lightweight threads or light-weight processes.
It means that they can be executed in the same memory space because all the
threads in the main application program share the same address space in the
memory so that they can easily communicate among themselves. Thus, they
also take less space in memory and less processor time.

Main Thread in Java

Every Java program has always at least one thread, even if you do not create any
thread. This thread is called main thread.
The main thread is also called parent thread and the rest of threads that are
generated from it are called child threads of the program.
Main thread is the last thread to be executed in a program. When main thread
finishes the execution, the program terminates immediately. Whenever Java
program starts, main thread is created automatically.
This main thread is available in all programs. We can control the execution of the
main thread by creating a Thread object and then using methods of Thread class.
To do so, we will have to create a Thread object by calling currentThread() method
of class Thread. A Thread object can be created as follows:
Thread obj = Thread.currentThread();

Since currentThread() method of class Thread is a public static method, therefore,


we can call it using class name.
The currentThread() method returns a reference of current thread on which it is
called. “obj” is a reference variable that is assigned to store the return value of
currentThread() method.
Let’s create a Java program to find the thread used by JVM to execute statements
and display the name of main thread.
Program code:
public class MainThread
{
public static void main(String[] args)
{
// Create a Thread object by calling currentThread() method of class
Thread.
Thread obj = Thread.currentThread();

System.out.println("Current thread is " +obj); // line 8


System.out.println("Name of current thread is " +obj.getName());
}
}
Output:
Current thread is Thread[main,5,main]
Name of current thread is main

public class MainThreadDemo


{
public static void main(String[] args)
{
// Create a Thread object by calling currentThread() method of class
Thread.
Thread obj = Thread.currentThread();
System.out.println("Current thread is " +obj);
System.out.println("Name of current thread is " +obj.getName());

obj.setName("New Thread"); // Changing name of main thread.


System.out.println("Name of current thread after changing name is " +obj);
System.out.println("Main thread existing");
}
}

Output:
Current thread is Thread[main,5,main]
Name of current thread is main
Name of current thread after changing name is Thread[New
Thread,5,main]
Main thread existing
Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:

thread is running...
Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create the Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.

Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined
above.

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");

// the start() method moves the thread to the active state


t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}

Output:
My first thread

Using the Thread Class: Thread(Runnable r, String name)

public class MyThread2 implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ...");
}

// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();

// creating an object of the class Thread using Thread(Runnable r, String name)


Thread th1 = new Thread(r1, "My new thread");

// the start() method moves the thread to the active state


th1.start();

// getting the thread name by invoking the getName() method


String str = th1.getName();
System.out.println(str);
}
}

Output:

My new thread
Now the thread is running ...
Thread States in Java

A thread is a program in execution created to perform a specific task. Life cycle of a Java
thread starts with its birth and ends on its death.

The start() method of the Thread class is used to initiate the execution of a thread and it
goes into runnable state and the sleep() and wait() methods of the Thread class sends the
thread into non runnable state.

After non runnable state, thread again comes into runnable state and starts its execution.
The run() method of thread is very much important. After executing the run() method, the
lifecycle of thread is completed.

All these phases of threads are the states of thread in Java.

To work with threads in a program, it is important to identify thread state. The following
figure shows thread states in Java thread life cycle.

Thread States in Java

A thread is a path of execution in a program that goes through the following states of a
thread. The five states are as follows:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
New (Newborn State)

When an instance of the Thread class is created a new thread is born and is known to be in
New-born state. That is, when a thread is born, it enters into new state but its execution
phase has not been started yet on the instance.

In simpler terms, Thread object is created but it cannot execute any program statement
because it is not in an execution state of the thread. Only start() method can be called on a
new thread; otherwise, an IllegalThreadStateException will be thrown.

Runnable State

The second phase of a new-born thread is the execution phase. When the start() method is
called on a the new instance of a thread, it enters into a runnable state.
In the runnable state, thread is ready for execution and is waiting for availability of the
processor (CPU time). There are many threads that are ready for execution, they all are
waiting in a queue (line).

If all threads have equal priority, a time slot is assigned for each thread execution on the
basis of first-come, first-serve manner by CPU. The process of allocating time to threads is
known as time slicing. A thread can come into runnable state from running, waiting, or
new states.

Running State

Running means Processor (CPU) has allocated time slot to thread for its execution. When
thread scheduler selects a thread from the runnable state for execution, it goes into
running state. Look at the above figure.

In running state, processor gives its time to the thread for execution and executes its run
method. It is the state where thread performs its actual functions. A thread can come into
running state only from runnable state.

A running thread may give up its control in any one of the following situations and can
enter into the blocked state.

1. When sleep() method is invoked on a thread to sleep for specified time period, the
thread is out of queue during this time period. The thread again reenters into the
runnable state as soon as this time period is elapsed.
2. When a thread is suspended using suspend() method for some time in order to
satisfy some conditions. A suspended thread can be revived by using resume()
method.
3. When wait() method is called on a thread to wait for some time. The thread in wait
state can be run again using notify() or notifyAll() method.

Blocked State

A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting


for some time in order to satisfy some condition.
Dead State

A thread dies or moves into dead state automatically when its run() method completes the
execution of statements. That is, a thread is terminated or dead when a thread comes out of
run() method. A thread can also be dead when the stop() method is called.

During the life cycle of thread in Java, a thread moves from one state to another state in a
variety of ways. This is because in multithreading environment, when multiple threads are
executing, only one thread can use CPU at a time.

All other threads live in some other states, either waiting for their turn on CPU or waiting
for satisfying some conditions. Therefore, a thread is always in any of the five states.

Example:
/* Thread 1 */
class Thread1 extends Thread
{
public void run()
{
System.out.println("Thread 1");
System.out.println("i in Thread 1 ");
for (int i = 1; i <= 5; i++)
{
System.out.println("i = " + i);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Thread 1 Completed.");
}
}

/* Thread 2 */
class Thread2 extends Thread
{
public void run()
{
System.out.println("Thread 2");
System.out.println("i in Thread 2 ");
for (int i = 1; i <= 5; i++)
{
System.out.println("i = " + i);
}
System.out.println("Thread 2 Completed.");
}
}

/* Driver code */
public class ThreadDemo
{
public static void main(String[] args) {
// life cycle of Thread
// Thread's New State
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
// Both the above threads are in runnable state
// Running state of Thread1 and Thread2
t1.start();
// Move control to another thread
t2.yield();
// Blocked State Thread1
try
{
t1.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
t2.start();
System.out.println("Main Thread End");
}
}

Output:

Thread 1
i in Thread 1
i=1
Main Thread End
Thread 2
i in Thread 2
i=1
i=2
i=3
i=4
i=5
Thread 2 Completed.
i=2
i=3
i=4
i=5
Thread 1 Completed.
Java - Multithreading
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that
can run concurrently and each part can handle a different task at the same time making
optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where
you can subdivide specific operations within a single application into individual threads.
Each of the threads can run in parallel. The OS divides processing time not only among
different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Thread creation by extending the Thread class:

We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.

Output
Thread 15 is running

Thread 14 is running

Thread 16 is running

Thread 12 is running

Thread 11 is running

Thread 13 is running
Thread 18 is running

Thread 17 is running

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

Output
Thread 13 is running

Thread 11 is running
Thread 12 is running
Thread 15 is running

Thread 14 is running

Thread 18 is running

Thread 17 is running

Thread 16 is running
Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority (known
as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java programmer
can also assign the priorities of a thread explicitly in a Java program.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority
of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method


updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

Three constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


value of MAX_PRIORITY is 10.

Example of priority of a Thread:

import java.lang.*;

public class ThreadPriorityExample extends Thread


{

public void run()


{
System.out.println("Inside the run() method");
}

public static void main(String argvs[])


{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();

System.out.println("Priority of the thread th1 is : " + th1.getPriority());

System.out.println("Priority of the thread th2 is : " + th2.getPriority());


System.out.println("Priority of the thread th2 is : " + th2.getPriority());

th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);

System.out.println("Priority of the thread th1 is : " + th1.getPriority());

System.out.println("Priority of the thread th2 is : " + th2.getPriority());


System.out.println("Priority of the thread th3 is : " + th3.getPriority());

System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

Thread.currentThread().setPriority(10);

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());


}
}

Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Synchronization in Java

Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization?

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data.
It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every
object has a lock associated with it. By convention, a thread that needs consistent access to
an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the


example:

class Table
{
void printTable(int n)
{//method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}

}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5 100 10 200 15 300 20 400 25 500

Java Synchronized Method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.

class Table
{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}

public void run()


{
t.printTable(5);
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5 10 15 20 25 100 200 300 400 500

Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific resource of the
method.

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines,
in such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to Remember

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.
o A Java synchronized block doesn't allow more than one JVM, to provide access
control to a shared resource.
o The system performance may degrade because of the slower working of
synchronized keyword.
o Java synchronized block is more efficient than Java synchronized method.

Syntax

synchronized (object reference expression)


{
//code block
}

Example of Synchronized Block

class Table
{
void printTable(int n)
{
synchronized(this)
{//synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{ this.t=t; }
public void run()
{ t.printTable(5); }
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{ this.t=t; }
public void run()
{ t.printTable(100); }
}

public class TestSynchronizedBlock1


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5 10 15 20 25 100 200 300 400 500


Static Synchronization

If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization

Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In
case of synchronized method and synchronized block there cannot be interference between
t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single
lock. But there can be interference between t1 and t3 or t2 and t4 because t1 acquires
another lock and t3 acquires another lock. We don't want interference between t1 and t3 or
t2 and t4. Static synchronization solves this problem.

Example of Static Synchronization

In this example we have used synchronized keyword on the static method to perform static
synchronization.
class Table
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}

class MyThread1 extends Thread{


public void run(){
Table.printTable(1);
}
}

class MyThread2 extends Thread{


public void run(){
Table.printTable(10);
}
}

class MyThread3 extends Thread{


public void run(){
Table.printTable(100);
}
}

class MyThread4 extends Thread{


public void run(){
Table.printTable(1000);
}
}

public class TestSynchronization4{


public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Test it Now

Output:

1 2 3 4 5 6 7 8 9 10 10 20 30
40 50 60 70 80 90 100 100 200 300 400 500
600 700 800 900 1000 1000 2000 3000 4000
5000 6000 7000 8000 9000 10000
Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads


to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

 wait()
 notify()
 notifyAll()

1) wait() method

The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) notify() method

The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.

Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication


The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of
the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread
class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

Example of Inter Thread Communication in Java

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");

if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread(){
public void run()
{
c.withdraw(15000);
}
}.start();

new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();

}
}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

What is Polling, and what are the problems with it?


The process of testing a condition repeatedly till it becomes true is known as polling.
Polling is usually implemented with the help of loops to check whether a particular
condition is true or not. If it is true, a certain action is taken. This wastes many CPU
cycles and makes the implementation inefficient.
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such


as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will
have different look and feel for the different platforms like Windows, MAC OS,
and Unix. The reason for this is the platforms have different view for their native
components and AWT directly calls the native subroutine that creates those
components.

In simple words, an AWT application will look like a windows application in


Windows OS whereas it will look like a Mac application in the MAC OS.

Java AWT Hierarchy

The hierarchy of Java AWT classes are


shown.

Components

All the elements like the button, text fields,


scroll bars, etc. are called components. In
Java AWT, there are classes for each
component as shown in the diagram. In
order to place every component in a
particular position on a screen, we need to
add them to a container.

Container

The Container is a component in AWT that


can contain another components like buttons, textfields, labels etc. The classes
that extends Container class are known as container such as Frame,
Dialog and Panel.
It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.

Note: A container itself is a component (see the above diagram), therefore


we can add a container inside container.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

Window: The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.

Panel: The Panel is the container that doesn't contain title bar, border or
menu bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components. You can also customize its
components using the Layout Managers.

Dialog: Dialog class has border and title. An instance of the Dialog class
cannot exist without an associated instance of the Frame class.

Frame: The frame is a component that works as the main top-level window of
the GUI application. It is created using the Frame class. For any GUI application,
the first step is to create a frame. There are two methods to create a frame: by
extending the Frame class or by creating an object of Frame class.

The frame is a resizable and movable window. It has the title bar and border
and can have menu bars. The default visibility of a Frame is hidden. The
programmer has to make it visible by using the set Visible method and
providing the value “true” to it.

It can have other components like button, text field, scrollbar etc. Frame is most
widely used container while developing an AWT application.
Difference between Frame and Panel:

The primary difference between these Java


programming languages is that the Panel is an
internal region to a frame or another panel
that helps to group multiple components
together while a Frame is a resizable,
movable independent window with a title
bar which contains all other components.
Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int Sets the size (width and height) of the
height) component.

public void Defines the layout manager for the component.


setLayout(LayoutManager m)

public void setVisible(boolean status) Changes the visibility of the component, by


default false.

Java AWT Example

We can create a GUI using Frame in two ways:

 By extending Frame class


 By creating the instance of Frame class
AWT Example 1: creating Frame by extending Frame class

import java.awt.*;

public class SimpleExample extends Frame{


SimpleExample(){
Button b=new Button("Button!!");

// setting button position on screen


b.setBounds(50,50,50,50);

//adding button into frame


add(b);

//Setting Frame width and height


setSize(500,300);

//Setting the title of Frame


setTitle("This is my First AWT example");

//Setting the layout for the Frame


setLayout(new FlowLayout());

/* By default frame is not visible


so we are setting the
visibility to true
to make it visible. */
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}
AWT Example 2: creating Frame by creating instance of Frame class

import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();

//Creating a label
Label lb = new Label("UserId: ");

//adding label to the frame


fr.add(lb);

//Creating Text Field


TextField t = new TextField();

//adding text field to the frame


fr.add(t);

//setting frame size


fr.setSize(500, 300);

//Setting the layout for the Frame


fr.setLayout(new FlowLayout());

fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
Output:
import java.awt.*;

class AWTExample2
{

AWTExample2()
{

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

f.setTitle("Employee info");

f.setLayout(null);

f.setVisible(true);
}

// main method
public static void main(String args[])
{

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
}
Java GUI Event Handling: Any program that uses GUI (graphical user interface)
such as Java application written for windows, is event driven. Event describes
the change in state of any object. For Example : Pressing a button, Entering a
character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling

Event handling has three main components,

 Events : An event is a change in state of an object.

 Events Source : Event source is an object that generates an event.

 Listeners : A listener is an object that listens to the event. A listener gets


notified when an event occurs.

How Events are handled?


A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and
then return. Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.

Important Event Classes and Interface

Event Classes Description Listener Interface

generated when button is pressed,


ActionEvent menu-item is selected, list-item is ActionListener
double clicked

generated when mouse is dragged,


moved,clicked,pressed or released
MouseEvent MouseListener
and also when it enters or exit a
component
generated when input is received
KeyEvent KeyListener
from keyboard

generated when check-box or list


ItemEvent ItemListener
item is clicked

generated when value of textarea or


TextEvent TextListener
textfield is changed

generated when mouse wheel is


MouseWheelEvent MouseWheelListener
moved

generated when window is activated,


WindowEvent deactivated, deiconified, iconified, WindowListener
opened or closed

generated when component is


ComponentEvent ComponentEventListener
hidden, moved, resized or set visible

generated when component is added


ContainerEvent ContainerListener
or removed from container

generated when scroll bar is


AdjustmentEvent AdjustmentListener
manipulated

generated when component gains or


FocusEvent FocusListener
loses keyboard focus
Steps For Handling Events In JAVA

1. Create a class that extends Applet and implements an interface.

class<name> extends Applets implements <interface>

Class Skey extends Applet implements MouseListener

There are different Interfaces for different events i.e.for keyboard->KeyListner,


for Mouse->MouseListner/MouseMotionListner etc.

2. Initialize applet by init method.

init() { }

3. Add or Register the listener to source for receiving notification. Each type of
event has its own listener.

1. add TypeListener(TypeListener);
2. addMouseListener(this);

4. Implement the method to receive and process these notifications.

1. public void method(eventclass obj){}


2. public void mouseEntered(MouseEvent m){}
3. public void mousePressed(MouseEvent m){}
4. public void mouseClicked(MouseEvent m){}
5. public void mouseExited(MouseEvent m){}
6. public void mouseReleased(MouseEvent m){}

Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class
//Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
//create components
tf=new TextField();

//setBounds(int xaxis, int yaxis, int width, int height);

tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
tf.setText("Welcome");
}

public static void main(String args[])


{
new AEvent();
}
}
//Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame
{
TextField tf;

AEvent2()
{

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}

public static void main(String args[])


{
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener
{
AEvent2 obj;
Outer(AEvent2 obj)
{
this.obj=obj;
}
public void actionPerformed(ActionEvent e)
{
obj.tf.setText("welcome");
}
}
//Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame
{
TextField tf;
AEvent3()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener()

public void actionPerformed()


{
tf.setText("hello");
}
}

add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);

public static void main(String args[])


{
new AEvent3();
}
}
Java AWT Button
The Button class is used to implement a GUI push button. It has a label and generates
an event, whenever it is clicked. It extends the Component class and implements the
Accessible interface.

Whenever a button is pushed, it generates an instance of the ActionEvent class. To


perform some functionality on a button click, we need an ActionListener. Any class
implementing the ActionListener interface can be used to handle a button click.

Class constructors

Constructor & Description

Button() : Constructs a button with an empty string for its label.

Button(String text): Constructs a new button with specified label.

Class methods

Method & Description

String getActionCommand() : Returns the command name of the action


event fired by this button.

ActionListener[] getActionListeners(): Returns an array of all the action


listeners registered on this button.

String getLabel() :Gets the label of this button.

protected String paramString() :Returns a string representing the state of


this Button.
void setActionCommand(String command) : Sets the command name for
the action event fired by this button.

void setLabel(String label) :Sets the button's label to be the specified string.

import java.awt.*;
public class CreateButton
{
CreateButton()
{
Frame f = new Frame();
Button b1 = new Button("Button 1");
Button b2 = new Button("B2");
Button b3 = new Button();

b1.setBounds(50,50,100,50);
b2.setBounds(50,100,100,50);
b3.setBounds(150,50,100,100);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);

f.add(b1);
f.add(b2);
f.add(b3);

if(b1.getLabel() == "Button 1")


b3.setLabel("B3");
}
public static void main(String []args)
{
CreateButton b = new CreateButton();
}
}
Java AWT Label

The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.

AWT Label Class Declaration

public class Label extends Component implements Accessible

AWT Label Fields

The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors

Sr. Constructor Description


no.

1. Label() It constructs an empty label.

2. Label(String text) It constructs a label with the given string (left


justified by default).

3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.

Label Class Methods


Sr. Method name Description
no.

1. void setText(String text) It sets the texts for label with the specified text.

2. void setAlignment(int It sets the alignment for label with the specified
alignment) alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

7. protected String It returns the string the state of the label.


paramString()

import java.awt.*;
public class LabelExample
{
public static void main(String args[])
{

Frame f = new Frame ("Label example");


Label l1, l2;

l1 = new Label ("First Label.");


l2 = new Label ("Second Label.");

l1.setBounds(50, 100, 100, 30);


l2.setBounds(50, 150, 100, 30);

f.add(l1);
f.add(l2);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a single
line text and edit it. It inherits TextComponent class, which further
inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed), the
event is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It
can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then
the ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.

AWT TextField Class Declaration


public class TextField extends TextComponent

TextField Class constructors

Sr. Constructor Description


no.

1. TextField() It constructs a new text field component.

2. TextField(String text) It constructs a new text field initialized with the


given string text to be displayed.

3. TextField(int columns) It constructs a new textfield (empty) with given


number of columns.

4. TextField(String text, int It constructs a new text field with the given text and
columns) given number of columns (width).

TextField Class Methods


Sr. Method name Description
no.

It tells whether text field has character set for echoing


1. boolean echoCharIsSet()
or not.

2. int getColumns() It fetches the number of columns in text field.

3. char getEchoChar() It fetches the character that is used for echoing.

void setColumns(int
4. It sets the number of columns in text field.
columns)

void setEchoChar(char
5. It sets the echo character for text field.
c)

It sets the text presented by this text component to the


6. void setText(String t)
specified text.
// Example1
import java.awt.*;
public class TextFieldExample1
{
// main method
public static void main(String args[])
{
// creating a frame
Frame f = new Frame("TextField Example");

// creating objects of textfield


TextField t1, t2;
// instantiating the textfield objects

// setting the location of those objects in the frame


t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// Our class extends Frame class and implements ActionListener interface
public class TextFieldExample2 extends Frame implements ActionListener {
// creating instances of TextField and Button class
TextField tf1, tf2, tf3;
Button b1, b2;
// instantiating using constructor
TextFieldExample2() {
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
// adding action listener
b1.addActionListener(this);
b2.addActionListener(this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on buttons
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
// main method
public static void main(String[] args) {
new TextFieldExample2();
}
}
Label Class:

The object of the Label class is a component for placing text in a container. It
is used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is


accessed. To create a label, we need to create the object of Label class.

Constructors of Label

Constructor Description

public Label() Creates a Label with an empty text.

public Label(String text) Creates a Label with specified text.

public Label(String text, Creates a Label with specified text


int alignment) and alignment.

Label's alignment could be any of these fields -


 Label.RIGHT, to align a label to the right.
 Label.CENTER, to align a label to the left
 Label.LEFT, to align a label to the center.

Methods of Label class

Methods Description

public void
Sets a String message on the Label.
setText(String text)

public String getText() Gets a String message of Label.

void setAlignment(int
Sets an alignment on this label.
alignment)

void int getAlignment() Gets the current alignment of this label


TextField class

The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the
ActionEvent is enabled on the text field, then the ActionEvent may be fired by
pressing return key. The event is handled by the ActionListener interface.

Constructors of TextField

Constructor Description
public TextField) Creates a TextField..
public TextField(String text) Creates a TextField with a specified default text.
public TextField(int width) Creates a TextField with a specified width.
public TextField(String text, int Creates a TextField with a specified default text and
width) width.

Some methods of TextField class

Methods Description
public void setText(String text) Sets a String message on the TextField.
public String getText() Gets a String message of TextField.

public void setEditable(boolean b) Sets a Sets a TextField to editable or uneditable.

public void setFont(Font f) Sets a font type to the TextField


void setForeground(Color c) Sets a foreground color, i.e. color of text in TextField.
import java.awt.*; // setting size, layout and visibility of frame
import java.awt.event.*;
setSize(300,300);
public class TextFieldExample2 extends Fra setLayout(null);
me implements ActionListener setVisible(true);
{ }
TextField tf1, tf2, tf3; public void actionPerformed(ActionEvent e)
Button b1, b2; {
String s1 = tf1.getText();
TextFieldExample2() String s2 = tf2.getText();
{ int a = Integer.parseInt(s1);
tf1 = new TextField(); int b = Integer.parseInt(s2);
tf1.setBounds(50, 50, 150, 20); int c = 0;
tf2 = new TextField(); if (e.getSource() == b1)
tf2.setBounds(50, 100, 150, 20); {
tf3 = new TextField(); c = a + b;
tf3.setBounds(50, 150, 150, 20); }
tf3.setEditable(false); else if (e.getSource() == b2)
b1 = new Button("+"); {
b1.setBounds(50, 200, 50, 50); c = a - b;
b2 = new Button("-"); }
b2.setBounds(120,200,50,50);
String result = String.valueOf(c);
// adding action listener tf3.setText(result);
b1.addActionListener(this); }
b2.addActionListener(this);
// main method
// adding components to frame public static void main(String[] args)
add(tf1); {
add(tf2); new TextFieldExample2();
add(tf3); }
add(b1); }
add(b2);
TextArea class:

The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.

The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps
us to scroll the text up and down, or right and left.

Constructors of TextArea

Constructor Description
public TextArea() Creates a new TextArea..
public TextArea(String text) Creates a new TextArea with specified text.
public TextArea(int rows, int Creates a new TextArea with specified number of rows and
columns) columns.
public TextArea(String text, int Creates a new TextArea with a text and a number of rows and
rows, int columns) columns.

Methods of TextArea class


Methods Description
public void setText(String text) Sets a String message on the TextArea.
public String getText() Gets a String message of TextArea.
public void append(String text) Appends the text to the TextArea.
public int getRows() Gets the total number of rows in TextArea.
public int getColumns() Gets the total number of columns in TextArea.
Button Class: The Button class is used to implement a GUI push button. It has a
label and generates an event, whenever it is clicked.

Whenever a button is pushed, it generates an instance of the ActionEvent class. To


perform some functionality on a button click, we need an ActionListener. Any class
implementing the ActionListener interface can be used to handle a button click.

Constructors of Button

Constructor Description
public Button() Creates a button with no text on it.
public Button(String text) Creates a button with a text on it.

Methods of Button class

Methods Description
public void setText(String
Sets a String message on the Button.
text)
public String getText() Gets a String message of Button.
public void setLabel() Sets a String text on button.
public String getLabel() Gets the String text of this button.
Scrollbar class
Scrollbar class is used to create a horizontal and vertical Scrollbar. A
Scrollbar can be added to a top-level container like Frame or a component like
Panel. Scrollbar class is another component in the AWT package which extends
the Component class.

Constructors of Scrollbar

Constructor Description
public Scrollbar(int orientation, Creates a Scrollbar with the
int value int extent, int min, specified orientation, value, extent,
int max) minimum, and maximum, where -

orientation - This parameter specifies the Scrollbar to be a horizontal or a


vertical Scrollbar.
value - This parameter specifies the starting position of the knob of Scrollbar on
the track of a Scrollbar.
extent - This parameter specified the width of the knob of Scrollbar.
min - This parameter specifies the minimum width of the track on which
Scrollbar moves.
max - This parameter specifies the maximum width of the track.
A few methods of Scrollbar class

Methods Description
public
addAdjustmentListener(AdjustmentListener Adds an AdjustmentListener.
al)
Gets the Scrollbar's current
public int getValue()
position value.
Sets the Scrollbar's current
public int setValue(int value)
position value.
Checkbox class: Checkbox class is used to create a checkbox control, which
contains a box that can be checked or unchecked by clicking on it.
Checkbox is a component which extends Component class and it can be added
to the container like Frame or a component like Panel.

Constructors of Checkbox

Constructor Description
Creates a checkbox with no text, this checkbox is
public Checkbox()
unchecked by default.
Creates a checkbox with a text, this checkbox is
public Checkbox(String text)
unchecked by default.

public Checkbox(String text, Creates a checkbox with a text, this checkbox is


boolean b) checked or unchecked depending on the boolean value.

Checkbox(String label,
Constructs a Checkbox with the specified label, set to
boolean state,
the specified state, and in the specified check box
CheckboxGroup group)
group.

Checkbox(String label,
CheckboxGroup group, Creates a check box with the specified label, in the
boolean state) specified check box group, and set to the specified
state.

Methods of Checkbox class

Methods Description
public void Sets a name on the Checkbox, this name will not
setName(String text) be displayed.
Gets a String message of Checkbox, this name will
public String getName()
not be displayed.
public void setLabel() Sets a String text on button.
public String getLabel() Gets the String text of this button.
public void
Sets a state of Checkbox.
setState(boolean b)
public boolean getState() Gets the state of Checkbox.
CheckboxGroup class: The object of CheckboxGroup class is used to group together a
set of Checkbox. At a time only one check box button is allowed to be in "on" state and
remaining check box button in "off" state. It inherits the object class.
import java.awt.*;
import java.awt.event.*;
public class CBG implements ItemListener
{ public void itemStateChanged(ItemEvent ie)
Frame jf; {
CheckboxGroup cbg; Checkbox ch =(Checkbox)ie.getItemSelectable();
Checkbox winXP, winVista,solaris,mac; if(ch.getState()==true)
Label label1; {
CBG() label1.setText(ch.getLabel()+ " is checked");
{ jf.add(label1);
jf= new Frame("Checkbox"); jf.setVisible(true);
cbg = new CheckboxGroup(); }
label1 = new Label(); }
public static void main(String... ar)
winXP = new Checkbox("Windows XP", cbg, true); {
winVista = new Checkbox("Windows Vista", cbg, false); new CBG();
solaris = new Checkbox("Solaris", cbg, false); }
mac = new Checkbox("Mac OS", cbg, false);
}
jf.add(winXP);
jf.add(winVista);
jf.add(solaris);
jf.add(mac);

winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

jf.setLayout(new FlowLayout());
jf.setSize(232,150);
jf.setVisible(true);
}
List Class:
List class is used to create a list with multiple values, allowing a user to
select any of the values. When a value is selected from List, an ItemEvent is
generated, which is handled by implementing ItemListener interface. List is
another component in AWT which extends Component class.

Constructors of List

Constructor Description
public List() Creates a scrolling list.
public List(int rows) Creates a List with a number of rows.

Creates a List with a number of rows, allowing us to


public List(int rows, boolean mode)
select multiple values from list if mode is true.

Methods of List class

Methods Description
public void add(String item) Adds the item to the end of List.
public void add(String item, int index) Adds the item at a specific index in the list.
Adds a specific ActionListener to listen an Action
public void
event generated when item is selected from this
addActionListener(ActionListener al)
list.
Adds a specific ItemListener to listen an Item
public void
event generated when item is selected from this
addItemListener(ItemListener al)
list.
public String getItem( int index) Gets an item from a specific index in the list.
public String getSelectedItem() Gets the selected item in the list.
public String[] getSelectedItems() Gets the selected item in the list.
public int getRows() Gets the total number of rows in the list.
Choice Class
Choice class is part of Java Abstract Window Toolkit (AWT). The Choice class
presents a pop- up menu for the user, the user may select an item from the
popup menu. The selected item appears on the top. The Choice class inherits
the Component.
Note that you cannot select multiple items from the list. This component is
the best component to use than the check box groups or list because it
consumes less space than these components. It can be created by
instantiating the Choice class.
Choice has only one default constructor, namely the following.
Choice choice = new Choice()

Methods in Choice Class

Method Notes

void addItem(String item) To add items to the choice


void add(String item)

int countItems() Useful for interrogating the Choice contents

String getItem(int index) From 0 to countItems() -1

int getSelectedIndex() Tells which item is selected by number

String getSelectedItem() Returns the selected item’s text

void select(int pos) Make a particular cell the default

void select(String str) Highlight the first cell with text equal to str
import java.awt.*;
import java.awt.event.*; f.add(c);
public class CE implements f.add(label);
ActionListener
f.add(b);
{
Frame f;
f.setSize(400, 400);
Label label;
f.setLayout(null);
Button b;
f.setVisible(true);
Choice c;
CE()
b.addActionListener(this);
{
}
f = new Frame();
Label = new Label();
public void
label.setAlignment(Label.CEN actionPerformed(ActionEvent e)
TER);
{
label.setSize(400, 100);
String data = "Programming
language Selected: "+
c.getItem(c.getSelectedIndex());
b = new Button("Show");
label.setText(data);
b.setBounds(200, 100, 50, 20);
}

c = new Choice();
public static void main(String args[])
c.setBounds(100, 100, 75, 75);
{
new ChoiceExample2();
c.add("C");
}
c.add("C++");
}
c.add("Java");
c.add("PHP");
c.add("Android");
Event Handling in Java:
Event handling is prime to Java programming because it’s integral to the
creation of applets and other sorts of GUI-based programs. Events are
supported by a variety of packages, including java.util, java.awt, and
java.awt.event. The program response is generated when the user interacts with
a GUI-based program.
User interaction with the elements of Graphical User Interface (GUI) of a Java
program leads to events. These elements could be a button, checkbox, radio
button, menu, list, table, scrollbar, mouse, window etc. Such elements are
also known as source of an event and there is a specific class corresponding to
each source and each event.

Some of the events could be


 A click on button, checkbox, radio button.
 Selecting a menuitem or list item.
 Clicking or movement of a mouse.
 Entering or editing the data in a textfield.

Delegation Event Model


Java follows a Delegation Event Model to
handle the such events. The two main
components of this model are as follows

 Source
 Listener

Source
Interaction with a source generates
an event, which is an object of event class
describing the current state of source. A
source must register the listener class that wishes to listen and respond to its
event, by calling a method, which has a general form of

public void addEventTypeListener(EventTypeListener el)

where, EventType could be replaced by the name of the type of event.


For example - A click on a source such as button raises to an event, which is an
object of type ActionEvent class, hence a source button must call its
method addActionListener() to register any class that wishes to listen and
respond to its button event of type ActionEvent.
Listener
The event is delegated to the registered listener classes. In order to listen and
respond to events, such registered listener class must implement
EventTypeListener interface, where, EventType could be replaced by the name of
the type of event.
For example - A class wishing to listen and respond to the a button click
event(which is an object of type ActionEvent), must
implement ActionListener interface.
AWT Event Classes:
Following is the list of commonly used event classes.
Event Classe Description Listener Interface

ActionEvent generated when button is pressed, menu-item is ActionListener


selected, list-item is double clicked.

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released also when the
enters or exit a component.

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is TextListener


changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, deactivated, WindowListener


deiconified, iconified, opened or closed

ComponentEvent generated when component is hidden, moved, ComponentEventListener


resized or set visible

ContainerEvent generated when component is added or removed ContainerListener


from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus
S.NO Event Type Event Listener Methods in interface(Event Handler
method)
1 Action Event ActionListener void actionPerformed(ActionEvent e)
2 Adjustment Event AdjustmentListener void
adjustmentValueChanged(AdjustmentEvent
e)
3 ItemEvent ItemListener void itemStateChanged(ItemEvent e)
4 TextEvent TextListener void textValueChanged(TextEvent e)
5 ComponentEvent ComponentListener void componentHidden(ComponentEvent e)
C void componentMoved(ComponentEvent e)
void componentResized(ComponentEvent e)
void componentShown(ComponentEvent e)
6 KeyEvent KeyListener void keyPressed(KeyEvent e) void
keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
7 MouseEvent MouseListener, void mouseClicked(MouseEvent e)
MouseMotionListener void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseDragged(MouseEvent e)
void mouseMoved(MouseEvent e)
8 ContainerEvent ContainerListener void componentAdded(ContainerEvent e)
void componentRemoved(ContainerEvent e)
9 WindowEvent WindowListener
KeyEvent Class:
An event of type KeyEvent class is generated when a source such as, a key on
the keyboard is pressed , the key is typed and a key is released in
a textfield or in a textarea.
The key Listener interface is handling key events.

Each of the key event handling methods takes a keyEvent object is its
arguments.

A key event object contains information about the key event.

Some methods of KeyEvent class


Method Description

Returns the character associated with the key


public char getKeyChar() pressed on the keyboard, which triggered
the KeyEvent.

Returns an int key code associated with the key


public int getKeyCode() pressed on the keyboard.

Returns true if key pressed was an "action" key,


public boolean i.e. keys that don't generate a character, such
isActionKey() as Cut, Copy, Paste, Page Up, Caps Lock, the
arrow and function keys.

A class to listen and respond to a KeyEvent, must perform the next two
steps -

 It should implement an interface, KeyListener, by providing an


implementation of its three methods –
Method Description

public void keyPressed(KeyEvent This method is called when a key is


e) pressed on the keyboard.

public void This method is called when a key is


keyReleased(KeyEvent ke) released on the keyboard.

This method is called when pressing a key


public void keyTyped(KeyEvent
on they keyboard has resulted in a
ke)
character.

A KeyEvent source which could be a textfield or a textarea, must call its


method -

Method Description

where, object is an object of the class


that has
public void implemented KeyListener interface and
addKeyListener(KeyListener object) wanted to register itself to listen and
respond to ActionEvent generated
when a key is pressed in this source.
MouseEvent and MouseListener
An event of type MouseEvent is generated in a situations when -
 A mouse cursor enters a window area.
 A mouse cursor exists a window area.
 A mouse button is being pressed.
 A mouse button is released.

Some methods of MouseEvent class

Method Description
public int getX() Returns the x-coordinate of the MouseEvent.
public int getY() Returns the y-coordinate of the MouseEvent.

A class to listen & respond to a MouseEvent, must perform the next two
steps -
 It should implement an interface, MouseListener, by providing an
implementation of its methods -

Method Description

public void This method is called when a mouse cursor enters a


mouseEntered(MouseEvent me) window listening for MouseEvent

public void This method is called when a mouse button is being


mousePressed(MouseEvent me) pressed.

public void This method is called when a mouse button was


mouseClicked(MouseEvent me) clicked.

public void
This method is called when a mouse button is
mouseReleased(MouseEvent
released.
me)

public void This method is called when a mouse cursor exists the
mouseExited(MouseEvent me) window.

 A MouseEvent source is a window in which such event is generated, must


call a method -
Method Description
where object is an object of the class that
wants to listen and respond to
public void MouseEvent and has
addMouseListener(ItemListener object) implemented MouseListener interface.
This registers the class to listen &
respond to MouseEvent.

Handling an MouseEvent by implementing MouseListener interface


In the upcoming code, we are going to create a class by
implementing MouseListener interface, to listen to MouseEvent-
 When a mouse cursor is moved in the Frame's window.
 When a mouse cursor is moved out of the Frame's window.
 When a mouse button is pressed within the Frame's window.
 When a mouse button is released within the Frame's window
MouseMotionListener
In order to handle mouse motion events in an appliction i.e. events which are
generated when a mouse is moved, we need to work with MouseEvent class.
An event of type MouseEvent class is generated in mouse motion situations
like -
 When a mouse is moved.
 When a mouse button is being pressed and dragged.

In order to create a class that handles mouse motion events, we need to


understand some important methods of MouseEvent class in the table below.

Some methods of MouseEvent class

Method Description

public Point Returns the absolute x, y position of


getLocationOnScreen() the MouseEvent.

public int getX() Returns the x-coordinate of the MouseEvent.

public int getY() Returns the y-coordinate of the MouseEvent.

A class to listen and respond to event type MouseEvent, must perform


two steps:
 A class that wants to handle and respond to mouse motion events of
type MouseEvent should implement an interface
i.e. MouseMotionListener and also provide implementation of its
methods shown in the table below -

Method Description

public void This method is called when a mouse cursor


mouseMoved(MouseEvent moves in a window listening for mouse motion
me) event of type MouseEvent.

public void This method is called when a mouse cursor is


mouseDragged(MouseEvent being dragged in a window listening for mouse
me) motion event of type MouseEvent.
 A MouseEvent source is a window in which such event is generated,
must call its method -

Method Description

where object is an object of the


class that has
public void implemented MouseMotionListen
addMouseMotionListener(MouseMotionL er interface. Doing this, registers
istener object) the class to listen and respond to
mouse move and
drag MouseEvent.

Handling an MouseEvent by implementing MouseListener interface


In the upcoming example, we are going to handle mouse motion events such as
 When a mouse is moved within the Frame's window area.
 When a mouse button is pressed and dragged within the Frame's
window.
Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner.


The Java LayoutManagers facilitates us to control the positioning and size
of the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are the following
classes that represent the layout managers:

 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north,


south, east, west, and center. Each region (area) may contain one
component only. It is the default layout of a frame or window. The
BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

 BorderLayout(): creates a border layout but with no gaps between the


components.
 BorderLayout(int vgap, int hgap): creates a border layout with the
given horizontal and vertical gaps between the components.
import java.awt.*;
import javax.swing.*;

public class BLManager


{
Frame f;
BLManager()
{
f = new Frame();

// creating buttons
Button b1 = new Button("NORTH");; // the button will be labeled as NORTH
Button b2 = new Button("SOUTH");; // the button will be labeled as SOUTH
Button b3 = new Button("EAST");; // the button will be labeled as EAST
Button b4 = new Button("WEST");; // the button will be labeled as WEST
Button b5 = new Button("CENTER");; // the button will be labeled as CENTER

f.setLayout(new BorderLayout(20, 50));// horizontal gap is 50 and vertical gap is 20

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args)
{
new BLManager();
}
}
Grid Layout Manager

The grid layout manager divides the container into a grid, so that components
can be placed in rows and columns. Each component will have the same width
and height. The components are added to the grid starting at the top-left cell
and proceeding left-to-right, until the row is full. Then go to the next row. This
type of layout is known as, the Grid Layout Manager.
There are 3 types of constructor in Grid Layout. They are as following:

 GridLayout()
 GridLayout(int rows, int columns)
 GridLayout(int rows, int columns, inthgap, int vgap)

import java.awt.*;

public class GridDemo


{
Frame frame1;

GridDemo()
{
frame1=new Frame();

Button box1=new Button("*1*");


Button box2=new Button("*2*");
Button box3=new Button("*3*");
Button box4=new Button("*4*");
Button box5=new Button("*5*");
Button box6=new Button("*6*");
Button box7=new Button("*7*");
Button box8=new Button("*8*");
Button box9=new Button("*9*");

frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);

frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);

}
public static void main(String[] args)
{
new GridDemo();
}

}
Flow Layout manager
The flow layout, is the most basic layout manager in which components are
placed from left to right, as they were added. When the horizontal row is too
small, to put all the components in one row, then it uses multiple rows. You can
align the components left, right, or center (default).
Notice that FlowLayout is the default layout of Panel container.

There are 3 types of constructor in the Flow Layout. They are as following:

 FlowLayout()
 FlowLayout(int align)
 FlowLayout(int align, inthgap, intvgap)

import java.awt.*;

public class FlowDemo


{
Frame frame1;
FlowDemo()
{

frame1=new Frame();

Button box1=new Button("Button1");


Button box2=new Button("Button2");
Button box3=new Button("Button3");
Button box4=new Button("Button4");
Button box5=new Button("Button5");

frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);

frame1.setLayout(new FlowLayout());

frame1.setSize(300,300);
frame1.setVisible(true);
}
public static void main(String[] args)
{
new FlowDemo();
}
}
CardLayout Manager
CardLayout manager is used to position the components in a manner of deck
of cards, with only the card at the top of deck is visible at a time. All the
components of CardLayout Manager are of the type - JPanel and they are
contained in a main parent JPanel container. The layout manager of this main
parent JPanel is set to CardLayout manager.
Constructors of CardLayout

Constructor Description

Creates a CardLayout with gap of size zero


public CardLayout()
between the components..

public
Creates a CardLayout with a specified number of
CardLayout(int hGap,
gap between the components.
int vGap)

CardLayout methods

Methods Description

public void This method flips to the first card in the


first(Component comp) container.

public void This method flips to the next card in the


next(Component comp) container.

public void last(Component This method flips to the last card in the
comp) container.

public void
This method shows a specific card in the
show(Component
container with a specific name.
comp,String name)

public void setHgap(int This method sets the horizontal space between
horizontalGap) components.

public void setVgap(int This method sets the vertical space between
verticalGap) components.

LayoutManager is an interface which is implemented by CardLayout manager


class.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{

CardLayout crd;

JButton btn1, btn2, btn3;


Container cPane;

CardLayoutExample1()
{
cPane = getContentPane();

//default constructor used therefore, components will cover the whole area
crd = new CardLayout();

cPane.setLayout(crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1


cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3

public void actionPerformed(ActionEvent e)


{
// Upon clicking the button, the next card of the container is shown after the
//last card, again, the first card of the container is shown upon clicking

crd.next(cPane);
}

public static void main(String argvs[])


{

CardLayoutExample1 crdl = new CardLayoutExample1();

crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
GridBagLayout Manager

GridBagLayout manager is used to position the components in rows and


columns, where each row may have different number of columns. Each
component added using GridBagLayout can have a different size and positioning
as compared to the other components.

The location, size, alignment, height, width of each component is specified by


using fields provided by GridBagLayout constraints, where constraints are
object of type GridBagConstraints class.

Constructors of GridBagLayout

Constructor Description

public GridBagLayout() Creates a GridBagLayout manager.

Fields of GridBagConstraints class

GridBagLayout Constraints Description

Specifies the location of a component within a cell. Some of


the values it can take -
GridBagConstraints.CENTER
int anchor GridBagConstraints.WEST
GridBagConstraints.EAST
GridBagConstraints.SOUTH
GridBagConstraints.NORTH

Specifies the X-Coordinate to which a component will be


int gridx
added.

Specifies the Y-Coordinate to which a component will be


int gridy
added

int ipadx Specifies the extra horizontal space around the component.

int ipady Specifies the extra vertical space around the component.
int gridheight Specifies the height of the component.

Specifies the width of the component. It can take values :


int gridwidth GridBagConstraints.RELATIVE
GridBagConstraints.REMAINDER

Specifies how a component is resized, if it is small the size of


cell. It can take values of - GridBagConstraints.NONE
int fill GridBagConstraints.HORIZONTAL
GridBagConstraints.VERTICAL
GridBagConstraints.BOTH

A few GridLayout methods

Methods Description

public void setConstraints(Component This method sets the constraints cons to a


comp, GridBagConstraints cons) Component, comp

public GridBagConstraints This method gets the constraints applied to a


getConstraints(Component comp) Component, comp

LayoutManager is an interface which is implemented


by GridBagLayout manager class.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutEx extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutEx a = new GridBagLayoutEx();
}
public GridBagLayoutEx()
{
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);

setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
}
Menu, MenuItems and MenuBar class
 A menu bar can be created
using MenuBar class.

 A menu bar may contain one or


multiple menus, and these menus
are created using Menu class.

 A menu may contain one of multiple


menu items and these menu items
are created using MenuItem class.

Simple constructors of MenuBar, Menu


and MenuItem

Constructor Description

Creates a menu bar to which one or many menus are


public MenuBar()
added.

public Menu(String title) Creates a menu with a title.

public MenuItem(String title) Creates a menu item with a title.


Interface in Java

An interface in Java is syntactically similar to a class but can have only abstract
methods declaration and constants as members.
In other words, an interface is a collection of abstract methods and constants (i.e.
static and final fields). It is used to achieve complete abstraction.
Every interface in java is abstract by default. So, it is not compulsory to write
abstract keyword with an interface.
Once an interface is defined, we can create any number of separate classes and can
provide their own implementation for all the abstract methods defined by an interface.
A class that implements an interface is called implementation class. A class can
implement any number of interfaces in Java.
Every implementation class can have its own implementation for abstract methods
specified in the interface as shown in the below figure.

Since the implementation classes will have all the methods with a body, it is possible to
create an instance of implementation classes.

How to Declare Interface in Java?

In Java, an interface is declared syntactically much like a class. It is declared by using


the keyword interface followed by interface name. It has the following general form:
Syntax
accessModifier interface interfaceName
{
// declare constant fields.
// declare methods that abstract by default.
}
Before interface keyword, we can specify access modifiers such as public, or default with
abstract keyword.
Example:
public abstract interface MyInterfac
{
int x = 10; // public static final keyword invisibly present.
void m1(); // public and abstract keywords invisibly present.
void m2();
}
Java compiler automatically adds public and abstract keywords before to all interface
methods. Moreover, it also adds public, static, and final keywords before interface
variables. Look at the below figure to understand better.

Therefore, all the variables declared in an interface are considered as public, static, and
final by default and acts like constant. We cannot change their value once they
initialized.

Features of Interface

There are the following features of an interface in Java. They are as follows:
1. Interface provides pure abstraction in Java. It also represents the Is-A
relationship.
2. It can contain three types of methods: abstract, default, and static methods.
3. All the (non-default) methods declared in the interface are by default abstract and
public. So, there is no need to write abstract or public modifiers before them.
4. The fields (data members) declared in an interface are by default public, static,
and final. Therefore, they are just public constants. So, we cannot change their
value by implementing class once they are initialized.
5. Interface cannot have constructors.
6. The interface is the only mechanism that allows achieving multiple inheritance
in java.
7. A Java class can implement any number of interfaces by using keyword
implements.
8. Interface can extend an interface and can also extend multiple interfaces.

Rules of Interface in Java

Here are some key points for defining an interface in Java that must be kept in mind.
The rules are as follows:
1. An interface cannot be instantiated directly. But we can create a reference to an
interface that can point to an object of any of its derived types implementing it.
2. An interface may not be declared with final keyword.
3. It cannot have instance variables. If we declare a variable in an interface, it must
be initialized at the time of declaration.
4. A class that implements an interface, must provide its own implementations of
all the methods defined in the interface.
5. We cannot reduce the visibility of an interface method while overriding. That is,
when we implement an interface method, it must be declared as public.
6. It can also be declared with an empty body (i.e. without any members). For
example, java.util package defines EventListener interface without a body.
7. An interface can be declared within another interface or class. Such interfaces
are called nested interfaces in Java.
8. A top-level interface can be public or default with the abstract modifier in its
definition. Therefore, an interface declared with private, protected, or final will
generate a compile-time error.
9. All non-default methods defined in an interface are abstract and public by
default. Therefore, a method defined with private, protected, or final in an
interface will generate compile-time error.
10. If you add any new method in interface, all concrete classes which implement
that interface must provide implementations for newly added method because all
methods in interface are by default abstract.

Extending Interface in Java with Example

Like classes, an interface can also extend another interface. This means that an
interface can be sub interfaces from other interfaces.
The new sub-interface will inherit all members of the super interface similar to
subclasses. It can be done by using the keyword “extends”. It has the following general
form:
Syntax:
interface interfaceName2 extends interfaceName1
{
// body of interfaceName2.
}
Look at the below figure a, b, c, and d to understand better.

Let’s understand the extending interface better with the help of different examples.
1. We can define all the constants in one interface and methods in another interface.
We can use constants in classes where methods are not required. Look at the example
below.
interface A
{
int x = 10;
int y = 20;
}
interface B extends A
{
void show();
}
The interface B would inherit both constants x and y into it.
2. We can also extend various interfaces together by a single interface. The general
declaration is given below:
interface A
{
int x = 20;
int y = 30;
}
interface B extends A
{
void show();
}
interface C extends A, B
{
........
}
Key points:
1. An interface cannot extend classes because it would violate rules that an interface
can have only abstract methods and constants.
2. An interface can extend Interface1, Interface2.

Implementing Interface in Java with Example

An interface is used as “superclass” whose properties are inherited by a class. A class


can implement one or more than one interface by using a keyword implements followed
by a list of interfaces separated by commas.
When a class implements an interface, it must provide an implementation of all methods
declared in the interface and all its super interfaces.
Otherwise, the class must be declared abstract. The general syntax of a class that
implements an interface is as follows:
Syntax:
accessModifier class className implements interfaceName
{
// method implementations;
// member declaration of class;
}
A more general form of interface implementation is given below:
accessModifier class className extends superClass implements interface1,
interface2,.. .
{
// body of className.
}
This general form shows that a class can extend another class while implementing
interfaces.
Key points:
1. All methods of interfaces when implementing in a class must be declared as public
otherwise, you will get a compile-time error if any other modifier is specified.
2. Class extends class implements interface.
3. Class extends class implements Interface1, Interface2…
The implementation of interfaces can have the following general forms as shown in the
below figure.

Accessing Interface Variable in Java

The interface is also used to declare a set of constants that can be used in multiple
classes. The constant values will be available to any classes that implement interface
because it is by default public, static, and final.
We can use values in any method as part of the variable declaration or anywhere in the
class.
Java Interface Example Programs

Program code 1:
public interface ConstantValues
{
// Declaration of interface variables.
int x = 20;
int y = 30;
}
public class Add implements ConstantValues
{
int a = x;
int b = y;
void m1()
{
System.out.println("Value of a: " +a);
System.out.println("Value of b: " +b);
}
void sum()
{
int s = x + y;
System.out.println("Sum: " +s);
}
}
public class Sub implements ConstantValues
{
void sub()
{
int p = y - x;
System.out.println("Sub: " +p);
}
}
public class Test
{
public static void main(String[] args)
{
Add a = new Add();
a.m1();
a.sum();
Sub s = new Sub();
s.sub();
}
}
Output:
Value of a: 20
Value of b: 30
Sum: 50
Sub: 10

Program code 2:
public interface A
{
void msg(); // No body.
}
public class B implements A
{
public void msg()
{
System.out.println("Hello Java");
}
void show()
{
System.out.println("Welcome you");
}
public static void main(String[] args)
{
B b = new B();
b.msg();
b.show(); // A reference of interface is pointing to objects of class B.

A a = new B();
a.msg();

// This statement will generate a compile-time error because


// a reference of interface can only call methods declared in it and implemented
by implementing class.
// a.show();

// show() method is not part of interface. It is part of class B.


// When you will call this method, the compiler will give a compile-time error.
// It can only be called when you create an object reference of class B.
}
}
Output:
Hello Java
Welcome you
Hello Java

Polymorphism in Java Interface

When two or more classes implement the same interface with different implementations,
then through the object of each class, we can achieve polymorphic behavior for a given
interface. This is called polymorphism in interface.
In the above figure, (d) shows polymorphism in interfaces where class B and class C
implement the same interface A.
Program code 3:
public interface Rectangle
{
void calc(int l, int b); // no body.
}
public class RecArea implements Rectangle
{
public void calc(int l, int b)
{
int area = l * b; // Implementation.
System.out.println("Area of rectangle = "+area);
}
}
public class RecPer implements Rectangle
{
public void calc(int l, int b)
{
int perimeter = 2 * (l + b); // Implementation.
System.out.println("Perimeter of rectangle = "+perimeter);
}
}
public class Execution {
public static void main(String[] args)
{
Rectangle rc; // Creating an interface reference.
rc = new RecArea(); // Creating object of RecArea.
rc.calc(20, 30); // calling method.

rc = new RecPer(); // Creating an object of RecPer.


rc.calc(20, 30);
}
}
Output:
Area of rectangle = 600
Perimeter of rectangle = 100

Multilevel Inheritance by Interface

Let’s take an example program in which we will create a multilevel inheritance by


interface. If one interface extends an interface, that interface extends another interface,
and a class implements methods of all interfaces, we can achieve multilevel inheritance
by interfaces.
Program code 4:
public interface Continent
{
void showContinent();
}
public interface Country extends Continent
{
void showCountry();
}
public interface State extends Country
{
void showState();
}
public class City implements State
{
public void showContinent()
{
System.out.println("Asia");
}
public void showCountry()
{
System.out.println("India");
}
public void showState()
{
System.out.println("Jharkhand");
}
void showCity()
{
System.out.println("Dhanbad");
}
public static void main(String[] args)
{
City c = new City();
c.showContinent();
c.showCountry();
c.showState();
c.showCity();
}
}
Output:
Asia
India
Jharkhand
Dhanbad

Multiple Inheritance in Java by Interface

When a class implements more than one interface, or an interface extends more than
one interface, it is called multiple inheritance. Various forms of multiple inheritance
are shown in the following figure.

Program code 5:
public interface Home
{
void homeLoan();
}
public interface Car
{
void carLoan();
}
public interface Education
{
void educationLoan();
}
public class Loan implements Home, Car, Education
{
// Multiple inheritance using multiple interfaces.
public void homeLoan()
{
System.out.println("Rate of interest on home loan is 8.5%");
}
public void carLoan()
{
System.out.println("Rate of interest on car loan is 9.25%");
}
public void educationLoan()
{
System.out.println("Rate of interest on education loan is 10.45%");
}
public static void main(String[] args)
{
Loan l = new Loan();
l.homeLoan();
l.carLoan();
l.educationLoan();
}
}
Output:
Rate of interest on home loan is 8.5%
Rate of interest on car loan is 9.25%
Rate of interest on education loan is 10.45%
What is a Java String?
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. The java.lang.String class
is used to create a Java string object.
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";

Memory Allocation of String:


String str = "Geeks";

There are two ways to create a String object:


By string literal: Java String literal is created by using double quotes.
For Example: String s=“Welcome”;
By new keyword: Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
First thing, java strings are immutable or final, immutable or final means
each time when we are creating or editing or performing any method to
change string, one new string created in string pool.

We can create new string as string literal or by create string object.

Create String literal :

String exampleString=”java”

Each time when we will create string literal, new String object created in String
pool .string value stored in string pool. String pool space is located inside
heap, because of lot use of strings when new string create as string literal.
Java firstly check string pool for string value, if string value exist in string pool
then return reference for that string value, if value not exist then new string
will create inside string pool and return reference for new string value.

Create String Object :

String exampleString = new String(“java”)

If you are creating a new String object by using new operator, then string pool
check will not perform and string object will create in heap memory.
String Methods

Method Description Return


Type

charAt() Returns the character at the specified index char


(position)

compareTo() Compares two strings lexicographically Int

compareToIgnoreCase() Compares two strings lexicographically, int


ignoring case differences

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence boolean


of characters

copyValueOf() Returns a String that represents the String


characters of the character array

endsWith() Checks whether a string ends with the boolean


specified character(s)

equals() Compares two strings. Returns true if the boolean


strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the specified String


locale, format string, and arguments

indexOf() Returns the position of the first found int


occurrence of specified characters in a string

isEmpty() Checks whether a string is empty or not boolean


lastIndexOf() Returns the position of the last found int
occurrence of specified characters in a string

length() Returns the length of a specified string int

replace() Searches a string for a specified value, and String


returns a new string where the specified
values are replaced

replaceFirst() Replaces the first occurrence of a substring String


that matches the given regular expression with
the given replacement

replaceAll() Replaces each substring of this string that String


matches the given regular expression with the
given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified boolean


characters

substring() Extracts the characters from a string, String


beginning at a specified start position, and
through the specified number of character

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the primitive value of a String object String


StringBuffer in Java
StringBuffer in java is used to create modifiable String objects. This means
that we can use StringBuffer to append, reverse, replace, concatenate and
manipulate Strings or sequence of characters. Corresponding methods
under StringBuffer class are respectively created to adhere to these
functions. A StringBuffer is comparatively fast as compared to a string class.
In Java, Strings are known to be immutable or un-editable, unless
overwritten upon. This is where StringBuffer class comes into picture, where it
can accommodate character sequences and still enable a mutable feature.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot
access it simultaneously. So it is safe and will result in an order.
StringBuffer Class Diagram
Constructors in StringBuffer in Java

Constructor Description

StringBuffer() creates an empty string buffer with the initial


capacity of 16.

StringBuffer(String creates a string buffer with the specified


str) string.

StringBuffer(int creates an empty string buffer with the


capacity) specified capacity as length.

Methods of StringBuffer class

1. length(): Returns the StringBuffer object’s length.


2. capacity(): Returns the capacity of the StringBuffer object.

package com.journaldev.java;

public class StringBufferExample {

public static void main(String[] args) {


StringBuffer sb = new StringBuffer("Hello");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is
" + sbLength);
System.out.println("Capacity of " + sb + " is " +
sbCapacity);
}

Output:

String Length of Hello is 5


Capacity of Hello is 21
3. append(): appends the specified argument string representation at the end of
the existing String Buffer. This method is overloaded for all the primitive data
types and Object.

StringBuffer sb = new StringBuffer("Hello ");

sb.append("World ");

sb.append(2017);

System.out.println(sb);

Output: Hello World 2017

4. insert(): insert() method takes two parameters – the index integer value to insert
a value and the value to be inserted. The index tells StringBuffer where to insert
the passed character sequence. Again this method is overloaded to work with
primitive data types and Objects.

StringBuffer sb = new StringBuffer("HelloWorld ");

sb.insert(5, " ");

sb.insert(sb.length(), 2017);

System.out.println(sb);

Output: Hello World 2017

5. reverse(): Reverses the existing String or character sequence content in the buffer
and returns it. The object must have an existing content or else
a NullPointerException is thrown.

StringBuffer sb = new StringBuffer("Hello World");

System.out.println(sb.reverse());

Output: dlroW olleH


6. delete(int startIndex, int endIndex): accepts two integer arguments. The former
serves as the starting delete index and latter as the ending delete index. Therefore
the character sequence between startIndex and endIndex–1 are deleted. The
remaining String content in the buffer is returned.

StringBuffer sb = new StringBuffer("Hello World");

System.out.println(sb.delete(5,11)); //prints Hello

7. deleteCharAt(int index): deletes single character within the String inside


the buffer. The location of the deleted character is determined by the
passed integer index. The remaining String content in the buffer is
returned.

StringBuffer sb = new StringBuffer("Hello World!");

System.out.println(sb.deleteCharAt(11)); //prints "Hello World"

8. replace(int startIndex, int endIndex, String str): Accepts three arguments: first
two being the starting and ending index of the existing String Buffer. Therefore
the character sequence between startIndex and endIndex–1 are removed. Then
the String passed as third argument is inserted at startIndex.

StringBuffer sb = new StringBuffer("Hello World!");

System.out.println(sb.replace(6,11,"Earth")); //prints "Hello


Earth!"
Java StringTokenizer:
In Java, the string tokenizer class allows an application to break a string into
tokens. The tokenization method is much simpler than the one used by
the StreamTokenizer class. The StringTokenizermethods do not distinguish
among identifiers, numbers, and quoted strings, nor do they recognize and
skip comments.
Example:

Constructors:

StringTokenizer(String str) : str is string to be tokenized. Considers default


delimiters like new line, space, tab, carriage return and form feed.

StringTokenizer(String str, String delim) : delim is set of delimiters that are


used to tokenize the given string.

StringTokenizer(String str, String delim, boolean flag): The first two


parameters have same meaning. The flag serves following purpose.

If the flag is false, delimiter characters serve to separate tokens. For example,
if string is "hello geeks" and delimiter is " ", then tokens are "hello" and "geeks".

If the flag is true, delimiter characters are considered to be tokens. For example,
if string is "hello geeks" and delimiter is " ", then tokens are "hello", " " and
"geeks".
Introduction to Java I/O:
 Java I/O (Input and Output) is used to process the input and produce
the output.

 Java uses the concept of stream to make I/O operation fast.

 Java brings various Streams with its I/O package that helps the
user to perform all the input-output operations. These streams
support all the types of objects, data-types, characters, files etc.,
to fully execute the I/O operations.
Stream:
A stream is a sequence of data. In Java a stream is composed of bytes. A stream
is a way of sequentially accessing a file. It's called a stream because it is like a
stream of water that continues to flow.

Programs read inputs from data sources (e.g., keyboard, file, network,
memory buffer, or another program) and write outputs to data sinks (e.g.,
display console, file, network, memory buffer, or another program). In Java
standard I/O, inputs and outputs are handled by the so-called streams.
A stream is a sequential and contiguous one-way flow of data (just like
water or oil flows through the pipe). It is important to mention that Java does
not differentiate between the various types of data sources or sinks (e.g.,
file or network) in stream I/O. They are all treated as a sequential flow of
data. Input and output streams can be established from/to any data
source/sink, such as files, network, keyboard/console or another program. The
Java program receives data from a source by opening an input stream, and
sends data to a sink by opening an output stream. All Java I/O streams are
one-way (except the RandomAccessFile). If your program needs to perform both
input and output, you have to open two streams - an input stream and an
output stream.
Stream I/O operations involve three steps:
1. Open an input/output stream associated with a physical device (e.g., file,
network, console/keyboard), by constructing an appropriate I/O stream
instance.
2. Read from the opened input stream until "end-of-stream" encountered,
or write to the opened output stream (and optionally flush the buffered
output).
3. Close the input/output stream.

In java, three streams are


created for us
automatically(default).
All these streams are
attached with console.

System.out: standard
output stream

System.in: standard input


stream

System.err: standard
error stream

System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.

System.out: This is the standard output stream that is used to produce the
result of a program on an output device like the computer screen.

Here is a list of the various print functions that we use to output statements:

print(): This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method prints
the text on the console and the cursor remains at the end of the text at the
console. The next printing takes place from just here.

Syntax:
System.out.print(parameter);

Example:

println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next line
at the console. The next printing takes place from the next line.
Syntax:

System.out.println(parameter);

Example:
printf(): This is the easiest of all methods as this is similar to printf in C. Note
that System.out.print() and System.out.println() take a single argument, but
printf() may take multiple arguments. This is used to format the output in Java.

Example:
System.err: This is the standard error stream that is used to output all the error
data that a program might throw, on a computer screen or any standard output
device.

This stream also uses all the 3 above-mentioned functions to output the error
data:

 print()
 println()
 printf()

Example:

System is final class from java.lang package(default package in java)


and cannot be instantiated.

out is a static member field of System class and is of


type PrintStream and its access specifiers are public final.
println – is an overloaded method of PrintStream class. println prints the
argument passed to the standard console and a newline. There are
multiple println overloaded methods with different arguments.
Every println makes a call to print method and adds a newline. Internally, print
calls write() and write() takes care of displaying data to the standard output
window.

Types of Streams:

Depending on the type of operations, streams can be divided into two primary
classes:

InputStream
Java application uses an input stream to read data from a source, it may be
a file, an array, peripheral device or socket.

OutputStrem
Java application uses an output stream to write data to a destination, it
may be a file, an array, peripheral device or socket.
InputStream class
InputStream class is an abstract class. It is the super class of all classes
representing an input stream of bytes.

Methods of InputStream

Method Description

public abstract int reads the next byte of data from the input
read()throws IOException stream. It returns -1 at the end of file.

public int available()throws returns an estimate of the number of bytes that


IOException can be read from the current input stream.

public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes
representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.

Methods of OutputStream:

Method Description

public void write(int)throws is used to write a byte to the current output


IOException stream.

public void write(byte[])throws is used to write an array of byte to the current


IOException output stream.

public void flush()throws flushes the current output stream.


IOException

public void close()throws is used to close the current output stream


IOException

OutputStream Hierarchy
Byte Streams and Character Streams:
Java provides I/O Streams to read and write data where, a Stream represents
an input source or an output destination which could be a file, i/o devise, other
program etc.
Based on the data they handle there are two types of streams −

 Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream
classes read/write data of 8 bits. Using these you can store characters,
videos, audios, images etc.
 Character Streams − These handle data in 16 bit Unicode. Using these
you can read and write text data only.

The Reader and Writer classes (abstract) are the super classes of all the character
stream classes: classes that are used to read/write character streams.
Whereas the InputStream and OutputStream classes (abstract) are the super
classes of all the input/output stream classes: classes that are used to
read/write a stream of bytes.
Following diagram illustrates all the input and output Streams (classes) in Java.
Difference between input/output Streams and Readers/Writers
The major difference between these is that the input/output stream classes
read/write byte stream data. Whereas the Reader/Writer classes handle
characters.
The methods of input/output stream classes accept byte array as parameter
whereas the Reader/Writer classes accept character array as parameter.
The Reader/Writer classes handles all the Unicode characters, comes handy for
internalization, comparatively efficient that input/output streams.

When to use Character Stream over Byte Stream?


 In Java, characters are stored using Unicode conventions. Character stream
is useful when we want to process text files. These text files can be processed
character by character. A character size is typically 16 bits.

When to use Byte Stream over Character Stream?


 Byte oriented reads byte by byte. A byte stream is suitable for processing
raw data like binary files.
Reading from an InputStream

The abstract superclass InputStream declares an abstract method read() to


read one data-byte from the input source:

public abstract int read() throws IOException

public int read(byte[] bytes, int offset, int length) throws IOException
// Read "length" number of bytes, store in bytes array starting from offset of
index.

public int read(byte[] bytes) throws IOException


// Same as read(bytes, 0, bytes.length)

Writing to an OutputStream
Similar to the input counterpart,
the abstract superclass OutputStream declares an abstract method write() to
write a data-byte to the output sink. write() takes an int. The least-significant
byte of the int argument is written out; the upper 3 bytes are discarded. It throws
an IOException if I/O error occurs (e.g., output stream has been closed).

public void abstract void write(int unsignedByte) throws IOException


Similar to the read(), two variations of the write() method to write a block of bytes
from a byte-array are implemented:

public void write(byte[] bytes, int offset, int length) throws IOException
// Write "length" number of bytes, from the bytes array starting from offset of
index.
public void write(byte[] bytes) throws IOException
// Same as write(bytes, 0, bytes.length)

Opening & Closing I/O Streams

You open an I/O stream by constructing an instance of the stream. Both the InputStream and
the OutputStream provides a close() method to close the stream, which performs the necessary
clean-up operations to free up the system resources.
public void close() throws IOException // close this Stream
Flushing the OutputStream
In addition, the OutputStream provides a flush() method to flush the remaining bytes from the
output buffer.
public void flush() throws IOException // Flush the output

Implementations of abstract InputStream/OutputStream

InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose
an appropriate concrete subclass to establish a connection to a physical device. For example, you can
instantiate a FileInputStream or FileOutputStream to establish a stream to a physical disk file.

Layered (or Chained) I/O Streams


The I/O streams are often layered or chained with other I/O streams, for purposes such as buffering,
filtering, or data-format conversion (between raw bytes and primitive types). For example, we can layer
a BufferedInputStream to a FileInputStream for buffered input, and stack a DataInputStream in
front for formatted data input (using primitives such as int, double), as illustrated in the following
diagrams.
Vector Class in Java
• It is found in the java.util package and implements
the List interface
• Vector implements List Interface(use methods of List
interface).
• Vector implements a dynamic array that means it
can grow or shrink as required.
• They are very similar to ArrayList but Vector is
synchronized
• It also maintains an insertion order
Vector Class in Java

Constructors:

• Vector(): Creates a default vector of the initial capacity is 10.

• Vector(int size): Creates a vector whose initial capacity is specified by size.

• Vector(int size, int incr): Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate
each time that a vector is resized upward.

• Vector(Collection c): Creates a vector that contains the elements of collection c.


How to create a Vector.
Vector v1 = new Vector(); // create default vector
v1.add(10);
v1.add("geeks");
Vector<Integer> v = new Vector<Integer>(n); // Declaring the Vector with initial size n
v.add(10);
v.add(20);
Vector<Integer> v = new Vector<Integer>(); // Creating an empty Vector
v.add(10);
v.add(20);
Vector<String> v = new Vector(n); // Declaring the Vector with initial size n
v.add(“Ram");
v1.add(“Kumar");
Method & Description
void addElement(Object obj): Adds the specified component to the end of this vector, increasing its size by one.

int capacity(): Returns the current capacity of this vector.

void clear(): Removes all of the elements from this vector.

Object clone(): Returns a clone of this vector.

boolean equals(Object o): Compares the specified Object with this vector for equality.

Object firstElement(): Returns the first component (the item at index 0) of this vector.

Object get(int index): Returns the element at the specified position in this vector.

int indexOf(Object elem): Searches for the first occurence of the given argument, testing for equality using the equals
method.

int indexOf(Object elem, int index): Searches for the first occurence of the given argument, beginning the search at
index, and testing for equality using the equals method.

void insertElementAt(Object obj, int index): Inserts the specified object as a component in this vector at the specified
index.
Method & Description
boolean isEmpty(): Tests if this vector has no components.
Object lastElement(): Returns the last component of the vector.
int lastIndexOf(Object elem): Returns the index of the last occurrence of the specified object in this
vector.
int lastIndexOf(Object elem, int index): Searches backwards for the specified object, starting from the
specified index, and returns an index to it.
Object remove(int index): Removes the element at the specified position in this vector.

boolean remove(Object o): Removes the first occurrence of the specified element in this vector, If the
vector does not contain the element, it is unchanged.

boolean removeAll(Collection c): Removes from this vector all of its elements that are contained in the
specified Collection.
void removeAllElements(): Removes all components from this vector and sets its size to zero.

boolean removeElement(Object obj): Removes the first (lowest-indexed) occurrence of the argument from
this vector.
int size(): Returns the number of components in this vector.
Example
Java Stack

The stack is a linear data structure that is used to store the collection of objects.
It is based on Last-In-First-Out (LIFO). Java collection framework provides
many interfaces and classes to store the collection of objects. One of them is
the Stack class that provides different operations such as push, pop, search,
etc.
Creating a Stack

To create a stack, first, import the java.util package and create an object of the
Stack class.

Stack stk = new Stack();

Stack<type> stk = new Stack<>();

Java Stack Methods

Java Stack extends Vector class with the following five operations only.

 empty(): Tests if this stack is empty.


 peek(): Looks at the object at the top of this stack without removing it from
the stack.
 pop() : Removes the object at the top of this stack and returns that object as
the value of this function.
 push(E item) : Pushes an item onto the top of this stack.
 search(Object o) : Returns the 1-based position where an object is on this
stack.
Example:

import java.util.*;
public class st
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
stk.push("Mac Book");
stk.push("HP");
stk.push("DELL");
stk.push("Asus");

String fruits = stk.peek();


//prints stack
System.out.println("Element at top: " + fruits);

// Checks the Stack is empty or not


boolean rslt=stk.empty();
System.out.println("Is the stack empty or not? " +rslt);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);

System.out.println("Before the pop() method :" + stk);


stk.pop();

System.out.println("After the pop() method : " + stk);


// Search an element
int location = stk.search("HP");
System.out.println("Location of Dell: " + location);
}
}

Output

Element at top: Asus


Is the stack empty or not? false
The stack size is: 4
pop -> Before the pop() method :[Mac Book, HP, DELL, Asus]
After the pop() method : [Mac Book, HP, DELL]
Location of Dell: 2
Hashtable in Java
This class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value.
To successfully store and retrieve objects from a hashtable, the objects used as
keys must implement the hashCode method and the equals method.
 A Hashtable is an array of a list. Each list is known as a bucket. The
position of the bucket is identified by calling the hashcode() method.
A Hashtable contains values based on the key.

 Hashtable uses a hash function to compute an index into an array of


buckets or slots, from which the desired value can be found.

 Java Hashtable class contains unique elements.


 Java Hashtable class doesn't allow null key or value.
 Java Hashtable class is synchronized.
 The initial default capacity of Hashtable class is 11.
Hashtable class declaration

public class Hashtable<K,V> extends Dictionary<K,V> implements


Map<K,V>, Cloneable, Serializable

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

Constructors of Java Hashtable class

Constructor Description

Hashtable() It creates an empty hashtable having the initial


default capacity and load factor.

Hashtable(int capacity) It accepts an integer parameter and creates a


hash table that contains a specified initial
capacity.

Hashtable(int capacity, float It is used to create a hash table having the


loadFactor) specified initial capacity and loadFactor.

Hashtable(Map<? extends It creates a new hash table with the same


K,? extends V> t) mappings as the given Map.
Methods of Java Hashtable class

Method Description

void clear() It is used to reset the hash table.

Object clone() It returns a shallow copy of the


Hashtable.

V compute(K key, BiFunction<? It is used to compute a mapping for the


super K,? super V,? extends V> specified key and its current mapped
remappingFunction) value (or null if there is no current
mapping).

V computeIfAbsent(K key, It is used to compute its value using the


Function<? super K,? extends V> given mapping function, if the specified
mappingFunction) key is not already associated with a value
(or is mapped to null), and enters it into
this map unless null.

V computeIfPresent(K key, It is used to compute a new mapping


BiFunction<? super K,? super V,? given the key and its current mapped
extends V> remappingFunction) value if the value for the specified key is
present and non-null.

Enumeration elements() It returns an enumeration of the values in


the hash table.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings


contained in the map.

boolean equals(Object o) It is used to compare the specified Object


with the Map.

void forEach(BiConsumer<? super It performs the given action for each entry
K,? super V> action) in the map until all entries have been
processed or the action throws an
exception.
V getOrDefault(Object key, V It returns the value to which the specified
defaultValue) key is mapped, or defaultValue if the map
contains no mapping for the key.

int hashCode() It returns the hash code value for the Map

Enumeration<K> keys() It returns an enumeration of the keys in


the hashtable.

Set<K> keySet() It returns a Set view of the keys contained


in the map.

V merge(K key, V value, If the specified key is not already


BiFunction<? super V,? super V,? associated with a value or is associated
extends V> remappingFunction) with null, associates it with the given non-
null value.

V put(K key, V value) It inserts the specified value with the


specified key in the hash table.

void putAll(Map<? extends K,? It is used to copy all the key-value pair
extends V> t)) from map to hashtable.

V putIfAbsent(K key, V value) If the specified key is not already


associated with a value (or is mapped to
null) associates it with the given value
and returns null, else returns the current
value.

boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the
hashtable.

V replace(K key, V value) It replaces the specified value for a


specified key.

boolean replace(K key, V oldValue, It replaces the old value with the new
V newValue) value for a specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the
K,? super V,? extends V> function) result of invoking the given function on
that entry until all entries have been
processed or the function throws an
exception.

String toString() It returns a string representation of the


Hashtable object.

Collection values() It returns a collection view of the values


contained in the map.

boolean contains(Object value) This method returns true if some value


equal to the value exists within the hash
table, else return false.

boolean containsValue(Object This method returns true if some value


value) equal to the value exists within the hash
table, else return false.

boolean containsKey(Object key) This method return true if some key equal
to the key exists within the hash table,
else return false.

boolean isEmpty() This method returns true if the hash table


is empty; returns false if it contains at
least one key.

protected void rehash() It is used to increase the size of the hash


table and rehashes all of its keys.

V get(Object key) This method returns the object that


contains the value associated with the
key.

V remove(Object key) It is used to remove the key and its value.


This method returns the value associated
with the key.
int size() This method returns the number of
entries in the hash table.
Random Class
The Java Random class is a part of the java.util package and contains
inbuilt methods to generate random numbers.
Class declaration
Following is the declaration for java.util.Random class
public class Random
extends Object
implements Serializable

Constructors

Random() : This creates a new random number generator.


Random(long seed): This creates a new random number generator
using a single long seed.

Built-in Methods
The most frequently used built-in methods for generating random
numbers, are the following:

 nextInt(): Returns a random int value within the range: -


2,147,483,648<=value<= 2,147,483, 647

 nextInt(int range): Returns a random int value within the range:


0 <= value < range

 nextDouble(): Returns a random double value within the range:


0.0 <= value < 1.0

 nextFloat(): Returns a random float value within the range:


0.0 <= value < 1.0

 nextLong(): Returns a random long value.


import java.util.Random;

public class RandomDemo


{
public static void main(String[] args)
{
Random random = new Random();
System.out.println(random.nextInt(10));
System.out.println(random.nextBoolean());
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextGaussian());

byte[] bytes = new byte[10];


random.nextBytes(bytes);
System.out.printf("[");
for(int i = 0; i< bytes.length; i++)
{
System.out.printf("%d ", bytes[i]);
}

System.out.printf("]\n");

System.out.println(random.nextLong());
System.out.println(random.nextInt());

}
}
Output
5
true
0.09507979119059662
0.8763395
-2.1809846422230037
[-126 -31 18 -10 -99 34 -39 84 68 -115 ]
-2755864444256421329
-1335486132
Calendar Class in Java with examples

Calendar class in Java is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable, Serializable, Cloneable interfaces.

Class declaration
Following is the declaration for java.util.Calendar class:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>

As it is an Abstract class, so we cannot use a constructor to create an


instance. Instead, we will have to use the static method
Calendar.getInstance() to instantiate and implement a sub-class.
 Calendar.getInstance(): return a Calendar instance based on the
current time in the default time zone with the default locale.
 Calendar.getInstance(TimeZone zone)
 Calendar.getInstance(Locale aLocale)
 Calendar.getInstance(TimeZone zone, Locale aLocale)
Important Methods and their usage

DESCRIPTION
METHOD

It is used to add or subtract the specified

abstract void add(int amount of time to the given calendar field,

field, int amount) based on the calendar’s rules.

It is used to return the value of the given

int get(int field) calendar field.

abstract int It is used to return the maximum value for the

getMaximum(int field) given calendar field of this Calendar instance.

abstract int It is used to return the minimum value for the

getMinimum(int field) given calendar field of this Calendar instance.

It is used to return a Date object representing

Date getTime() this Calendar’s time value.</td


0.
Currency Class
The java.util.Currency class represents a currency.
Currency Class represents a currency. Currencies are identified by their ISO
4217 currency codes. Visit the ISO web site for more information.
Currencies can be represented in the code in two ways: a three-letter
alphabetic code and a three-digit numeric code.
The class is designed so that there's never more than one Currency instance
for any given currency. Therefore, there's no public constructor. You obtain
a Currency instance using the getInstance methods.
Class declaration
Following is the declaration for java.util.Currency class −

public final class Currency extends Object


implements Serializable

Class methods

Method & Description

String getCurrencyCode(): This method gets the ISO 4217 currency


code of this currency.

int getDefaultFractionDigits(): This method gets the default number of


fraction digits used with this currency.

static Currency getInstance(Locale locale): This method returns the


Currency instance for the country of the given locale.

static Currency getInstance(String currencyCode): This method


returns the Currency instance for the given currency code.

String getSymbol(): This method gets the symbol of this currency for the
default locale.

String getSymbol(Locale locale): This method gets the symbol of this


currency for the specified locale.
getAvailableCurrencies() Method

The getAvailableCurrencies() is a method of Java Currency class which is used


to get the set of available currencies. It returns all the currencies which may
include currencies that represent obsolete ISO 4217 codes.

Following is the declaration of getAvailableCurrencies() method:

Public static Set<Currency> getAvailableCurrencies()


Dictionary Class:
The java.util.Dictionary class is the abstract parent of any class, such as
Hashtable, which maps keys to values. Following are the important points
about Dictionary:
 In this class every key and every value is an object.
 In this class object every key is associated with at most one value.

The Dictionary object class is implemented in java.utils.

The following snippet shows the syntax of the Dictionary class.


public abstract class Dictionary extends Object

Constructor and Description


Dictionary(): It’s the default constructor and is the sole constructor for the class.
Since Dictionary class is abstract hence it cannot be instantiated directly. We
need to create the object of the subclass i.e. Hashtable while creating the
instance of the Dictionary class as shown in the below code:
Dictionary object = new Hashtable();
In the above code, we can see while instantiating the Dictionary class the object
of the Hashtable class is created thereby calling the constructor of the Hashtable
class which in turn calls the constructor of the parent class which is the
Dictionary class itself.
Class methods

 Dictionary(): the default constructor.

 elements(): returns the enumeration of all the values in the dictionary.

 isEmpty(): checks whether or not the dictionary is empty.

 keys(): returns the enumeration of all the keys in the dictionary.

 put(K key, V value): adds the key-value pair to the dictionary.

 remove(K key): removes the key-value pair that was mapped with the
specified key.

 get(K key): returns the value that was mapped to the specified key.

 size(): returns the number of key-value pairs in the Dictionary.


OUTPUT
JAVA URL CLASS
Proxy Server

The proxy server is a computer on the internet that accepts the incoming requests from the
client and forwards those requests to the destination server. It works as a gateway between the
end-user and the internet. It has its own IP address. It separates the client system and web
server from the global network.
Mechanism of Proxy Server
The following figure depicts the mechanism of the proxy server.

What is a proxy server and how does it work


The proxy server accepts the request from the client and produces a response based on the
following conditions:
● If the requested data or page already exists in the local cache, the proxy server itself
provides the required retrieval to the client.
● If the requested data or page does not exist in the local cache, the proxy server forwards
that request to the destination server.
● The proxy servers transfer the replies to the client and also being cached to them.

Therefore, it can be said that the proxy server acts as a client as well as the server.
Java Networking

Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.

Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking


Sharing resources
Centralize software management

Java Networking Terminology

● IP Address
● Protocol
● Port Number
● MAC Address
● Connection-oriented and connection-less protocol
● Socket

IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is


composed of octets that range from 0 to 255.

It is a logical address that can be changed.

Protocol
A protocol is a set of rules basically that is followed for communication. For example:

TCP
FTP
Telnet
SMTP
POP etc.

Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.

The port number is associated with the IP address for communication between two applications.

MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not


reliable but fast. The example of connection-less protocol is UDP.

Socket
A socket is an endpoint between two way communications.
What is JavaScript?
JavaScript is a light-weight object-oriented programming language which is
used by several websites for scripting the webpages. It is an interpreted, full-
fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document.
JavaScript was developed by Brendan Eich in 1995. It was introduced to adding
programs to the webpages in the Netscape Navigator browser. Since sthen, it
has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without
reloading the page every time. The traditional website uses to provide several
forms of interactivity and simplicity.
Being a scripting language, JavaScript cannot run on its own. In fact, the
browser is responsible for running JavaScript code. When a user requests an
HTML page with JavaScript in it, the script is sent to the browser and it is up to
the browser to execute it. The main advantage of JavaScript is that all modern
web browsers support (Internet Explorer, Google Chrome, Firefox or any other
browser). Also, JavaScript runs on any operating system including
Windows, Linux or Mac. Thus, JavaScript overcomes the main disadvantages
of VBScript (Now deprecated) which is limited to just IE and Windows.
Although, JavaScript has no connectivity with Java programming language.
The name was suggested and provided in the times when Java was gaining
popularity in the market. In addition to web browsers, databases such as
CouchDB and MongoDB uses JavaScript as their scripting and query
language.

Advantages of JavaScript
 Speed - JavaScript tends to be very fast because it is often run
immediately within the client's browser. So long as it doesn't require
outside resources, JavaScript isn't slowed down by calls to a backend
server. Also, major browsers all support JIT (just in time) compilation for
JavaScript, meaning that there's no need to compile the code before
running it.
 Simplicity - JavaScript's syntax was inspired by Java's and is relatively
easy to learn compared to other popular languages like C++.
 Popularity - JavaScript is everywhere on the web, and with the advent of
Node.js, is increasingly used on the backend. There are countless
resources to learn JavaScript. Both StackOverflow and GitHub show an
increasing amount of projects that use JavaScript, and the traction it's
gained in recent years is only expected to increase.
 Interoperability - Unlike PHP or other scripting languages, JavaScript
can be inserted into any web page. JavaScript can be used in many
different kinds of applications because of support in other languages like
Pearl and PHP.
 Server Load - JavaScript is client-side, so it reduces the demand on
servers overall, and simple applications may not need a server at all.
 Rich interfaces - JavaScript can be used to create features like drag and
drop and components such as sliders, all of which greatly enhance the
user interface and experience of a site.
 Extended Functionality - Developers can extend the functionality of web
pages by writing snippets of JavaScript for third party add-ons like
Greasemonkey.
 Versatility - There are many ways to use JavaScript through Node.js
servers. If you were to bootstrap Node.js with Express, use a document
database like MongoDB, and use JavaScript on the frontend for clients, it
is possible to develop an entire JavaScript app from front to back using
only JavaScript.
 Updates - Since the advent of ECMAScript 5 (the scripting specification
that JavaScript relies on), ECMA International has been dedicated to
updating JavaScript annually. So far, we have received browser support
for ES6 in 2017 and look forward to ES7 being supported in the future.
Disadvantages of JavaScript
 Client-Side Security - Since JavaScript code is executed on the client-
side, bugs and oversights can sometimes be exploited for malicious
purposes. Because of this, some people choose to disable JavaScript
entirely.
 Browser Support - While server-side scripts always produce the same
output, different browsers sometimes interpret JavaScript code differently.
These days the differences are minimal, and you shouldn't have to worry
about it as long as you test your script in all major browsers.
JavaScript Example:
Javascript example is easy to code. JavaScript provides 3 places to put the
JavaScript code: within body tag, within head tag and external JavaScript file.
Let’s create the first JavaScript example.
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>

The script tag specifies that we are using JavaScript.


The text/javascript is the content type that provides information to the browser
about the data.
The document.write() function is used to display dynamic content through
JavaScript.

Three Places to put JavaScript code

 Between the body tag of html


 Between the head tag of html
 In .js file (external javaScript)

Code between the body tag:

In the above example, we have displayed the dynamic content using JavaScript.
Let’s see the simple example of JavaScript that displays alert dialog box.

<body>
<p>Welcome to JavaScript</p>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
Code between the head tag

Let’s see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.

In this example, we are creating a function msg(). To create function in


JavaScript, you need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to
call msg() function.

<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello Javatpoint");
}
</script>
</head>

<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

External JavaScript file

We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in


several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to


embed all JavaScript files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert
dialog box.
message.js

function msg()
{
alert("Hello Javatpoint");
}

Let's include the JavaScript file into html page. It calls the JavaScript
function on button click.

index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>

<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Advantages of External JavaScript

There will be following benefits if a user creates an external javascript:

 It helps in the reusability of code in more than one HTML file.


 It allows easy code readability.
 It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
 It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
 The length of the code reduces as only we need to specify the location of
the js file.
Disadvantages of External JavaScript

There are the following disadvantages of external files:

 The stealer may download the coder's code using the url of the js file.
 If two js files are dependent on one another, then a failure in one file
may affect the execution of the other dependent file.
 The web browser needs to make an additional http request to get the js
code.
 A tiny to a large change in the js code may cause unexpected results in
all its dependent files.
 We need to check each file that depends on the commonly created
external javascript file.
 If it is a few lines of code, then better to implement the internal
javascript code.

JavaScript Comment

The JavaScript comments are meaningful way to deliver message. It is used to


add information about the code, warnings or suggestions so that end user can
easily interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in


the browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code


so that end user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code
being executed. Sometimes, we add the code to perform some action. But
after sometime, there may be need to disable the code. In such case, it is
better to use comments.
Types of JavaScript Comments

There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment

It is represented by double forward slashes (//). It can be used before and after
the statement.

Let’s see the example of single-line comment i.e. added before the statement.

<script>
// It is single line comment
document.write("hello javascript");
</script>

Let’s see the example of single-line comment i.e. added after the statement.

<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>

JavaScript Multi line Comment

It can be used to add single as well as multi line comments. So, it is more
convenient.

It is represented by forward slash with asterisk then asterisk with forward slash.
For example:

/* your code here */

It can be used before, after and middle of the statement.


<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types
of variables in JavaScript: local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as
identifiers).

 Name must start with a letter (a to z or A to Z), underscore( _ ), or


dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are
different variables.

JavaScript Declare Variables

In JavaScript, we use the following keywords to declare variables: var and let. For
example,

var x;
let y;

Here, x and y are variables.


JavaScript var Vs let

Both var and let are used to declare variables. However, there are some
differences between them.

Var let

var is used in the older let is the new way of declaring


versions of JavaScript variables starting ES6 (ES2015).

var is function scoped. let is block scoped.

For example, var x; For example, let y;

Note: It is recommended to use let instead of var. However, there are a few
browsers that do not support let. Visit JavaScript let browser support to learn
more

JavaScript Initialize Variables

We use the assignment operator = to assign a value to a variable.

let x;
x = 5;

Here, 5 is assigned to variable x.

You can also initialize variables during its declaration.

let x = 5;
let y = 6;
In JavaScript, it's possible to declare variables in a single statement.

let x = 5, y = 6, z = 7;

If you use a variable without initializing it, it will have an undefined value.

let x; // x is the name of the variable


document.write(x); // undefined

Here x is the variable name and since it does not contain any value, it will be
undefined.

Change the Value of Variables

It's possible to change the value stored in the variable. For example,

// 5 is assigned to variable x
let x = 5;
document.write(x); // 5

// variable x is changed 3
x = 3;
document.write(x); // 3

The value of a variable may vary. Hence, the name variable.


Rules for Naming JavaScript Variables

The rules for naming variables are:

Variable names must start with either a letter, an underscore _, or the dollar
sign $. For example,

//valid
let a = 'hello';
let _a = 'hello;

let $a = 'hello';

Variable names cannot start with numbers. For example,

//invalid
Let 1a = 'hello'; // this gives an error

JavaScript is case-sensitive. So y and Y are different variables. For example,

let y = "hi";
let Y = 5;

document.write(y); // hi

document.write(Y); // 5

Keywords cannot be used as variable names. For example,

//invalid
let new = 5; // Error! new is a keyword.

Notes:
 Though you can name variables in any way you want, it's a good practice to
give a descriptive variable name. If you are using a variable to store the number
of apples, it better to use apples or numberOfApples rather than x or n.
 In JavaScript, the variable names are generally written in camelCase if it has
multiple words. For example, firstName, annualSalary, etc.

JavaScript Constants

The const keyword was also introduced in the ES6(ES2015) version to create
constants. For example,

const x = 5;

Once a constant is initialized, we cannot change its value.

const x = 5;
x = 10; // Error! constant cannot be changed.
document.write(x)

Simply, a constant is a type of variable whose value cannot be changed.

Also, you cannot declare a constant without initiating it. For example,

const x; // Error! Missing initializer in const declaration.


x = 5;
document.write(x)

Note: If you are sure that the value of a variable won't change throughout the
program, it's recommended to use const. However, there are a few browsers
that do not support const. Visit JavaScript const browser support to learn
more.
Example of JavaScript variable

Let’s see a simple example of JavaScript variable.

<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

Output of the above example


30

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible


within the function or block only. For example:

<script>
function abc()
{
var x=10;//local variable
}
</script>

Or,

<script>
if(10<13)
{
var y=20;//JavaScript local variable
}
</script>

JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e.


declared outside the function or declared with window object is known as global
variable. For example:

<script>
var data=200;//gloabal variable

function a()
{
document.writeln(data);
}

function b()
{
document.writeln(data);
}

a();//calling JavaScript function


b();
</script>

JavaScript Global Variable

A JavaScript global variable is declared outside the function or declared with


window object. It can be accessed from any function.

Let’s see the simple example of global variable in JavaScript.

<script>
var value=50;//global variable

function a()
{
alert(value);
}

function b()
{
alert(value);
}
</script>

Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window
object. For example:

 window.value=90;

Now it can be declared inside any function and can be accessed from any
function. For example:

function m()
{
window.value=100;//declaring global variable by window object
}

function n()
{
alert(window.value);//accessing global variable from other function
}

Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object
internally. You can access it through window object also. For example:

var value=50;

function a()
{
alert(window.value);//accessing global variable
}
Javascript Data Types

JavaScript provides different data types to hold different types of values. There
are two types of data types in JavaScript.

 Primitive data type


 Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type
of the variable because it is dynamically used by JavaScript engine. You need to
use var here to specify the data type. It can hold any type of values such as
numbers, strings etc.

JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Description
Type

Object represents instance through which we can access


members

Array represents group of similar values


RegExp represents regular expression

JavaScript String

String is used to store text. In JavaScript, strings are surrounded by quotes:

 Single quotes: 'Hello'


 Double quotes: "Hello"
 Backticks: `Hello`

For example,

//strings example
let name = 'ram';
let name1 = "hari";
let result = `The names are ${name} and ${name1}`;

Single quotes and double quotes are practically the same and you can use either
of them.

Backticks are generally used when you need to include variables or expressions
into a string. This is done by wrapping variables or expressions with ${variable
or expression} as shown above.

JavaScript Number

Number represents integer and floating numbers (decimals and exponentials).


For example,

let number1 = 3;
let number2 = 3.433;
let number3 = 3e5 // 3 * 10^5

A number type can also be +Infinity, -Infinity, and NaN (not a number). For
example,
let number1 = 3/0;
document.write(number1); // returns Infinity

let number2 = -3/0;


document.write(number2); // returns -Infinity

// strings can't be divided by numbers


let number3 = "abc"/3;
document.write(number3); // returns NaN

JavaScript BigInt

In JavaScript, Number type can only represent numbers less than (253 - 1) and
more than -(253 - 1). However, if you need to use a larger number than that, you
can use the BigInt data type.

A BigInt number is created by appending n to the end of an integer. For example,

// BigInt value
let value = 900719925124740998n;

// Adding two big integers


let value1 = value + 1n;
document.write(value1); // returns "900719925124740999n"

let value = 900719925124740998n;

// Error! BitInt and number cannot be added


let value1 = value + 1;
document.write(value1);

Output

900719925124740999n
Uncaught TypeError: Cannot mix BigInt and other types

Note: BigInt was introduced in the newer version of JavaScript and is not
supported by many browsers including Safari. Visit JavaScript BigInt support to
learn more.
JavaScript Boolean

This data type represents the logical entity. Boolean represents one of two
values: true or false. It is easier to think of it as a yes/no switch. For example,

let dataChecked = true;


let valueCounted = false;

JavaScript undefined

The undefined data type represents value is not assigned. If a variable is


declared but the value is not assigned, then the value of that variable will
be undefined. For example,

let name;
document.write(name); // returns undefined

It is also possible to explicitly assign a variable value undefined. For example,

let name = undefined;


document.write(name); // returns undefined

Note: It is recommended not to explicitly assign undefined to a variable.


Usually, null is used to assign 'unknown' or 'empty' value to a variable.

JavaScript null

In JavaScript, null is a special value that represents empty or unknown value.


For example,

let number = null;

The code above suggests that the number variable is empty.


Note: null is not the same as NULL or Null.
JavaScript Symbol

This data type was introduced in a newer version of JavaScript (from ES2015).

A value having the data type Symbol can be referred to as a symbol


value. Symbol is an immutable primitive value that is unique. For example,

// two symbols with the same description

let value1 = Symbol('hello');


let value2 = Symbol('hello');

Though value1 and value2 both contain 'hello', they are different as they are of
the Symbol type.
Visit JavaScript Symbol to learn more.

JavaScript Object

An object is a complex data type that allows us to store collections of data. For
example,

let student = {
firstName: 'ram',
lastName: null,
class: 10
};

JavaScript Type

JavaScript is a dynamically typed (loosely typed) language. JavaScript


automatically determines the variables' data type for you.

It also means that a variable can be of one data type and later it can be changed
to another data type. For example,
// data is of undefined type
let data;

// data is of integer type


data = 5;

// data is of string type


data = "JavaScript Programming";

JavaScript typeof

To find the type of a variable, you can use the typeof operator. For example,

let name = 'ram';


typeof(name); // returns "string"

let number = 4;
typeof(number); //returns "number"

let valueChecked = true;


typeof(valueChecked); //returns "boolean"

let a = null;
typeof(a); // returns "object"

Notice that typeof returned "object" for the null type. This is a known issue in
JavaScript since its first release.
JavaScript Operators

In this tutorial, you will learn about different operators available in JavaScript
and how to use them with the help of examples.

What is an Operator?

In JavaScript, an operator is a special symbol used to perform operations on


operands (values and variables). For example,

2 + 3; // 5

Here + is an operator that performs addition, and 2 and 3 are operands.

JavaScript Operator Types

Here is a list of different operators you will learn in this tutorial.

 Assignment Operators

 Arithmetic Operators

 Comparison Operators

 Logical Operators

 Bitwise Operators

 String Operators

 Other Operators
JavaScript Assignment Operators

Assignment operators are used to assign values to variables. For example,

let x = 5;

Here, the = operator is used to assign value 5 to variable x.


Here's a list of commonly used assignment operators:

Operator Name Example

= Assignment operator a = 7; // 7

+= Addition assignment a += 5; // a = a + 5

-= Subtraction Assignment a -= 2; // a = a - 2

*= Multiplication Assignment a *= 3; // a = a * 3

/= Division Assignment a /= 2; // a = a / 5

%= Remainder Assignment a %= 2; // a = a % 2

**= Exponentiation Assignment a **= 2; // a = a^2

Note: The commonly used assignment operator is =. You will understand other
assignment operators such as +=, -=, *= etc. once we learn arithmetic operators.
JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic calculations. For example,

let number = 3 + 5; // 8

Here, the + operator is used to add two operands.

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Remainder x%y

++ Increment (increments by 1) ++x or x++

-- Decrement (decrements by 1) --x or x--

** Exponentiation (Power) x ** y

Example 1: Arithmetic operators in JavaScript

let x = 5;
let y = 3;

// addition
document.write('x + y = ', x + y);

// subtraction
document.write('x - y = ', x - y);

// multiplication
document.write('x * y = ', x * y);

// division
document.write('x / y = ', x / y);

// remainder
document.write('x % y = ', x % y);

// increment
document.write('++x = ', ++x); // x is now 6
document.write('x++ = ', x++); // x returns 6 and then increases by 1
document.write('x = ', x);

// decrement
document.write('--x = ', --x); // x is now 6
document.write('x-- = ', x--); // x returns 6 and then increases by 1
document.write('x = ', x);

//exponentiation
document.write('x ** y =', x ** y);

Output

x+y= 8
x-y= 2
x * y = 15
x / y = 1.6666666666666667
x%y=2
++x = 6
x++ = 6
x=7
--x = 6
x-- = 6
x=5
x ** y = 125
Note: The ** operator was introduced in EcmaScript 2016. And, some browsers
may not support the exponentiation operator. To learn more, visit JavaScript
exponentiation browser support.

JavaScript Comparison Operators

Comparison operators compare two values and return a boolean value,


either true or false. For example,

let a = 3, b = 2;
document.write(a > b); // true

Here, the comparison operator > is used to compare whether a is greater than b.

Operator Description Example

== Equal to: returns true if the operands are equal x == y

Not equal to: returns true if the operands are


!= x != y
not equal

Strict equal to: true if the operands are equal


=== x === y
and of the same type

Strict not equal to: true if the operands are


!== x !== y
equal but of different type or not equal at all

Greater than: true if left operand is greater than


> x>y
the right operand

Greater than or equal to: true if left operand is


>= x >= y
greater than or equal to the right operand
Less than: true if the left operand is less than
< x<y
the right operand

Less than or equal to: true if the left operand is


<= x <= y
less than or equal to the right operand

Example 2: Comparison operators in JavaScript

// equal operator
document.write(2 == 2); // true
document.write(2 == '2'); // true

// not equal operator


document.write(3 != 2); // true
document.write('hello' != 'Hello'); // true

// strict equal operator


document.write(2 === 2); // true
document.write(2 === '2'); // false

// strict not equal operator


document.write(2 !== '2'); // false
document.write(2 !== '2'); // true

Output

true
true
true
true
true
false
false
true
Comparison operators are used in decision making and loops. You will learn
about the use of comparison operators in detail in the later tutorials.

JavaScript Logical Operators

Logical operators perform logical operations and return a boolean value,


either true or false. For example,

let x = 5, y = 3;
(x < 6) && (y < 5); // true

Here, && is a logical operator AND. Since both x < 6 and y < 5 are true, the
result is true.
Operator Description Example

Logical AND: true if both the operands are true,


&& x && y
else returns false

Logical OR: true if either of the operands is


|| x || y
true; returns false if both are false

Logical NOT: true if the operand is false and


! !x
vice-versa.

Example 3: Logical Operators in JavaScript

// logical AND
document.write(true && true); // true
document.write(true && false); // false
// logical OR
document.write(true || false); // true

// logical NOT
document.write(!true); // false

Output

true
false
true
false

Logical operators are used in decision making and loops. You will learn about
the use of logical operators in detail in the later tutorials.

JavaScript Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.


Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT

<< Left shift


>> Sign-propagating right shift

>>> Zero-fill right shift

Bitwise operators are rarely used in everyday programming. If you are interested,
visit JavaScript Bitwise Operators to learn more.

JavaScript String Operators

In JavaScript, you can also use the + operator to concatenate (join) two or more
strings.
Example 4: String operators in JavaScript

// concatenation operator
document.write('hello' + 'world');

let a = 'JavaScript';

a += ' tutorial'; // a = a + ' tutorial';


document.write(a);

Output

helloworld
JavaScript tutorial

Note: When + is used with strings, it performs concatenation. However,


when + is used with numbers, it performs addition.

Other JavaScript Operators


For the sake of completeness, here's a list of other operators available in
JavaScript. You will learn about these operators in the later tutorials.

Operator Description Example

evaluates multiple operands and


, returns the value of the last let a = (1, 3 , 4); // 4
operand.

returns value based on the (5 > 3) ? 'success' :


?:
condition 'error'; // "success"

deletes an object's property, or an


delete delete x
element of an array

returns a string indicating the


typeof typeof 3; // "number"
data type

discards the expression's return


void void(x)
value

returns true if the specified


in prop in object
property is in the object

returns true if the specified object object instanceof


instanceof
is of of the specified object type object_type
JavaScript if...else Statement

In JavaScript, there are three forms of the if...else statement.


 if statement
 if...else statement
 if...else if...else statement

JavaScript if Statement

The syntax of the if statement is:

if (condition)
{
// the body of if
}

The if statement evaluates the condition inside the parenthesis ().


 If the condition is evaluated to true, the code inside the body of if is
executed.
 If the condition is evaluated to false, the code inside the body of if is
skipped.
Note: The code inside { } is the body of the if statement.
Working of the if Statement

Example 1: if Statement

// check if the number is positive

let number = prompt("Enter a number: ");

// check if number is greater than 0


if (number > 0)
{
// the body of the if statement
document.write("The number is positive");
}

document.write("The if statement is easy");

Output 1

Enter a number: 2
The number is positive
The if statement is easy

Suppose the user entered 2. In this case, the condition number > 0 evaluates
to true. And, the body of the if statement is executed.
Output 2

Enter a number: -1
The if statement is easy

Suppose the user entered -1. In this case, the condition number > 0 evaluates
to false. Hence, the body of the if statement is skipped.
Since document.write("The if statement is easy"); is outside the body of
the if statement, it is always executed.
Comparison and logical operators are used in conditions. So to learn more about
comparison and logical operators, you can visit JavaScript Comparison and
Logical Operators.

JavaScript if...else statement

An if statement can have an optional else clause. The syntax of


the if...else statement is:

if (condition)
{
// block of code if condition is true
}
else
{
// block of code if condition is false
}
The if..else statement evaluates the condition inside the parenthesis.
If the condition is evaluated to true,
 the code inside the body of if is executed
 the code inside the body of else is skipped from execution

If the condition is evaluated to false,


 the code inside the body of else is executed
 the code inside the body of if is skipped from execution

Working of the if...else statement

Example 2 : if…else Statement

// check is the number is positive or negative/zero

let number = prompt("Enter a number: ");

// check if number is greater than 0


if (number > 0)
{
document.write("The number is positive");
}
// if number is not greater than 0
else
{
document.write("The number is either a negative number or 0");
}

document.write("The if...else statement is easy");

Output 1

Enter a number: 2
The number is positive
The if...else statement is easy

Suppose the user entered 2. In this case, the condition number > 0 evaluates
to true. Hence, the body of the if statement is executed and the body of
the else statement is skipped.
Output 2

Enter a number: -1
The number is either a negative number or 0
The if...else statement is easy

Suppose the user entered -1. In this case, the condition number > 0 evaluates
to false. Hence, the body of the else statement is executed and the body of
the if statement is skipped.

JavaScript if...else if statement


The if...else statement is used to execute a block of code among two alternatives.
However, if you need to make a choice between more than two
alternatives, if...else if...else can be used.
The syntax of the if...else if...else statement is:

if (condition1)
{
// code block 1
}
else if (condition2)
{
// code block 2
}
else
{
// code block 3
}

 If condition1 evaluates to true, the code block 1 is executed.


 If condition1 evaluates to false, then condition2 is evaluated.
 If the condition2 is true, the code block 2 is executed.
 If the condition2 is false, the code block 3 is executed.

Working of the if...else if...else statement


Example 3: if...else if Statement

// check if the number if positive, negative or zero


let number = prompt("Enter a number: ");

// check if number is greater than 0


if (number > 0)
{
document.write("The number is positive");
}
// check if number is 0
else if (number == 0)
{
document.write("The number is 0");
}
// if number is neither greater than 0, nor zero
else
{
document.write("The number is negative");
}

document.write("The if...else if...else statement is easy");

Output

Enter a number: 0
The number is 0
The if...else if...else statement is easy

Suppose the user entered 0, then the first test condition number > 0 evaluates
to false. Then, the second test condition number == 0 evaluates to true and its
corresponding block is executed.
Nested if...else Statement

You can also use an if...else statement inside of an if...else statement. This is
also known as nested if...else statement.
Example 4: Nested if...else Statement

// check if the number is positive, negative or zero


let number = prompt("Enter a number: ");

if (number >= 0)
{
if (number == 0)
{
document.write("You entered number 0");
}
else
{
document.write("You entered a positive number");
}
}
else
{
document.write("You entered a negative number");
}

Output

Enter a number: 0
You entered number 0

Suppose the user entered 0. In this case, the condition number > -1 evaluates
to true. Then the second condition number == 0 is checked which evaluates
to true and its corresponding body is executed.
Note: As you can see, nested if...else makes your logic complicated. If possible,
you should always try to avoid nested if...else.
Body of if...else With Only One Statement

If the body of if...else has only one statement, you can omit { } in the program.
For example, you can replace

let number = 2;
if (number > 0)
{
document.write("The number is positive.");
}
else
{
document.write("The number is negative or zero.");
}

with

let number = 2;
if (number > 0)
document.write("The number is positive.");
else
document.write("The number is negative or zero.");

The output of both programs will be the same.

Output

The number is positive.

Note: Although it's not necessary to use { } if the body of if...else has only one
statement, using { } makes your code more readable.
JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous
page. But it is convenient than if..else..if because it can be used with numbers,
characters etc.

The signature of JavaScript switch statement is given below.

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

default:
code to be executed if above values are not matched;
}

<script>
var grade='B';
var result;
switch(grade)
{
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

Output of the above example

B Grade

The switch statement is fall-through i.e. all the cases will be evaluated if you
don't use break statement.

Let’s understand the behaviour of switch statement in JavaScript.

<script>
var grade='B';
var result;

switch(grade)
{
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

JavaScript for loop

The syntax of the for loop is:

for(initialExpression; condition; updateExpression) {


// for loop body
}

Here,

1. The initialExpression initializes and/or declares variables and executes only


once.
2. The condition is evaluated.
 If the condition is false, the for loop is terminated.
 if the condition is true, the block of code inside of the for loop is
executed.
3. The updateExpression updates the value of initialExpression when the
condition is true.
4. The condition is evaluated again.This process continues until the condition
is false.
Flowchart of JavaScript for loop
Example 1: Display a Text Five Times

// program to display text 10 times


let n = 5;

// looping from i = 1 to 5
for (let i = 1; i <= n; i++)
{
document.write(`I love JavaScript.`);
}

Output

I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.

Here is how this program works.

Condition: i <=
Iteration Variable Action
n

I love JavaScript. is
i=1
1st true printed.
n=5
i is increased to 2.

I love JavaScript. is
i=2
2nd true printed.
n=5
i is increased to 3.

I love JavaScript. is
i=3
3rd true printed.
n=5
i is increased to 4.
I love JavaScript. is
i=4
4th true printed.
n=5
i is increased to 5.

I love JavaScript. is
i=5
5th true printed.
n=5
i is increased to 6.

i=6
6th false The loop is terminated.
n=5

Example 2: Display numbers from 1 to 5

// program to display numbers from 1 to 5


let n = 5;

// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++)
{
document.write(i); // printing the value of i
}

Output

1
2
3
4
5

Here is how this program works.

Iteration Variable Condition: i <= n Action


i=1 1 is printed.
1st true
n=5 i is increased to 2.

i=2 2 is printed.
2nd true
n=5 i is increased to 3.

i=3 3 is printed.
3rd true
n=5 i is increased to 4.

i=4 4 is printed.
4th true
n=5 i is increased to 5.

i=5 5 is printed.
5th true
n=5 i is increased to 6.

i=6
6th false The loop is terminated.
n=5

Example 3: Display Sum of n Natural Numbers

// program to display the sum of natural numbers


let sum = 0;
let n = 100

// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++)
{
sum += i; // sum = sum + i
}

document.write('sum:', sum);

Output
sum: 5050

Here, the value of sum is 0 initially. Then, a for loop is iterated from i = 1 to
100. In each iteration, i is added to sum and its value is increased by 1.
When i becomes 101, the test condition is false and sum will be equal to 0 + 1
+ 2 + ... + 100.

The above program to add sum of natural numbers can also be written as

// program to display the sum of n natural numbers


let sum = 0;
let n = 100;

// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- )
{
// adding i to sum in each iteration
sum += i; // sum = sum + i
}

document.write('sum:',sum);

This program also gives the same output as the Example 3. You can
accomplish the same task in many different ways in programming;
programming is all about logic.
Although both ways are correct, you should try to make your code more
readable.
JavaScript Infinite for loop

If the test condition in a for loop is always true, it runs forever (until memory is
full). For example,

// infinite for loop


for(let i = 1; i > 0; i++)
{
// block of code
}

In the above programs, the condition is always true which will then run the
code for infinite times.

JavaScript while loop

The syntax of the while loop is:

while (condition)
{
// body of loop
}

Here,

1. A while loop evaluates the condition inside the parenthesis ().


2. If the condition evaluates to true, the code inside the while loop is executed.
3. The condition is evaluated again.
4. This process continues until the condition is false.
5. When the condition evaluates to false, the loop stops.
Flowchart of while loop

Flowchart of JavaScript while loop

Example 1: Display Numbers from 1 to 5

// program to display numbers from 1 to 5


// initialize the variable
let i = 1, n = 5;

// while loop from i = 1 to 5


while (i <= n)
{
document.write(i);
i += 1;
}
Output

1
2
3
4
5

Here is how this program works.

Condition: i <=
Iteration Variable Action
n

i = 1 1 is printed. i is
1st true
n=5 increased to 2.

i = 2 2 is printed. i is
2nd true
n=5 increased to 3.

i = 3 3 is printed. i is
3rd true
n=5 increased to 4.

i = 4 4 is printed. i is
4th true
n=5 increased to 5.

i = 5 5 is printed. i is
5th true
n=5 increased to 6.

i = 6
6th false The loop is terminated
n=5
Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers


// if the user enters a negative numbers, the loop ends
// the negative number entered is not added to sum

let sum = 0;

// take input from the user


let number = parseInt(prompt('Enter a number: '));

while(number >= 0)
{

// add all positive numbers


sum += number;

// take input again if the number is positive


number = parseInt(prompt('Enter a number: '));
}

// display the sum


document.write(`The sum is ${sum}.`);

Output

Enter a number: 2
Enter a number: 5
Enter a number: 7
Enter a number: 0
Enter a number: -3
The sum is 14.

In the above program, the user is prompted to enter a number.

Here, parseInt() is used because prompt() takes input from the user as a string.
And when numeric strings are added, it behaves as a string. For example, '2' +
'3' = '23'. So parseInt() converts a numeric string to number.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total
sum is displayed.

JavaScript do...while loop

The syntax of do...while loop is:

do
{
// body of loop
} while(condition)

Here,

1. The body of the loop is executed at first. Then the condition is evaluated.
2. If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
5. This process continues until the condition evaluates to false. Then the loop
stops.
Note: do...while loop is similar to the while loop. The only difference is that
in do…while loop, the body of loop is executed at least once.
Flowchart of do...while loop

Flowchart of JavaScript do...while loop

Let's see the working of do...while loop.


Example 3: Display Numbers from 1 to 5

// program to display numbers


let i = 1;
let n = 5;

// do...while loop from 1 to 5


do
{
document.write(i);
i++;
} while(i <= n);
Output

1
2
3
4
5

Here is how this program works.

Condition: i <=
Iteration Variable Action
n

i = 1 1 is printed. i is increased to
not checked
n=5 2.

i = 2 2 is printed. i is increased to
1st true
n=5 3.

i = 3 3 is printed. i is increased to
2nd true
n=5 4.

i = 4 4 is printed. i is increased to
3rd true
n=5 5.

i = 5 6 is printed. i is increased to
4th true
n=5 6.

i = 6
5th false The loop is terminated
n=5
Example 4: Sum of Positive Numbers

// to find the sum of positive numbers


// if the user enters negative number, the loop terminates
// negative number is not added to sum

let sum = 0;
let number = 0;

do
{
sum += number;
number = parseInt(prompt('Enter a number: '));
} while(number >= 0)

document.write(`The sum is ${sum}.`);

Output 1

Enter a number: 2
Enter a number: 4
Enter a number: -500
The sum is 6.

Here, the do...while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not
added to the sum variable.
Output 2

Enter a number: -80


The sum is 0.

The body of the do...while loop runs only once if the user enters a negative
number.
Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until
the memory is full). For example,

// infinite while loop


while(true)
{
// body of loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop


let count = 1;
do
{
// body of loop
} while(count == 1)

In the above programs, the condition is always true. Hence, the loop body will
run for infinite times.
JavaScript break Statement

The break statement is used to terminate the loop immediately when it is


encountered.
The syntax of the break statement is:

break [label];

Note: label is optional and rarely used.

Working of JavaScript break Statement

Working of JavaScript break Statement


Example 1: break with for loop

// program to print the value of i


for (let i = 1; i <= 5; i++)
{
// break condition
if (i == 3)
{
break;
}
document.write(i);
}

Output

1
2

In the above program, the for loop is used to print the value of i in each
iteration. The break statement is used as:

if(i == 3)
{
break;
}

This means, when i is equal to 3, the break statement terminates the loop.
Hence, the output doesn't include values greater than or equal to 3.
Note: The break statement is almost always used with decision-making
statements. To learn more, visit JavaScript if...else Statement.
To learn more about for loop, visit JavaScript for loop.
Example 2: break with while loop

// program to find the sum of positive numbers


// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum

let sum = 0;

while(true)
{

// take input again if the number is positive


number = parseInt(prompt('Enter a number: '));

// break condition
if(number < 0)
{
break;
}
// add all positive numbers
sum += number;

// display the sum


document.write(`The sum is ${sum}.`);

Output

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.

In the above program, the user enters a number. The while loop is used to
print the total sum of numbers entered by the user.
Here the break statement is used as:
if(number < 0)
{
break;
}

When the user enters a negative number, here -5, the break statement
terminates the loop and the control flow of the program goes outside the loop.
The while loop continues until the user enters a negative number.
To learn more about while loop, visit JavaScript while loop.

break with Nested loop

When break is used inside of two nested loops, break terminates the inner
loop. For example,

// nested for loops

// first loop
for (let i = 1; i <= 3; i++)
{

// second loop
for (let j = 1; j <= 3; j++)
{
if (i == 2)
{
break;
}
document.write(`i = ${i}, j = ${j}`);
}
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In the above program, when i == 2, break statement executes. It terminates the


inner loop and control flow of the program moves to the outer loop.
Hence, the value of i = 2 is never displayed in the output.
JavaScript continue Statement

The continue statement is used to skip the current iteration of the loop and the
control flow of the program goes to the next iteration.
The syntax of the continue statement is:

continue [label];

Note: label is optional and rarely used.

Working of JavaScript continue Statement

Working of JavaScript continue Statement


continue with for loop

In a for loop, continue skips the current iteration and control flow jumps to
the updateExpression.

Example 1: Print the value of i

// program to print the value of i


for (let i = 1; i <= 5; i++)
{

// condition to continue
if (i == 3)
{
continue;
}

document.write(i);
}

Output

1
2
4
5

In the above program, for loop is used to print the value of i in each iteration.
Notice the continue statement inside the loop.
if(i == 3)
{
continue;
}

This means

 When i is equal to 3, the continue statement skips the third iteration.


 Then, i becomes 4 and the test condition and continue statement is evaluated
again.
 Hence, 4 and 5 are printed in the next two iterations.
Note: The continue statement is almost always used with decision making
statements. To learn more, visit JavaScript if...else Statement.
To learn more about for loop, visit JavaScript for loop.
Note: The break statement terminates the loop entirely. However,
the continue statement only skips the current iteration.

continue with while loop

In a while loop, continue skips the current iteration and control flow of the
program jumps back to the while condition.
The continue statement works in the same way for while and do...while loops.
Example 2: Calculate Positive Number

// program to calculate positive numbers only


// if the user enters a negative number, that number is skipped from
calculation

// negative number -> loop terminate


// non-numeric character -> skip iteration

let sum = 0;
let number = 0;

while (number >= 0)


{

// add all positive numbers


sum += number;

// take input from the user


number = parseInt(prompt('Enter a number: '));

// continue condition
if (isNaN(number))
{
document.write('You entered a string.');
number = 0; // the value of number is made 0 again
continue;
}
}

// display the sum


document.write(`The sum is ${sum}.`);

Output

Enter a number: 1
Enter a number: 2
Enter a number: hello
You entered a string.
Enter a number: 5
Enter a number: -2
The sum is 8.

In the above program, the user enters a number. The while loop is used to
print the total sum of positive numbers entered by the user.
Notice the use of the continue statement.

if (isNaN(number))
{
continue;
}

 When the user enters a non-numeric number/string, the continue statement


skips the current iteration. Then the control flow of the program goes to
the condition of while loop.
 When the user enters a number less than 0, the loop terminates.
In the above program, isNaN() is used to check if the value entered by a user is
a number or not.
To learn more about the while loop, visit JavaScript while loop.

continue with Nested loop

When continue is used inside of two nested loops, continue skips the current
iteration of the inner loop. For example,

for (let i = 1; i <= 3; i++)


{
for (let j = 1; j <= 3; j++)
{
if (j == 2)
{
continue;
}
document.write(`i = ${i}, j = ${j}`);
}
}
Output

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3

In the above program, when the continue statement executes, it skips the
current iteration in the inner loop and control flow of the program moves to
the updateExpression of the inner loop.
Hence, the value of j = 2 is never displayed in the output.
JavaScript array:
JavaScript array is an object, which can store multiple values using special
syntax. Every value is associated with numeric index starting with 0. The
following figure illustrates how an array stores values.

JavaScript Array

Array Initialization

An array in JavaScript can be defined and initialized in two ways, array literal
and Array constructor syntax.

Array Literal

Array literal syntax is simple. It takes a list of values separated by a comma


and enclosed in square brackets.

var <array-name> = [element0, element1, element2,... elementN];

The following example shows how to define and initialize an array using array
literal syntax.

Example: Declare and Initialize JS Array

var stringArray = ["one", "two", "three"];

var numericArray = [1, 2, 3, 4];

var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];

JavaScript array can store multiple element of different data types. It is not
required to store value of same data type in an array.
Simple example of creating and using array in JavaScript.

<script type="text/javascript">
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>

JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

The example of creating array directly.

<script type="text/javascript">
var i;

var emp = new Array();

emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor


so that we don't have to provide value explicitly.

The example of creating object by array constructor is given below.

<script type="text/javascript">

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>

Accessing Array Elements

An array elements (values) can be accessed using index (key). Specify an index
in square bracket with array name to access the element at particular index.
Please note that index of an array starts from zero in JavaScript.

Example: Access Array Elements


var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"

var numericArray = [1, 2, 3, 4];


numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4
Array Properties

Array includes "length" property which returns number of elements in the


array.

Use for loop to access all the elements of an array using length property.

Example: Access Array using for Loop


var stringArray = new Array("one", "two", "three", "four");

for (var i = 0; i < stringArray.length ; i++)


{
stringArray[i];
}

JavaScript Array Methods

Popping

The pop() method removes the last element from an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits

Pushing

The push() method adds a new element to an array (at the end):

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits

Shifting Elements

Shifting is equivalent to popping, working on the first element instead of the


last.
The shift() method removes the first array element and "shifts" all other
elements to a lower index.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits

Deleting Elements

Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined

Merging (Concatenating) Arrays

The concat() method creates a new array by merging (concatenating) existing


arrays:

Example (Merging Two Arrays)


var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls
and myBoys

Slicing an Array

The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1
("Orange"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
The slice() method creates a new array. It does not remove any elements from
the source array.

Sorting an Array

The sort() method sorts an array alphabetically:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Reversing an Array

The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements
JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript


function many times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.

JavaScript Function Syntax

The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has
arguments.

<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function
that has one argument.

<script>
function getcube(number)
{
alert(number*number*number);
}
</script>

<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value

We can call function that returns a value and use it in our program. Let’s see
the example of function that returns value.

<script>
function getInfo()
{
return "hello javatpoint! How r u?";
}
</script>

<script>
document.write(getInfo());
</script>

Output of the above example

hello javatpoint! How r u?


JavaScript Dialog Boxes

There are mostly three types of dialog boxes in JavaScript. They are used to
either show confirmation messages, raise an error, or show a warning
message. You can get input also from these dialog boxes. The following are the
dialog boxes in JavaScript:

1. Alert Dialog Box


2. Prompt Dialog Box
3. Confirmation Dialog Box

Alert Dialog Box

This dialog box is mostly used for validation. It displays a message in the dialog
box. This dialog box will block the browser. You cannot do anything in the
browser page without pressing the “OK” button of this dialog box, then it is
closed. It is used for displaying error messages.

Example alert dialog box:


Prompt Dialog Box
It is the only dialog box that can get input from the user. This dialog box has the
two buttons “OK” and “Cancel”. Using this dialog box you can get input from the
user then perform the operation you want on that input value. You can provide
a default value for the prompt dialog box. The default value is “undefined”.
The following is an example of a prompt dialog box:
Confirmation Dialog Box
This dialog box is mostly used, for providing confirmation for the user of specific
actions. When you are exiting from a window then it could request confirmation
from the user, like “Do you really want to Exit?”, It displays two buttons on the
dialog box: “OK” and “Cancel”. When you click the “OK” button it returns true
otherwise it returns false.
The following is an example of a confirmation dialog box:
Document Object Model (DOB):

DOM stands for Document Object Model. An HTML page is rendered in a


browser. The browser assembles all the elements contained in the page,
downloaded from the webserver, in its memory. Once this is done, the browser
then displays these objects in the browser window and once that is done, the
browser can no longer recognize individual HTML elements. JavaScript enabled
browsers are capable of recognizing individual objects in an HTML page after the
page has been rendered in the browser because JavaScript enabled browser
recognizes and uses DOM.
With the document object model, JavaScript gets all the power it needs to
create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

Structure

 Navigator: The browser. Eg: Netscape Navigator, Internet Explorer, Opera,


Mosaic etc.

Window: It is a global object for the javascript code. And it also represents the
browser window.
Document: The document object is the main “entry point” to the page. We can
change or create anything on the page using it and represents all page content
as objects that can be modified.

According to the Document Object Model (DOM), every HTML tag is an object.
Nested tags are “children” of the enclosing one. The text inside a tag is an object
as well.

DOM Object
DOM Properties

Properties Description
Cookie It returns all name or value pairs of cookies in the document.
documentMode It returns the mode used by the browser to render the
document.
Domain It returns the domain name of the server that loaded the
document.
lastModified It returns the date and time of last modified document.
readyState It returns the status of the document.
Referrer It returns the URL of the document that loaded the current
document.
Title It sets or returns the title of the document.
URL It returns the full URL of the document.

DOM Methods

Methods Description
close() It closes the output stream previously opened with document.open().
clear() It clears the document in a window.
open() It opens an output stream to collect the output from
document.write().
write() It writes output (JavaScript code) to a document.
writeln() Same as write(), but adds a newline character after each statement.

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


JavaScript Can Change HTML Content

 One of many JavaScript HTML methods is getElementById().


 The example below "finds" an HTML element (with id="demo"), and
changes the element content (innerHTML) to "Hello JavaScript":
Form Object

 Form object represents an HTML form.


 It is used to collect user input through elements like text fields, check box and
radio button, select option, text area, submit buttons and etc.
Syntax:
<form> . . . </form>

Form Object Properties

Property Description

Action It sets and returns the value of the action attribute in a form.

enctype It sets and returns the value of the enctype attribute in a form.

Length It returns the number of elements in a form.

Method It sets and returns the value of the method attribute in a form that is GET or POST.

Name It sets and returns the value of the name attribute in a form.

Target It sets and returns the value of the target attribute in a form.

Form Object Methods

Method Description

reset() It resets a form.

submit() It submits a form.

2. Hidden Object

 Hidden object represents a hidden input field in an HTML form and it is invisible
to the user.
 This object can be placed anywhere on the web page.
 It is used to send hidden form of data to a server.
Syntax:
<input type= “hidden”>

Hidden Object Properties


Property Description

Name It sets and returns the value of the name attribute of the hidden input field.

Type It returns type of a form element.

Value It sets or returns the value of the value attribute of the hidden input field.

3. Password Object

 Password object represents a single-line password field in an HTML form.


 The content of a password field will be masked – appears as spots or asterisks
in the browser using password object.
Syntax:
<input type= “password”>

Password Object Properties

Property Description

defaultValue It sets or returns the default value of a password field.

maxLength It sets or returns the maximum number of characters allowed in a password filed.

Name It sets or returns the value of the name attribute of a password field.

readOnly It sets or returns whether a password fields is read only or not.

Size It sets or returns the width of a password field.

Value It sets or returns the value of the attribute of the password field.

Password Object Methods

Method Description

select() It selects the content of a password field.

4. Checkbox Object

 Check box object represents a checkbox in an HTML form.


 It allows the user to select one or more options from the available choices.
Syntax:
<input type= “checkbox”>
Checkbox Object Properties

Property Description

Name It sets or returns the name of the checkbox.

Type It returns the value “check”.

Value It sets or returns the value of the attribute of a checkbox.

checked It sets or returns the checked state of a checkbox.

defaultChecked It returns the default value of the checked attribute.

Checkbox Object Methods

Method Description

click() It sets the checked property.

5. Select Object

 Select object represents a dropdown list in an HTML form.


 It allows the user to select one or more options from the available choices.
Syntax:
<select> … </select>

Select Object Collections

Collection Description

options It returns a collection of all the options in a dropdown list.

Select Object Properties

Property Description

Length It returns the number of options in a dropdown list.

selectedIndex It sets or returns the index of the selected option in a dropdown list.

Type It returns a type of form element.

name It returns the name of the selection list.


Select Object Methods

Method Description

add() It adds an option to a dropdown list.

remove() It removes an option from a dropdown list.

6. Option Object

 Option object represents an HTML <option> element.


 It is used to add items to a select element.
Syntax:
<option value> . . . </option>

Option Object Properties

Property Description

Index It sets or returns the index position of an option in a dropdown list.

Text It sets or returns the text of an option element.

defaultSelected It determines whether the option is selected by default.

Value It sets or returns the value to the server if the option was selected.

Prototype It is used to create additional properties.

Option Object Methods

Methods Description

blur() It removes the focus from the option.

focus() It gives the focus to the option.

Example : Simple Program on Option Object Method

<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select"
onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>

Output:
Your Favorite Fruit is Mango.

7. Radio Object
Radio object represents a radio button in an HTML form.

Syntax:
<input type= “radio”>

Radio Object Properties

Property Description

Checked It sets or returns the checked state of a radio button.

defaultChecked Returns the default value of the checked attribute.

Name It sets or returns the value of the name attribute of a radio button.

Type It returns the type of element which is radio button.

Value It sets or returns the value of the radio button.

Radio Object Methods

Method Description

blur() It takes the focus away from the radio button.

click() It acts as if the user clicked the button.

focus() It gives the focus to the radio button.

8. Text Object
Text object represents a single-line text input field in an HTML form.

Syntax:
<input type= “text”>

Text Object Properties

Property Description

Value It sets or returns the value of the text field.

defaultValue It sets or returns the default value of a text field.

Name It sets or returns the value of the name attribute of a text field.

maxLength It sets or returns the maximum number of characters allowed in a text field.

readOnly It sets or returns whether a text field is read-only or not.

Size It sets or returns the width of a text field.

Type It returns type of form element of a text field.

9. Textarea Object
Textarea object represents a text-area in an HTML form.

Syntax:
<textarea> . . . </textarea>

Textarea Object Properties

Property Description

Value It sets or returns the value of the text field.

defaultValue It sets or returns the default value of a text field.

Name It sets or returns the value of the name attribute of a text field.

Type It returns type of form element of a text field.

Rows It displays the number of rows in a text area.

Cols It displays the number of columns in a text area.


Browser Object Model (BOM)

 The Browser Object Model (BOM) is used allow JavaScript to interact


with the browser.
 The Browser objects are automatically created by a browser at the time of
loading a Web page.
 When an HTML document is opened in a browser window, the browser
interprets the document as a collection of hierarchical objects and
accordingly displays the data contained in these objects.
 The browser parses the document and creates a collection of objects,
which defines the document and its details.
 The default object of browser is window.
 There are no official standards for the Browser Object Model (BOM).

The Window Object

 The window object represents a window in browser. An object of window


is created automatically by the browser.

 Window is the object of browser, it is not the object of javascript. The


javascript objects are string, array, date etc.

 All global JavaScript objects, functions, and variables automatically


become members of the window object.

 Global variables are properties of the window object.

 Global functions are methods of the window object.

 Even the document object (of the HTML DOM) is a property of the
window object:
window.document.getElementById("header");

is the same as:

document.getElementById("header");

Window Size

Two properties can be used to determine the size of the browser window.

Both properties return the sizes in pixels:

 window.innerHeight - the inner height of the browser window (in pixels)


 window.innerWidth - the inner width of the browser window (in pixels)

Window Methods

Method Description

alert() displays an alert box with a message and an OK button

blur() removes the focus from the current window

clearInterval() clears the timer, which is set by using the setInterval() method

clearTimeout() clears the timer, which is set by using the setTimeout() method

close() closes the current window

confirm() displays a dialog box with a message and two buttons, OK and Cancel

createPopup() creates a pop-up window

focus() sets focus on the current window

moveBy() moves a window relative to its current position

moveTo() moves a window to an specified position

open() opens a new browser window

print() sends a print command to print the content of the current window
prompt() prompts for input

resizeBy() resizes a window with the specified pixels

resizeTo() resizes a window with the specified width and height

scrollBy() scrolls the content of a window by the specified number of pixels

scrollTo() scrolls the content of a window up to the specified coordinates

setInterval() evaluates an expression at specified time intervals in milliseconds

setTimeout() evaluates an expression after a specified number of milliseconds

Example of alert() in javascript

Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.
Example of Settimeout() function
JavaScript History Object

 The JavaScript history object represents an array of URLs visited by


the user. By using this object, you can load previous, forward or any
particular page.
 The history object is the window property, so it can be accessed by:

window.history

Or,

history

Property of JavaScript history object

There are only 1 property of history object.

No. Property Description

1 Length returns the length of the history URLs.


Methods of JavaScript history object

There are only 3 methods of history object.

No. Method Description

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

JavaScript Navigator Object

The navigator object in JavaScript is used to display information about


the version and type of the browser.

window.navigator
Or,

navigator

JavaScript Navigator Object Properties

The navigator object in JavaScript is used to retrieve properties of client browser. The
following table describes properties of the navigator object in JavaScript.

Property Description

appcodename specifies the code name of the browser

appname specifies the name of the browser

appversion specifies the version of the browser being used

cookieenabled specifies whether the cookies are enabled or not in the browser

contains a string indicating the machine type for which the browser
platform
was compiled

contains a string representing the value of the user-agent header sent


useragent
by the client for the server in the http protocol

JavaScript Navigator Object Properties Example

Here is an example demonstrates navigator object properties in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Navigator Object Properties</title>
<script type="text/javascript">
function dispNavigatorProperties()
{
with(document)
{
write("<b>appName = </b>")
writeln(navigator.appName + "<br/><br/>")
write("<b>appVersion = </b>")
writeln(navigator.appVersion + "<br/><br/>")
write("<b>appCodeName = </b>")
writeln(navigator.appCodeName + "<br/><br/>")
write("<b>platform = </b>")
writeln(navigator.platform + " <br/><br/>")
write("<b>userAgent = </b>")
writeln(navigator.userAgent + "<br/><br/>")
}
}
function dispExplorerProperties()
{
with(document)
{
write("<b>appName = </b>")
writeln(navigator.appName + "<br/><br/>")
write("<b>appVersion = </b>")
writeln(navigator.appVersion + "<br/><br/>")
write("<b>appCodeName = </b>")
writeln(navigator.appCodeName + "<br/><br/>")
write("<b>platform = </b>")
writeln(navigator.platform + " <br/><br/>")
write("<b>userAgent = </b>")
writeln(navigator.userAgent + "<br/><br/>")
write("<b>cookieEnabled = </b>")
writeln(navigator.cookieEnabled + "<br/><br/>")
}
}
function dispBrowserProperties()
{
if(navigator.appName == "Netscape")
dispNavigatorProperties()
else if(navigator.appName == "Microsoft Internet
Explorer")
dispExplorerProperties()
}
dispBrowserProperties()
</script>
</head>
<body>

</body>
</html>
Here are some outputs of the above JavaScript navigator object properties example
code. This is the snapshot of output produced in Google Chrome browser:

Here is the output produced in Mozilla Firefox browser:


Here is the output produced in Safari browser:

Here is the output produced in Microsoft Internet Explorer browser:


JavaScript Screen Object

 The JavaScript screen object holds information of browser screen. It


can be used to display screen width, height, colorDepth, pixelDepth etc.
 The navigator object is the window property, so it can be accessed by:
window.screen

Or,

screen

Property of JavaScript Screen Object

There are many properties of screen object that returns information of the
browser.

No. Property Description

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.


JavaScript Functions:

 A JavaScript function is a block of code designed to perform a particular


task.
 A JavaScript function is executed when "something" invokes it (calls it).
 Function is a great time saver.
 It is used for performing repetitive tasks where you can call the same
function multiple times to get the same effect.
 It allows code reusability.
 JavaScript provides number of built-in functions.

Common Built-in Functions

Functions Description

isNan() Returns true, if the object is Not a Number.


Returns false, if the object is a number.

parseFloat If the string begins with a number, the function reads through the
(string) string until it finds the end of the number; cuts off the remainder of
the string and returns the result.
If the string does not begin with a number, the function returns NaN.

parseInt If the string begins with an integer, the function reads through the
(string) string until it finds the end of the integer, cuts off the remainder of
the string and returns the result.
If the string does not begin with an integer, the function returns NaN
(Not a Number).

String Converts the object into a string.


(object)

eval() Returns the result of evaluating an arithmetic expression.


Definition and Usage of NaN

 The Number.isNaN() method determines whether a value is NaN (Not-A-


Number).

isNan() : Returns true, if the object is Not a Number.


Returns false, if the object is a number.

isNaN(NaN); // true
isNaN(1); // false: 1 is a number
isNaN(-2e-4); // false: -2e-4 is a number (-0.0002) in scientific notation
isNaN(Infinity); // false: Infinity is a number
isNaN(true); // false: converted to 1, which is a number
isNaN(false); // false: converted to 0, which is a number
isNaN(null); // false: converted to 0, which is a number
isNaN(""); // false: converted to 0, which is a number
isNaN(" "); // false: converted to 0, which is a number
isNaN("45.3"); // false: string representing a number, converted to 45.3
isNaN("1.2e3"); // false: string representing a number, converted to 1.2e3
isNaN("Infinity"); // false: string representing a number, converted to Infinity
isNaN(new Date); // false: Date object, converted to milliseconds since epoch
isNaN("10$"); // true : conversion fails, the dollar sign is not a digit
isNaN("hello"); // true : conversion fails, no digits at all
isNaN(undefined); // true : converted to NaN
isNaN(); // true : converted to NaN (implicitly undefined)

parseFloat (string):
 If the string begins with a number, the function reads through the string
until it finds the end of the number; cuts off the remainder of the string
and returns the result.
 If the string does not begin with a number, the function returns NaN.

var a = parseFloat("10") // 10
var b = parseFloat("10.00") // 10
var c = parseFloat("10.33") // 10.33
var d = parseFloat("34 45 66") // 34
var e = parseFloat(" 60 ") // 60
var f = parseFloat("40 years") // 40
var g = parseFloat("He was 40") // NaN
parseInt (string):
 If the string begins with an integer, the function reads through the string
until it finds the end of the integer, cuts off the remainder of the string and
returns the result.
 If the string does not begin with an integer, the function returns NaN (Not
a Number).
var a = parseInt("10") // 10
var b = parseInt("10.00") // 10
var c = parseInt("10.33") // 10
var d = parseInt("34 45 66") // 34
var e = parseInt(" 60 ") // 60
var f = parseInt("40 years") // 40
var g = parseInt("He was 40") // NaN

eval(): Returns the result of evaluating an arithmetic expression.

var x = 10;
var y = 20;
var a = eval("x * y") + "<br>"; // 200
var b = eval("2 + 2") + "<br>"; // 4
var c = eval("x + 17") + "<br>"; // 27

User defined Functions:

JavaScript Function Syntax

 A JavaScript function is defined with the function keyword, followed by


a name, followed by parentheses ().
 Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
 The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly
brackets: {}

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}
Function parameters are listed inside the parentheses () in the function
definition.

Function arguments are the values received by the function when it is


invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other


programming languages.
Example
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return

 When JavaScript reaches a return statement, the function will stop


executing.
 If the function was invoked from a statement, JavaScript will "return" to
execute the code after the invoking statement.
 Functions often compute a return value. The return value is "returned"
back to the "caller":

Example

Calculate the product of two numbers, and return the result:

var x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
The result in x will be: 12
Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of
formulas, assignments, and calculations.

Example

Instead of using a variable to store the return value of a function:

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

var text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables

Variables declared within a JavaScript function, become LOCAL to the


function.

Local variables can only be accessed from within the function.

Example
// code here can NOT use carName

function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the
function is completed.
Date Object

 At times when user need to access the current date and time and also past
and future date and times. JavaScript provides support for working with
dates and time through the Date object.
 The Date object provides a system-independent abstraction of dates and
times.
 Date object can be created as : var today = new Date( );
 Dates may be constructed from a year, month, day of the month, hour,
minute, and second, and those six components, as well as the day of the
week, may be extracted from a date.
 Dates may also be compared and converted to a readable string form. A
Date is represented to a precision of one millisecond.
 Properties of Date object

 Constructor - Returns the function that created the Date object.


 Prototype - Add properties and methods to an object.

Date Methods

Methods Description

Date() Returns current date and time.

getDate() Returns the day of the month.

getDay() Returns the day of the week.

getFullYear() Returns the year.

getHours() Returns the hour.

getMinutes() Returns the minutes.

getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.

getTimezoneOffset() Returns the timezone offset in minutes for the current locale.

getMonth() Returns the month.

setDate() Sets the day of the month.

setFullYear() Sets the full year.


setHours() Sets the hours.

setMinutes() Sets the minutes.

setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.

toDateString() Returns the date portion of the Date as a human-readable string.

toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.


JavaScript Built in Objects
JavaScript has several built-in or core language objects. These built-in objects
are available regardless of window content and operate independently of
whatever page your browser has loaded.

Math Object

 The Math object is used to perform simple and complex arithmetic


operations.
 The Math object provides a number of properties and methods to work
with Number values
 The Math object does not have any constructors. All of its methods and
properties are static; that is, they are member functions of the Math object
itself. There is no way to create an instance of the Math object.

Math Properties

Math Property Description

SQRT2 Returns square root of 2.

PI Returns Π value.

E\ Returns Euler's Constant.

LN2 Returns natural logarithm of 2.

LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.

LOG10E Returns 10 logarithm of E.

Math Methods

Methods Description

abs() Returns the absolute value of a number.


acos() Returns the arccosine (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns cosine of a number.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is base exponent.


String Object
 in JavaScript, all strings are represented as instances of the String object.
 The String object is wrapper class and member of global objects.
 String object used to perform operations on the stored text, such as finding
the length of the string, searching for occurrence of certain characters
within string, extracting a substring etc.
 A String is created by using literals. A string literal is either enclosed within
single quotes(‘ ‘) or double quotes(“ “).
Syntax:
var variable_name = new String(string);
Example:
var s = new String(string);

String Properties

Properties Description

length It returns the length of the string.

prototype It allows you to add properties and methods to an object.

constructor It returns the reference to the String function that created the object.

String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the string into
the substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.

You might also like