You are on page 1of 500

JAVA

Module 1 (Basics and Control Structures) - Java

48 Articles

13 Problems

15 MCQ's
Learn

Module 2 (Arrays and Strings) - Java

12 Articles

11 Problems

10 MCQ's
Learn

Module 3 (Classes and BigInteger) - Java

12 Articles

5 Problems

10 MCQ's
Learn

Module 4 (Stacks, Queues, and Lists) - Java

6 Articles

5 Problems

10 MCQ's
Learn

Module 5 (Sets and Map) - Java

7 Articles

7 Problems

10 MCQ's
Learn
Module 6 (Misc) - Java

4 Articles

3 Problems

10 MCQ's

Articles (48)

Java | How to start learning Java

Java Hello World Program

Naming Conventions in Java

Java Virtual Machine (JVM) Stack Area

JVM Shutdown Hook in Java

Java Class File

Differences between JDK, JRE and JVM

How JVM Works - JVM Architecture?

Does JVM create object of Main class (the class with main())?

How is Java platform independent?

Is main method compulsory in Java?

Java Identifiers

Data types in Java

Myth about the file name and class name in Java

enum in Java

Enum with Customized Value in Java

StringBuffer appendCodePoint() Method in Java with Examples

Variables in Java
Scope of Variables In Java

Blank Final in Java

Bounded Types with Generics in Java

Operators in Java

new operator in Java

Bitwise Operators in Java

Bitwise Right Shift Operators in Java

instanceof Keyword in Java

Comparison of Autoboxed Integer objects in Java

Addition and Concatenation Using + Operator in Java

Java Numeric Promotion in Conditional Expression

Scanner Class in Java

Command Line Arguments in Java

Character Stream Vs Byte Stream in Java

DoubleStream mapToObj() in Java

Scanner and nextChar() in Java

Difference Between Scanner and BufferedReader Class in Java

Formatted output in Java

Fast I/O in Java in Competitive Programming

Ways to read input from console in Java

Loops in Java

For-each loop in Java

Decision Making in Java (if, if-else, switch, break, continue, jump)

Switch Statement in Java


String in Switch Case in Java

Do we need forward declarations in Java?

Type conversion in Java with Examples

Widening Primitive Conversion in Java

Comments in Java

Important Keywords in Java

Java | How to start learning Java

Java is one of the most popular and widely used programming languages and platforms. A platform is
an environment that helps to develop and run programs written in any programming language.
Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming
consoles, cell phones to the Internet, Java is used in every nook and corner.

About Java

 Java is a simple language: Java is easy to learn and its syntax is clear and concise. It is based on
C++ (so it is easier for programmers who know C++). Java has removed many confusing and
rarely-used features e.g. explicit pointers, operator overloading, etc. Java also takes care of
memory management and it also provides an automatic garbage collector. This collects the
unused objects automatically.
 Java is a platform-independent language: The programs written in Java language, after
compilation, are converted into an intermediate level language called the bytecode which is a
part of the Java platform irrespective of the machine on which the programs run. This makes
java highly portable as its bytecodes can be run on any machine by an interpreter called the Java
Virtual Machine(JVM) and thus java provides 'reusability of code'.
 Java is an object-oriented programming language: OOP makes the complete program
simpler by dividing it into a number of objects. The objects can be used as a bridge to have data
flow from one function to another. We can easily modify data and function's as per the
requirements of the program.
 Java is a robust language: Java programs must be reliable because they are used in both
consumer and mission-critical applications, ranging from Blu-ray players to navigation systems.
 Java is a multithreaded language: Java can perform many tasks at once by defining multiple
threads. For example, a program that manages a Graphical User Interface (GUI) while waiting
for input from a network connection uses another thread to perform and wait's instead of using
the default GUI thread for both tasks. This keeps the GUI responsive.
 Java programs can create applets: Applets are programs that run in web browsers. But applets
support was deprecated in Java 9 release and has been removed in Java 11 release due to
waning browser support for the Java plugin.
 Java does not require any preprocessor: It does not require inclusion of header files for
creating a Java application.
1. Understand the basics: Learning the basics of any programming language is very
important. It is the best way to begin learning something new. Don't have any anxiety,
begin learning the concepts about the language. Get familiar with the environment, and
slowly you will get used to it within no time. Here are a few links to get you started:
 Java - Overview
 Java - Basics(Articles)
 Java - Basics (Videos)
 OOP - Concept
2. Patience is the key: Learning Java will be overwhelming because of the volume of
material about the language but be patient, learn at your own pace, don't rush. Mastering
Java is a process that takes time. And remember even the best coders would have started
at some point. So it's not a big deal, just do as much as you can and keep going. Give it
your time. Patience is the key to success.
3. Practice Coding Once you have understood the basics, the best thing to do is to brush up
your skills with regular practice. True knowledge comes only when you implement what
you've learned, as is said 'Practice Makes a Man Perfect'. So, code more than you read.
This will build your confidence. Remember Perfect Practice makes you Perfect. Practice
Coding: You can increase your coding skills here. Happy Coding!
4. Read about Java regularly Continuously read about the various topics in Java and try to
explore more. This will help to maintain your interest in Java. Go through this link to
explore the vast world of Java: Explore Java >> Recent articles on Java >>
5. Study in a group Group study is a better way to learn something. This way you get to
know about new things about the topic as everyone presents their ideas and you can
discuss and solve your coding problems on the spot. Get to know a common group of
people who are willing to learn java. Get help from a tutor and read as many books about
java as possible. There are many good books in the market that will help you in learning
java.

Java Hello World Program

Java is one of the most popular and widely used programming languages and platforms. Java is fast,
reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific
supercomputers to gaming consoles, cell phones to the Internet.

Java is easy to learn, and its syntax is simple and easy to understand. It is based on C++ (so easier for
programmers who know C++).

The process of Java programming can be simplified in three steps:

 Create the program by typing it into a text editor and saving it to a file - HelloWorld.java.
 Compile it by typing "javac HelloWorld.java" in the terminal window.
 Execute (or run) it by typing "java HelloWorld" in the terminal window.

The below-given program is the most simple program of Java printing "Hello World" to the screen. Let
us try to understand every bit of code step by step.

Java
// This is a simple Java program.
// FileName : "HelloWorld.java".
class HelloWorld
{
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
System.out.println("Hello, World");
}
}

Output
Hello, World

Time Complexity: O(1)

Space Complexity: O(1)

The "Hello World!" program consists of three primary components: the HelloWorld class definition, the
main method, and source code comments. The following explanation will provide you with a basic
understanding of the code:

1. Class definition
This line uses the keyword class to declare that a new class is being defined.

class HelloWorld {
//
//Statements
}

2. HelloWorld
It is an identifier that is the name of the class. The entire class definition, including all of its members,
will be between the opening curly brace "{" and the closing curly brace "}".

3. main method:
In the Java programming language, every application must contain a main method. The main
function(method) is the entry point of your Java application, and it's mandatory in a Java program.
whose signature in Java is:

public static void main(String[] args)

 public: So that JVM can execute the method from anywhere.


 static: The main method is to be called without an object. The modifiers public and static can be written
in either order.
 void: The main method doesn't return anything.
 main(): Name configured in the JVM. The main method must be inside the class definition. The compiler
executes the codes starting always from the main function.
 String[]: The main method accepts a single argument, i.e., an array of elements of type String.
Like in C/C++, the main method is the entry point for your application and will subsequently invoke all
the other methods required by your program.

The next line of code is shown here. Notice that it occurs inside the main() method.

System.out.println("Hello, World");

This line outputs the string "Hello, World" followed by a new line on the screen. Output is accomplished
by the built-in println( ) method. The System is a predefined class that provides access to the system,
and out is the variable of type output stream connected to the console.

Comments

They can either be multiline or single-line comments.

// This is a simple Java program.


// Call this file "HelloWorld.java".

This is a single-line comment. This type of comment must begin with // as in C/C++. For multiline
comments, they must begin from /* and end with */.

Important Points

 The name of the class defined by the program is HelloWorld, which is the same as the name of the
file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a class, and there is
at most one public class which contains the main() method.
 By convention, the name of the main class(a class that contains the main method) should match the name
of the file that holds the program.
 Every Java program must have a class definition that matches the filename (class name and file name
should be same).

Compiling the program

 After successfully setting up the environment, we can open a terminal in both Windows/Unix and go to
the directory where the file - HelloWorld.java is present.
 Now, to compile the HelloWorld program, execute the compiler - javac, to specify the name of
the source file on the command line, as shown:

javac HelloWorld.java

 The compiler creates a HelloWorld.class (in the current working directory) that contains the bytecode
version of the program. Now, to execute our program, JVM(Java Virtual Machine) needs to be called using
java, specifying the name of the class file on the command line, as shown:

java HelloWorld

 This will print "Hello World" to the terminal screen.

In Windows
In Linux

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks. Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

Naming Conventions in Java

A programmer is always said to write clean codes, where naming has to be appropriate so that for any
other programmer it acts as an easy way out to read the code. At a smaller level, this seems meaningless
but think of the industrial level where it becomes necessary to write clean codes in order to save time
for which there are certain rules been laid of which one of the factors is to name the keyword right
which is termed as a naming convention in Java.

For example when you are using a variable name depicting displacement then it should be named as
"displace" or similar likewise not likely x, d which becomes complex as the code widens up and
decreases the readability aperture. Consider the below illustrations to get a better understanding which
later on we will be discussing in detail.

Illustrations:

 Class: If you are naming any class then it should be a noun and so should be named as per the
goal to be achieved in the program such as Add2Numbers, ReverseString, and so on not likely
A1, Programming, etc. It should be specific pointing what exactly is there inside without glancing
at the body of the class.
 Interface: If you are naming an interface, it should look like an adjective such as consider the
existing ones: Runnable, Serializable, etc. Try to use 'able' at the end, yes it is said to try as there
are no hard and fast bound rules as if we do consider an inbuilt interface such as 'Remote', it is
not having ble at the end. Consider if you are supposed to create an interface to make read
operation then it is suggested as per naming conventions in java to name a similar likely
'Readable' interface.
 Methods: Now if we do look closer a method is supposed to do something that it does contains
in its body henceforth it should be a verb.
 Constants: As the name suggests it should look like as we read it looks like it is fixed for examples
PI, MAX_INT, MIN_INT, etc. as follows.

Naming Conventions in Java

In java, it is good practice to name class, variables, and methods name as what they are actually
supposed to do instead of naming them randomly. Below are some naming conventions of the java
programming language. They must be followed while developing software in java for good maintenance
and readability of code. Java uses CamelCase as a practice for writing names of methods, variables,
classes, packages, and constants.

Camel's case in java programming consists of compound words or phrases such that each word or
abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital. Here
in simpler terms, it means if there are two

Note: Do look out for these exception cases to camel casing in java as follows:

 In package, everything is small even while we are combining two or more words in java
 In constants, we do use everything as uppercase and only '_' character is used even if we
are combining two or more words in java.

Type 1: Classes and Interfaces

 Class names should be nouns, in mixed cases with the first letter of each internal word
capitalized. Interfaces names should also be capitalized just like class names.
 Use whole words and must avoid acronyms and abbreviations.

Classes: class Student { }


class S=Integer {}
class Scanner {}
Interfaces : Runnable
Remote
Serializable

Type 2: Methods

 Methods should be verbs, in mixed case with the first letter lowercase and with the first letter
of each internal word capitalized.

public static void main(String [] args) {}


As the name suggests the method is supposed to be primarily method which indeed it is as main()
method in java is the method from where the program begins its execution.

Type 3: Variables

Variable names should be short yet meaningful.

Variable names should not start with underscore _ or dollar sign $ characters, even
though both are allowed.

 Should be mnemonic i.e., designed to indicate to the casual observer the intent of its use.
 One-character variable names should be avoided except for temporary variables.
 Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.

int[] marks;
double double answer,

As the name suggests one stands for marks while the other for an answer be it of any e do not mind.

Type 4: Constant variables

 Should be all uppercase with words separated by underscores ("_").


 There are various constants used in predefined classes like Float, Long, String etc.

num = PI;

Type 5: Packages

 The prefix of a unique package name is always written in all-lowercase ASCII letters and
should be one of the top-level domain names, like com, edu, gov, mil, net, org.
 Subsequent components of the package name vary according to an organization's own internal
naming conventions.

java.util.Scanner ;
java.io.*;

As the name suggests in the first case we are trying to access the Scanner class from the java.util package
and in other all classes(* standing for all) input-output classes making it so easy for another
programmer to identify.

Note:

 For class and interfaces, the first letter has to be uppercase.


 For method , variable, package_name, and constants, the first letter has to be lowercase.

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org. See your article appearing on the
GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Java Virtual Machine (JVM) Stack Area
For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java
Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two
operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be
termed as Run – Time Stack. Every method call performed by that thread is stored in the
corresponding run-time stack including parameters, local variables, intermediate computations, and
other data. After completing a method, the corresponding entry from the stack is removed. After
completing all method calls the stack becomes empty and that empty stack is destroyed by the JVM just
before terminating the thread. The data stored in the stack is available for the corresponding thread
and not available to the remaining threads. Hence we can say local data thread-safe. Each entry in the
stack is called Stack Frame or Activation Record.

Stack Frame Structure


The stack frame basically consists of three parts: Local Variable Array, Operand Stack & Frame
Data. When JVM invokes a Java method, first it checks the class data to determine the number of
words (size of the local variable array and operand stack, which is measured in words for each individual
method) required by the method in the local variables array and operand stack. It creates a stack frame
of the proper size for invoked method and pushes it onto the Java stack.

1. Local Variable Array (LVA):

 The local variables part of the stack frame is organized as a zero-based array of words.
 It contains all parameters and local variables of the method.
 Each slot or entry in the array is of 4 Bytes.
 Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4 bytes.
 Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes total.
 Byte, short, and char values will be converted to int type before storing and occupy 1 slot
i.e. 4 Bytes.
 But the way of storing Boolean values is varied from JVM to JVM. But most of the JVM gives 1 slot
for Boolean values in the local variable array.
 The parameters are placed into the local variable array first, in the order in which they are
declared.
 For Example: Let us consider a class Example having a method bike() then the local variable
array will be as shown in the below diagram:

// Class Declaration
class Example
{
public void bike(int i, long l, float f,
double d, Object o, byte b)
{

}
}
2. Operand Stack (OS):

 JVM uses operand stack as workspace like rough work or we can say for storing intermediate
calculation’s result.
 The operand stack is organized as an array of words like a local variable array. But this is not
accessed by using an index like local variable array rather it is accessed by some instructions
that can push the value to the operand stack and some instructions that can pop values from the
operand stack and some instructions that can perform required operations.
 For Example: Here is how a JVM will use this below code that would subtract two local variables
that contain two ints and store the int result in a third local variable:

 So here first two instructions iload_0 and iload_1 will push the values in the operand stack from
a local variable array. And instruction isub will subtract these two values and store the result
back to the operand stack and after istore_2 the result will pop out from the operand stack and
will store into a local variable array at position 2.
3. Frame Data (FD):

 It contains all symbolic references (constant pool resolution) and normal method returns related
to that particular method.
 It also contains a reference to the Exception table which provides the corresponding catch block
information in the case of exceptions.
 JVM Shutdown Hook in Java

 Shutdown Hooks are a special construct that allows developers to plug in a piece of code to be
executed when the JVM is shutting down. This comes in handy in cases where we need to do
special clean up operations in case the VM is shutting down.
Handling this using the general constructs such as making sure that we call a special procedure
before the application exits (calling System.exit(0) ) will not work for situations where the VM
is shutting down due to an external reason (ex. kill request from O/S), or due to a resource
problem (out of memory). As we will see soon, shutdown hooks solve this problem easily, by
allowing us to provide an arbitrary code block, which will be called by the JVM when it is shutting
down.
From the surface, using a shutdown hook is downright straightforward. All we have to do is
simply write a class that extends the java.lang.Thread class, and provide the logic that we want
to perform when the VM is shutting down, inside the public void run() method. Then we register
an instance of this class as a shutdown hook to the VM by calling
Runtime.getRuntime().addShutdownHook(Thread) method. If you need to remove a previously
registered shutdown hook, the Runtime class provides the removeShutdownHook(Thread)
method as well.
Example 1 (Anonymous inner class):

 Java

 public class ShutDownHook
 {
 public static void main(String[] args)
 {

 Runtime.getRuntime().addShutdownHook(new Thread()
 {
 public void run()
 {
 System.out.println("Shutdown Hook is running !");
 }
 });
 System.out.println("Application Terminating ...");
 }
 }
 When we run the above code, you will see that the shutdown hook is getting called by the JVM
when it finishes the execution of the main method.
Output:

 Application Terminating ...


 Shutdown Hook is running !

Example 2

 Java

 class ThreadChild extends Thread {

 public void run() {

 System.out.println("In clean up code");
 System.out.println("In shutdown hook");
 }
 }

 class Demo {

 public static void main(String[] args) {

 Runtime current = Runtime.getRuntime();
 current.addShutdownHook(new ThreadChild());

 for(int i = 1; i <= 10; i++)
 System.out.println("2 X " + i + " = " + 2 * i);
 }
 }
 Output:

 2 X 1 = 2
 2 X 2 = 4
 2 X 3 = 6
 2 X 4 = 8
 2 X 5 = 10
 2 X 6 = 12
 2 X 7 = 14
 2 X 8 = 16
 2 X 9 = 18
 2 X 10 = 20
 In clean up code
 In shutdown hook

Simple right? Yes, it is.
While it is pretty simple to write a shutdown hook, one needs to know the internals behind the
shutdown hooks to make use of those properly. Therefore, in this article, we will be exploring
some of the ‘gotchas’ behind the shutdown hook design.
1. Shutdown Hooks may not be executed in some cases!
The first thing to keep in mind is that it is not guaranteed that shutdown hooks will always run.
If the JVM crashes due to some internal error, then it might crash down without having a chance
to execute a single instruction. Also, if the O/S gives a SIGKILL
(http://en.wikipedia.org/wiki/SIGKILL) signal (kill -9 in Unix/Linux) or TerminateProcess
(Windows), then the application is required to terminate immediately without doing even
waiting for any cleanup activities. In addition to the above, it is also possible to terminate the
JVM without allowing the shutdown hooks to run by calling Runtime.halt() method.
Shutdown hooks are called when the application terminates normally (when all threads finish,
or when System.exit(0) is called). Also, when the JVM is shutting down due to external causes
such as a user requesting a termination (Ctrl+C), a SIGTERM being issued by O/S (normal kill
command, without -9), or when the operating system is shutting down.
2. Once started, Shutdown Hooks can be forcibly stopped before completion.
This is actually a special case of the case explained before. Although the hook starts execution, it
is possible to be terminated before it completes, in cases such as operating system shutdowns.
In this type of case, the O/S waits for a process to terminate for a specified amount of time once
the SIGTERM is given. If the process does not terminate within this time limit, then the O/S
terminates the process forcibly by issuing a SIGTERM (or the counterparts in Windows). So it is
possible that this happens when the shutdown hook is halfway through its execution.
Therefore, it is advised to make sure that the Shutdown Hooks are written cautiously, ensuring
that they finish quickly, and do not cause situations such as deadlocks. Also, the JavaDoc [1]
specifically mentions that one should not perform long calculations or wait for User I/O
operations in a shutdown hook.
3. We can have more than one Shutdown Hooks, but their execution order is not
guaranteed.
As you might have correctly guessed by the method name of the addShutdownHook method
(instead of setShutdownHook), you can register more than one shutdown hook. But the
execution order of these multiple hooks is not guaranteed by the JVM. The JVM can execute
shutdown hooks in any arbitrary order. Moreover, the JVM might execute all these hooks
concurrently.
4. We cannot register/unregister Shutdown Hooks within Shutdown Hooks
Once the shutdown sequence is initiated by the JVM, it is not allowed to add more or remove any
existing shutdown hooks. If this is attempted, the JVM throws IllegalStateException.
5. Once shutdown sequence starts, it can be stopped by Runtime.halt() only.
Once the shutdown sequence starts, only Runtime.halt() (which forcefully terminates the JVM)
can stop the execution of the shutdown sequence (except for external influences such as
SIGKILL). This means that calling System.exit() within a Shutdown Hook will not work. Actually,
if you call System.exit() within a Shutdown Hook, the VM may get stuck, and we may have to
terminate the process forcefully.
6. Using shutdown hooks require security permissions.
If we are using Java Security Managers, then the code which performs adding/removing of
shutdown hooks need to have the shutdown hooks permission at runtime. If we invoke this
method without permission in a secure environment, then it will result in SecurityException.
References :
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(j
ava.lang.Thread)
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to
contribute, you can also write an article using write.geeksforgeeks.org or mail your article to
review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page
and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

Java Class File

A Java class file is a file containing Java bytecode and having .class extension that can be executed
by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation.
As we know that a single Java programming language source file (or we can say .java file) may contain
one class or more than one class. So if a .java file has more than one class then each class will compile
into a separate class files.
For Example: Save this below code as Test.java on your system.
Java

// Compiling this Java program would


// result in multiple class files.

class Sample
{

// Class Declaration
class Student
{

}
// Class Declaration
class Test
{
public static void main(String[] args)
{
System.out.println("Class File Structure");
}
}
For Compiling:

javac Test.java

After compilation there will be 3 class files in corresponding folder named as:

 Sample.class
 Student.class
 Test.class

A single class file structure contains attributes that describe a class file.
Representation of Class File Structure

ClassFile
{
magic_number;
minor_version;
major_version;
constant_pool_count;
constant_pool[];
access_flags;
this_class;
super_class;
interfaces_count;
interfaces[];
fields_count;
fields[];
methods_count;
methods[];
attributes_count;
attributes[];
}
Elements of class file are as follows:

1. magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined
value which the JVM use to identify whether the .class file is generated by valid compiler or not.
The predefined value will be in hexadecimal form i.e. 0xCAFEBABE. Now let’s see what happen
when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as
follows and follow step by step process on your system.

// class Declaration
class Sample
{
public static void main(String[] args)
{
System.out.println("Magic Number");
}
}

Step 1: Compile using javac Sample.java Step 2: Now open the Sample.class file. It will looks like
following.

Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save
it. Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run
time exception (See the highlighted text in below image):
Note: This can vary depending on how much you remove the .class file data.

2. minor_version & major_version: These both together represents .class file version. JVM will
use these versions to identify which version of the compiler generates the current .class file. We
denotes the version of class file as M.m where M stands for major_version and m stands for
minor_version

Note: Lower version compiler generated .class file can be executed by high version JVM but
higher version compiler generated .class file cannot be executed by lower version JVM. If we will
try to execute we will get run time exception. This demonstration is for Windows OS as
follows: Step 1: Open a command prompt window and try to check java compiler version and
JVM version using following commands respectively (Highlighted text in image are the

commands) Output for 1.8 version will be:

Step 2: Now check with another version which may be


higher or lower than already installed.thisDownload link. And install this to your PC or laptops
and note the installation address. Step 3: Open a second command prompt window and set the
path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version

ad JVM version.
Step 4: Now on 1st command prompt compile the any valid .java file. For example: See
above Sample.java file. Compile it as:

Step 5: Now on
2nd command prompt window try to run the above compiled code class file and see what
happen. There is a run time exception which I have highlighted in below image.
Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file
version where the digits before the decimal point represent the major_version and digits after
decimal point represents the minor_version.

1. constant_pool_count: It represents the number of the constants present in the constant


pool (When a Java file is compiled, all references to variables and methods are stored in the
class's constant pool as a symbolic reference).
2. constant_pool[]: It represents the information about constants present in constant pool
file.
3. access_flags: It provide the information about the modifiers which are declared to the
class file.
4. this_class: It represents fully qualified name of the class file.
5. super_class: It represents fully qualified name of the immediate super class of current
class. Consider above Sample.java file. When we will compile it, then we can
say this_class will be Sample class and super_class will be Object class.
6. interface_count: It returns the number of interfaces implemented by current class file.
7. interface[]: It returns interfaces information implemented by current class file.
8. fields_count: It represents the number of fields (static variable) present in current class
file.
9. fields[]: It represent fields (static variable) information present in current class file.
10. method_count: It represents number of methods present in current class file.
11. method[]: It returns information about all methods present in current class file.
12. attributes_count: It returns the number of attributes (instance variables) present in
current class file.
13. attributes[]: It provides information about all attributes present in current class file.

Differences between JDK, JRE and JVM

Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java),
a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in
Java development.

Now we need an environment to make a run of our program. Henceforth, JRE stands for "Java Runtime
Environment" and may also be written as "Java RTE." The Java Runtime Environment provides the
minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM),
core classes, and supporting files.
Now let us discuss JVM, which stands out for java virtual machine. It is as follows:

 A specification where the working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
 An implementation is a computer program that meets the requirements of the JVM
specification.
 Runtime Instance Whenever you write a java command on the command prompt to run the
java class, an instance of JVM is created.

Before proceeding to the differences between JDK, JRE, and JVM, let us discuss them in brief first and
interrelate them with the image below being proposed.

Don't get confused as we are going to discuss all of them one by one.

1. 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).

2. 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.

3. 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.
Now let us discuss the components of JRE in order to understand its importance of it and perceive how
it actually works. For this let us discuss components.

The components of JRE are as follows:

1. Deployment technologies, including deployment, Java Web Start, and Java Plug-in.
2. User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility,
Image I/O, Print Service, Sound, drag, and drop (DnD), and input methods.
3. Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity
(JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote
Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP), and scripting.
4. Other base libraries, including international support, input/output (I/O), extension mechanism,
Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override
Mechanism, Security, Serialization, and Java for XML Processing (XML JAXP).
5. Lang and util base libraries, including lang and util, management, versioning, zip, instrument,
reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref
Objects, and Regular Expressions.
6. Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

After having an adequate understanding of the components, now let us discuss the working of JRE. In
order to understand how JRE works, let us consider an illustration below as follows:

Illustration:

Consider a java source file saved as 'Example.java'. The file is compiled into a set of Byte Code
that is stored in a ".class" file. Here it will be "Example.class".

Note: From above, media operation computing during the compile time can be interpreted.

The following actions occur at runtime as listed below:

 Class Loader
 Byte Code Verifier
 Interpreter
o Execute the Byte Code
o Make appropriate calls to the underlying hardware
Now let us discuss in brief how JVM works out. It is as follows:

JVM becomes an instance of JRE at the runtime of a Java program. It is widely known as a runtime
interpreter.JVM largely helps in the abstraction of inner implementation from the programmers who
make use of libraries for their programs from JDK.

It is mainly responsible for three activities.

 Loading
 Linking
 Initialization

Similarly, now let us discuss the working of JRE which is as follows:

 JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime
Environment).
 Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system
without any adjustments. This is all possible because of JVM.
 When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we
run it. These steps together describe the whole JVM.

This article is contributed by Krishna Bhatia. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about
the topic discussed above.

How JVM Works - JVM Architecture?

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually
calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop
Java code on one system and can expect it to run on any other Java-enabled system without any
adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we run it.
These steps together describe the whole JVM.

Class Loader Subsystem

It is mainly responsible for three activities.

 Loading
 Linking
 Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in
the method area. For each “.class” file, JVM stores the following information in the method area.

 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.

After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. These Class object
can be used by the programmer for getting class level information like the name of the class, parent
name, methods and variable information etc. To get this object reference we can use getClass() method
of Object class.

Java
// A Java program to demonstrate working
// of a Class type object created by JVM
// to represent .class file in memory.
import java.lang.reflect.Field;
import java.lang.reflect.Method;

// Java code to demonstrate use


// of Class object created by JVM
public class Test {
public static void main(String[] args)
{
Student s1 = new Student();

// Getting hold of Class


// object created by JVM.
Class c1 = s1.getClass();

// Printing type of object using c1.


System.out.println(c1.getName());

// getting all methods in an array


Method m[] = c1.getDeclaredMethods();
for (Method method : m)
System.out.println(method.getName());

// getting all fields in an array


Field f[] = c1.getDeclaredFields();
for (Field field : f)
System.out.println(field.getName());
}
}

// A sample class whose information


// is fetched above using its Class object.
class Student {
private String name;
private int roll_No;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no)
{
this.roll_No = roll_no;
}
}

Output
Student
getName
setName
getRoll_no
setRoll_no
name
roll_No

Note: For every loaded “.class” file, only one object of the class is created.

Student s2 = new Student();


// c2 will point to same object where
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true

Linking: Performs verification, preparation, and (optionally) resolution.


 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly
formatted and generated by a valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once
this activity is completed then the class file is ready for compilation.
 Preparation: JVM allocates memory for class variables and initializing the memory to default
values.
 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.

Initialization: In this phase, all static variables are assigned with their values defined in the code and
static block(if any). This is executed from top to bottom in a class and from parent to child in the class
hierarchy.
In general, there are three class loaders :

 Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of
loading trusted classes. It loads core java API classes present in the
“JAVA_HOME/jre/lib” directory. This path is popularly known as the bootstrap path. It is
implemented in native languages like C, C++.
 Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the
extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory
specified by the java.ext.dirs system property. It is implemented in java by
the sun.misc.Launcher$ExtClassLoader class.
 System/Application class loader: It is a child of the extension class loader. It is responsible to load
classes from the application classpath. It internally uses Environment Variable which mapped to
java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class.

Java
// Java code to demonstrate Class Loader subsystem
public class Test {
public static void main(String[] args)
{
// String class is loaded by bootstrap loader, and
// bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

// Test class is loaded by Application loader


System.out.println(Test.class.getClassLoader());
}
}

Output
null
jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f
Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load
request to extension class loader and extension class loader delegate request to the bootstrap class
loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to
the extension class loader and then to the system class loader. At last, if the system class loader fails to
load class, then we get run-time exception java.lang.ClassNotFoundException.

JVM Memory

1. Method area: In the method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There
is only one method area per JVM, and it is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per
JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block
of this stack is called activation record/stack frame which stores methods calls. All local
variables of that method are stored in their corresponding frame. After a thread terminates, its
run-time stack will be destroyed by JVM. It is not a shared resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread
has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native
method information.
Execution Engine

Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and
information present in various memory area and executes instructions. It can be classified into three
parts:

 Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is
that when one method is called multiple times, every time interpretation is required.
 Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the
entire bytecode and changes it to native code so whenever the interpreter sees repeated method
calls, JIT provides direct native code for that part so re-interpretation is not required, thus
efficiency is improved.
 Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.

Java Native Interface (JNI) :

It is an interface that interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries
which may be specific to hardware.

Native Method Libraries :

It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.

Does JVM create object of Main class (the class with main())?

Consider following program.


Java

class Main {
public static void main(String args[])
{
System.out.println("Hello");
}
}
Output:
Hello

Does JVM create an object of class Main?


The answer is "No". We have studied that the reason for main() static in Java is to make sure that the
main() can be called without any instance. To justify the same, we can see that the following program
compiles and runs fine.

Java

// Note Main is abstract


abstract class Main {
public static void main(String args[])
{
System.out.println("Hello");
}
}
Output:
Hello

Since we can't create object of abstract classes in Java, it is guaranteed that object of class with main()
is not created by JVM.

This article is contributed by Narendra Koli. If you like GeeksforGeeks and would like to contribute,
you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above
How is Java platform independent?

The meaning of platform-independent is that the java compiled code(byte code) can run on all operating
systems.
A program is written in a language that is a human-readable language. It may contain words, phrases,
etc which the machine does not understand. For the source code to be understood by the machine, it
needs to be in a language understood by machines, typically a machine-level language. So, here comes
the role of a compiler. The compiler converts the high-level language (human language) into a format
understood by the machines. Therefore, a compiler is a program that translates the source code for
another program from a programming language into executable code.
This executable code may be a sequence of machine instructions that can be executed by the CPU
directly, or it may be an intermediate representation that is interpreted by a virtual machine. This
intermediate representation in Java is the Java Byte Code.

Step by step Execution of Java Program:

 Whenever, a program is written in JAVA, the javac compiles it.


 The result of the JAVA compiler is the .class file or the bytecode and not the machine native
code (unlike C compiler).
 The bytecode generated is a non-executable code and needs an interpreter to execute on a
machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM.
 And finally program runs to give the desired output.

In case of C or C++ (language that are not platform independent), the compiler generates an .exe file
which is OS dependent. When we try to run this .exe file on another OS it does not run, since it is OS
dependent and hence is not compatible with the other OS.

Java is platform-independent but JVM is platform dependent

In Java, the main point here is that the JVM depends on the operating system – so if you are running Mac
OS X you will have a different JVM than if you are running Windows or some other operating system.
This fact can be verified by trying to download the JVM for your particular machine – when trying to
download it, you will be given a list of JVMs corresponding to different operating systems, and you will
obviously pick whichever JVM is targeted for the operating system that you are running. So we can
conclude that JVM is platform-dependent and it is the reason why Java is able to become "Platform
Independent".
Important Points:

 In the case of Java, it is the magic of Bytecode that makes it platform independent.
 This adds to an important feature in the JAVA language termed as portability. Every system has
its own JVM which gets installed automatically when the jdk software is installed. For every
operating system separate JVM is available which is capable to read the .class file or byte code.
 An important point to be noted is that while JAVA is platform-independent language, the JVM
is platform-dependent. Different JVM is designed for different OS and byte code is able to run
on different OS.

This article is contributed by Sania Parween. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Is main method compulsory in Java?

The answer to this question depends on the version of java you are using. Prior to JDK 7, the main
method was not mandatory in a java program.

 You could write your full code under static block and it ran normally.
 The static block is first executed as soon as the class is loaded before the main(); the method is
invoked and therefore before the main() is called. main is usually declared as static method and
hence Java doesn't need an object to call the main method.
 When you will give the run command(i.e java Test in the below-mentioned program in notepad),
so compiler presumes Test is that class in which main() is there and since compiler load, the
main() method, static blocks are ready to get executed. So here, it will run static block first and
then it will see no main() is there. Therefore it will give "exception", as exception comes while
execution. However, if we don't want an exception, we can terminate the program by
System.exit(0);
However, from JDK7 main method is mandatory. The compiler will verify first, whether main() is
present or not. If your program doesn't contain the main method, then you will get an error "main
method not found in the class". It will give an error (byte code verification error because in it's byte
code, main is not there) not an exception because the program has not run yet.

Note:- However, both the programs will get compile because for compilation we don't need main()
method.

Java

// This program will successfully run


// prior to JDK 7
public class Test
{
// static block
static
{
System.out.println("Hello User");
}
}
Below is the screenshot of the output to help you to visualize the same thing, practically. I have run this
program on Notepad so that you can able to understand why that exception has changed into error in
the latest version.

 If run prior to JDK 7


Output in JAVA 6 version.

 If run on JDK 7,8 and so on...

Output in JAVA 7

?list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Java Identifiers

In programming languages, identifiers are used for identification purposes. In Java, an identifier can be
a class name, method name, variable name, or label. For example :

public class Test


{
public static void main(String[] args)
{
int a = 20;
}
}
In the above java code, we have 5 identifiers namely :

 Test : class name.


 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for defining Java Identifiers

There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we
get compile-time error. These rules are also valid for other languages like C,C++.

 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]),
'$'(dollar sign) and '_' (underscore).For example "geek@" is not a valid java identifier as it
contain '@' special character.
 Identifiers should not start with digits([0-9]). For example "123geeks" is a not a valid java
identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum length of 4
- 15 letters only.
 Reserved Words can't be used as an identifier. For example "int while = 20;" is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.

Examples of valid identifiers :

MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :

My Variable // contains a space


123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

Reserved Words

Any programming language reserves some words to represent functionalities defined by that language.
These words are called reserved words.They can be briefly categorized into two parts : keywords(50)
and literals(3). Keywords define functionalities and literals define a value. Identifiers are used by
symbol tables in various analyzing phases(like lexical, syntax, semantic) of a compiler architecture.

Note: The keywords const and goto are reserved, even though they are not currently used. In place of
const, the final keyword is used. Some keywords like strictfp are included in later versions of Java.

?list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.

Data types in Java

Data types are different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Also, let us cover up other important ailments
that there are majorly two types of languages that are as follows:

1. First, one is a Statically typed language where each variable and expression type is already
known at compile time. Once a variable is declared to be of a certain data type, it cannot hold
values of other data types. For example C, C++, Java.
2. The other is Dynamically typed languages. These languages can receive different data types
over time. For example Ruby, Python

Java is statically typed and also a strongly typed language because, in Java, each type of data (such
as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the
programming language and all constants or variables defined for a given program must be described
with one of the data types.

Java has two categories in which data types are segregated

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Types Of Primitive Data Types

Primitive data are only single values and have no special capabilities. There are 8 primitive data
types. They are depicted below in tabular format below as follows:
Let us discuss and implement each one of the following data types that are as follows:

Type 1: boolean

Boolean data type represents only one bit of information either true or false which is intended to
represent the two truth values of logic and Boolean algebra, but the size of the boolean data type
is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with
casts) to any other type. But the programmer can easily write conversion code.

Syntax:

boolean booleanVar;

Size: Virtual machine dependent

Values: Boolean such as true, false

Default Value: false

Example:

Java
// Java Program to Demonstrate Boolean Primitive DataType

// Class
class GFG {

// Main driver method


public static void main(String args[])
{

//Boolean data type is a data type that has one of two possible
values (usually denoted true and false).
// Setting boolean to false and true initially
boolean a = false;
boolean b = true;

// If condition holds
if (b == true){

// Print statement
System.out.println("Hi Geek");
}
// If condition holds
if(a == false){

// Print statement
System.out.println("Hello Geek");
}
}
}

Output

Hi Geek
Hello Geek

Type 2: byte

The byte data type is an 8-bit signed two's complement integer. The byte data type is useful for saving
memory in large arrays.

Syntax:

byte byteVar;

Size: 1 byte (8 bits)

Values: -128 to 127

Default Value: 0

Example:

Java
// Java Program to demonstrate Byte Data Type

// Class
class GFG {

// Main driver method


public static void main(String args[]) {

byte a = 126;

// byte is 8 bit value


System.out.println(a);

a++;
System.out.println(a);

// It overflows here because


// byte can hold values from -128 to 127
a++;
System.out.println(a);

// Looping back within the range


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

Output
126
127
-128
-127

Type 3: short

The short data type is a 16-bit signed two's complement integer. Similar to byte, use a short to save
memory in large arrays, in situations where the memory savings actually matters.

Syntax:

short shortVar;

Size: 2 byte (16 bits)

Values: -32, 768 to 32, 767 (inclusive)


Default Value: 0

Type 4: int

It is a 32-bit signed two's complement integer.

Syntax:

int intVar;

Size: 4 byte ( 32 bits )

Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)

Note: The default value is '0'


Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit
integer, which has a value in the range [0, 232-1]. Use the Integer class to use the int data type as
an unsigned integer.

Type 5: long

The range of a long is quite large. The long data type is a 64-bit two's complement integer and is useful
for those occasions where an int type is not large enough to hold the desired value.

Syntax:
long longVar;

Size: 8 byte (64 bits)

Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775, 807} (inclusive)

Note: The default value is '0'.


Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-
bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also
contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic
operations for unsigned long.

Type 6: float

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if
you need to save memory in large arrays of floating-point numbers.

Syntax:

float floatVar;

Size: 4 byte (32 bits)

Values: upto 7 decimal digits


Note: The default value is '0.0'.
Example:

Java
// Java Program to Illustrate Float Primitive Data Type

// Importing required classes


import java.io.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring and initializing float value

// float value1 = 9.87;


// Print statement
// System.out.println(value1);
float value2 = 9.87f;
System.out.println(value2);
}
}

Output
9.87

If we uncomment lines no 14,15,16 then the output would have been totally different as we would have
faced an error.

Type 7: double
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data
type is generally the default choice.

Syntax:

double doubleVar;

Size: 8 bytes or 64 bits

Values: Upto 16 decimal digits

Note:

 The default value is taken as '0.0'.


 Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it
is recommended not to use these data types and use BigDecimal class instead.

It is recommended to go through rounding off errors in java.

Type 8: char

The char data type is a single 16-bit Unicode character.

Syntax:

char charVar;

Size: 2 byte (16 bits)

Values: '\u0000' (0) to '\uffff' (65535)

Note: The default value is '\u0000'


You must be wondering why is the size of char 2 bytes in Java?

So, in other languages like C/C++ uses only ASCII characters, and to represent all ASCII characters 8-
bits is enough. But java uses the Unicode system not the ASCII code system and to represent the
Unicode system 8 bits is not enough to represent all characters so java uses 2 bytes for
characters. Unicode defines a fully international character set that can represent most of the world's
written languages. It is a unification of dozens of character sets, such as Latin, Greeks, Cyrillic, Katakana,
Arabic, and many more.

Example:

Java
// Java Program to Demonstrate Char Primitive Data Type

// Class
class GFG {
// Main driver method
public static void main(String args[])
{

// Creating and initializing custom character


char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

// use byte and short


// if memory is a constraint
byte b = 4;

// this will give error as number is


// larger than byte range
// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

// by default fraction value


// is double in java
double d = 4.355453532;

// for float use 'f' as suffix as standard


float f = 4.7333434f;

//need to hold big range of numbers then we need this data type
long l = 12121;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}

Output

char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Non-Primitive Data Type or Reference Data Types

The Reference Data Types will contain a memory address of variable values because the reference
types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.

A: Strings

Strings are defined as an array of characters. The difference between a character array and a string in
Java is, that the string is designed to hold a sequence of characters in a single variable whereas, a
character array is a collection of separate char type entities. Unlike C/C++, Java strings are not
terminated with a null character.

Syntax: Declaring a string

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator


String s = "GeeksforGeeks";

// Declare String using new operator


String s1 = new String("GeeksforGeeks");

B: Class

A class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:

1. Modifiers: A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class's parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.

C: Object

It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of
:

1. State: It is represented by the attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.

D: Interface

Like a class, an interface can have methods and variables, but the methods declared in an interface are
by default abstract (only method signature, no body).

 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class implementing
Player must be able to (or must implement) move(). So it specifies a set of methods that the class
has to implement.
 If a class implements an interface and does not provide method bodies for all functions specified
in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface. If a class implements this interface, then it can
be used to sort a collection.

E: Array

An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. The following are some important points about Java arrays.

 In Java, all arrays are dynamically allocated. (discussed below)


 Since arrays are objects in Java, we can find their length using member length. This is different
from C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each has an index beginning from 0.
 Java array can also be used as a static field, a local variable, or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.

Check Out: Quiz on Data Type in Java

This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to
contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks. Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Myth about the file name and class name in Java

The first lecture note given during java class is “In java file name and class name should be the same”.
When the above law is violated a compiler error message will appear as below

Java

/***** File name: Trial.java ******/


public class Geeks {
public static void main(String[] args)
{
System.out.println("Hello world");
}
}

Output:

javac Trial.java
Trial.java:9: error: class Geeks is public, should be
declared in a file named Geeks.java
public class Geeks
^
1 error
But the myth can be violated in such a way to compile the above file.

Java

/***** File name: Trial.java ******/


class Geeks {
public static void main(String[] args)
{
System.out.println("Hello world");
}
}

Step 1:

javac Trial.java

Step 1 will create a Geeks.class (byte code) without any error message since the class is not public.
Step 2:

java Geeks
Now the output will be Hello world
The myth about the file name and class name should be same only when the class is declared in public.
The above program works as follows:

Now, this .class file can be executed. By the above features, some more miracles can be done. It is
possible to have many classes in a java file. For debugging purposes, this approach can be used. Each
class can be executed separately to test their functionalities(only on one condition: Inheritance concept
should not be used).
But in general, it is good to follow the myth.
Example 1:

Java

/*** File name: Trial.java ***/


class ForGeeks {
public static void main(String[] args)
{
System.out.println("For Geeks class");
}
}
class GeeksTest {
public static void main(String[] args)
{
System.out.println("Geeks Test class");
}
}

When the above file is compiled as javac Trial.java this will create 2 .class files as ForGeeks.class and
GeeksTest.class .
Since each class has separate main() stub they can be tested individually.

 When java ForGeeks is executed the output is For Geeks class.


 When java GeeksTest is executed the output is Geeks Test class.

Example 2:

Java

// Program to find area of triangle


class Triangle {
int x, y;
void printArea()
{
System.out.println("Area of triangle is: " + x * y / 2);
}
}

class Demo {
public static void main(String args[])
{
// Object creation
Triangle t = new Triangle();
t.x = 10;
t.y = 13;
t.printArea();
}
}

Note: There are two classes here, Triangle and Demo. Then which class name must be considered as
the file name?
The class name Demo must be taken as the file name. The reason behind taking Demo as the file name
is that it has the main method and execution begins from the main method.

Filename: Demo.java
Compilation: javac Demo.java
Run: java Demo
Output: Area of triangle:65

?list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj

This article is contributed by Sowmya.L.R. If you like GeeksforGeeks and would like to contribute, you
can also write an article and mail your article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above

enum in Java

Enumerations serve the purpose of representing a group of named constants in a programming


language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club,
Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include
natural enumerated types (like the planets, days of the week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding
modes, command-line flags, etc. It is not necessary that the set of constants in an enum type
stay fixed for all time.
A Java enumeration is a class type. Although we don't need need to instantiate an enum using new, it
has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just
like classes, you can give them constructor, add instance variables and methods, and even implement
interfaces.

One thing to keep in mind is that, unlike classes, enumerations neither inherit other classes nor can get
extended(i.e become superclass).

In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful
than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main
objective of enum is to define our own data types(Enumerated Data Types).

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not
inside a Method.

Java
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)

enum Color {
RED,
GREEN,
BLUE;
}

public class Test {


// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output
RED

Java
// enum declaration inside a class.

public class Test {


enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output
RED

 The first line inside the enum should be a list of constants and then other things like methods,
variables, and constructors.
 According to Java naming conventions, it is recommended that we name constant with all capital
letters

Important Points of enum:

 Every enum is internally implemented by using Class.

/* internally above enum Color is converted to


class Color
{
public static final Color RED = new Color();
public static final Color BLUE = new Color();
public static final Color GREEN = new Color();
}*/

 Every enum constant represents an object of type enum.


 enum type can be passed as an argument to switch statements.

Java
// A Java program to demonstrate working on enum
// in switch case (Filename Test. Java)

import java.util.Scanner;

// An Enum class
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}

// Driver class that contains an object of "day" and


// main().
public class Test {
Day day;

// Constructor
public Test(Day day) { this.day = day; }

// Prints a line about Day using switch


public void dayIsLike()
{
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}

// Driver method
public static void main(String[] args)
{
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
Output
Mondays are bad.

 Every enum constant is always implicitly public static final. Since it is static, we can access it
by using the enum Name. Since it is final, we can't create child enums.
 We can declare the main() method inside the enum. Hence we can invoke enum directly from
the Command Prompt.

Java
// A Java program to demonstrate that we can have
// main() inside enum class.

enum Color {
RED,
GREEN,
BLUE;

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output
RED

Enum and Inheritance:

 All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java,
so an enum cannot extend anything else.
 toString() method is overridden in java.lang.Enum class, which returns enum constant name.
 enum can implement many interfaces.

values(), ordinal() and valueOf() methods:

 These methods are present inside java.lang.Enum.


 values() method can be used to return all values present inside the enum.
 Order is important in enums.By using the ordinal() method, each enum constant index can be
found, just like an array index.
 valueOf() method returns the enum constant of the specified string value if exists.

Java
// Java program to demonstrate working of values(),
// ordinal() and valueOf()
enum Color {
RED,
GREEN,
BLUE;
}

public class Test {


public static void main(String[] args)
{
// Calling values()
Color arr[] = Color.values();

// enum with loop


for (Color col : arr) {
// Calling ordinal() to find index
// of color.
System.out.println(col + " at index "
+ col.ordinal());
}

// Using valueOf(). Returns an object of


// Color with given constant.
// Uncommenting second line causes exception
// IllegalArgumentException
System.out.println(Color.valueOf("RED"));
// System.out.println(Color.valueOf("WHITE"));
}
}

Output
RED at index 0
GREEN at index 1
BLUE at index 2
RED

enum and constructor:

 enum can contain a constructor and it is executed separately for each enum constant at the time
of enum class loading.
 We can't create enum objects explicitly and hence we can't invoke enum constructor directly.

enum and methods:


 enum can contain both concrete methods and abstract methods. If an enum class has an
abstract method, then each instance of the enum class must implement it

Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.

// An enum (Note enum keyword inplace of class keyword)


enum Color {
RED,
GREEN,
BLUE;

// enum constructor called separately for each


// constant
private Color()
{
System.out.println("Constructor called for : "
+ this.toString());
}

public void colorInfo()


{
System.out.println("Universal Color");
}
}

public class Test {


// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}
}

Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Next Article on enum: Enum with Customized Value in Java

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks. Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Enum with Customized Value in Java

Prerequisite : enum in Java

By default enums have their own string values, we can also assign some custom values to enums.
Consider below example for that.

Examples:

enum Fruits
{
APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);
}

In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES
with have their own different custom values RED, YELLOW and GREEN respectively.

Now to use this enum in code, there are some points we have to follow:-

1. We have to create parameterized constructor for this enum class. Why? Because as we know that
enum class’s object can’t be create explicitly so for initializing we use parameterized constructor.
And the constructor cannot be the public or protected it must have private or default modifiers.
Why? if we create public or protected, it will allow initializing more than one objects. This is
totally against enum concept.
2. We have to create one getter method to get the value of enums.

Java

// Java program to demonstrate how values can


// be assigned to enums.
enum TrafficSignal
{
// This will call enum constructor with one
// String argument
RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN");

// declaring private variable for getting values


private String action;

// getter method
public String getAction()
{
return this.action;
}

// enum constructor - cannot be public or protected


private TrafficSignal(String action)
{
this.action = action;
}
}

// Driver code
public class EnumConstructorExample
{
public static void main(String args[])
{
// let's print name of each enum and there action
// - Enum values() examples
TrafficSignal[] signals = TrafficSignal.values();

for (TrafficSignal signal : signals)


{
// use getter method to get the value
System.out.println("name : " + signal.name() +
" action: " + signal.getAction() );
}
}
}
Output:

name : RED action: STOP


name : GREEN action: GO
name : ORANGE action: SLOW DOWN
This article is contributed by Vihang Shah. If you like GeeksforGeeks and would like to contribute, you
can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.

StringBuffer appendCodePoint() Method in Java with Examples

appendCodePoint() method of StringBuffer class appends the string representation of the codePoint
argument to this sequence for which we require pre-requisite knowledge of ASCII table as then only we
will be able to perceive output why the specific literal is being appended as there is already an integer
value been assigned.

--> appendCodePoint() Method


--> StringBuffer Class
--> java.lang Package

Syntax:

public StringBuffer appendCodePoint(int cp)

Parameters: The method accepts a single parameter cp of integer type and refers to the Unicode code
point.

Return Type: The method returns this object after appending the string represented by the codepoint.

Illustrations:
Input : StringBuffer = Apple
int cp = 65
Output: AppleA
Input : StringBuffer = GeeksforGeeks
int cp = 156
Output: GeeksforGeeks?

Explanation: Because 65 is the ASCII value for 'A' and 156 is the ASCII value for '?'

Example 1:

Java
// Java program to illustrate appendCodePoint() Method
// of StringBuffer class
// Importing required classes
import java.lang.*;

// Main class
public class GFG {

// Main drive method


public static void main(String[] args)
{

// Reading passed string


StringBuffer sbf
= new StringBuffer("Geeksforgeeks");

// Printing the string


System.out.println("String buffer = " + sbf);

// Appending the CodePoint as String to the string


// buffer
sbf.appendCodePoint(65);

// Printing the string again after


// appending codePoint as string
System.out.println("After appending CodePoint is = "
+ sbf);
}
}

Output:

String buffer = Geeksforgeeks


After appending CodePoint is = GeeksforgeeksA

Example 2:

Java
// Java Program to Illustrate appendCodePoint() Method
// of StringBuffer class

// Importing required classes


import java.lang.*;
// Main class
public class GFG {

// Main driver method


public static void main(String[] args) {

// Reading passed string by creating object of class


StringBuffer sbf
= new StringBuffer("Geeksforgeeks");

System.out.println("String buffer = " + sbf);

// Here it appends the CodePoint as


// string to the string buffer
sbf.appendCodePoint(54);

System.out.println("After appending CodePoint is = "


+ sbf);
}
}

Output:

String buffer = Geeksforgeeks


After appending CodePoint is = Geeksforgeeks6

Example 3:

Java
// Java program to illustrate appendCodePoint() Method
// of StringBuffer class

// Importing required classes


import java.lang.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Reading passed string
StringBuffer sbf
= new StringBuffer("Geeksforgeeks");

// Printing string on console


System.out.println("String buffer = " + sbf);

// Appending the codePoint as string


// to the string buffer
sbf.appendCodePoint(43);

// Printing the string on console after


// appending codepoint as string
System.out.println("After appending CodePoint is = "
+ sbf);
}
}

Output:

String buffer = Geeksforgeeks


After appending CodePoint is = Geeksforgeeks+

Variables in Java

Variable in Java is a data container that saves the data values during Java program execution. Every
variable is assigned a data type that designates the type and quantity of value it can hold. A variable is
a memory location name for the data.

A variable is a name given to a memory location. It is the basic unit of storage in a program.

 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
affect that memory location.
 In Java, all 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 are:

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

2. data_name: 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.

Illustrations:
float simpleInterest;
// Declaring float variable
int time = 10, speed = 20;
// Declaring and initializing integer variable
char var = 'h';
// Declaring and initializing character variable

Types of Variables in Java

Now let us discuss different types of variables which are listed as follows:

1. Local Variables
2. Instance Variables
3. Static Variables

Let us discuss the traits of every type of variable listed here in detail.

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 variables are 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.

Java
/*package whatever //do not write package name here */
// Contributed by Shubham Jain
import java.io.*;

class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}

Output
Local Variable: 10

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method,
constructor, or block.

 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 an instance variable is not mandatory. Its default value is 0.
 Instance variables can be accessed only by creating objects.

Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public String geek; // Declared Instance Variable

public GFG()
{ // Default Constructor

this.geek = "Shubham Jain"; // initializing Instance Variable


}
//Main Method
public static void main(String[] args)
{

// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}

Output
Geek name is: Shubham Jain

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 of 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 a static variable is not mandatory. Its default value is 0.
 If we access a static variable like an instance variable (through an object), the compiler will show
a warning message, which won't halt the program. The compiler will replace the object name
with the class name automatically.
 If we access a static variable without the class name, the compiler will automatically append the
class name.

Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static String geek = "Shubham Jain"; //Declared static


variable

public static void main (String[] args) {

//geek variable can be accessed without object creation


//Displaying O/P
//GFG.geek --> using the static variable
System.out.println("Geek Name is : "+GFG.geek);
}
}

Output
Geek Name is : Shubham Jain

Differences between the Instance variables and the Static variables

Now let us discuss the differences between the Instance variables and the Static variables:

 Each object will have its own copy of an instance variable, whereas we can only have one copy
of a static variable per class, irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects as
each object has its own copy of the instance variable. In the case of a static variable, changes will
be reflected in other objects as static variables are common to all objects of a class.
 We can access instance variables through object references, and static variables can be accessed
directly using the class name.

Syntax: Static and instance variables

class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

Must Read:

 Rules of Variable Declaration in Java


 Scope of Variables in Java
 Comparison of static keyword in C++ and Java
 Are static local variables allowed in Java?
 Instance Variable Hiding in Java

This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks. Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

Scope of Variables In Java

Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all
identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and
independent of function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules
can be covered under following categories.

Member Variables (Class Level Scope)

These variables must be declared inside class (outside any function). They can be directly accessed
anywhere in class. Let's take a look at an example:

public class Test


{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}

 We can declare class variables anywhere in class, but outside methods.


 Access specified of member variables doesn't affect scope of them within a class.
 Member variables can be accessed outside a class with following rules

Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no
modifier) Yes No No

private No No No

Local Variables (Method Level Scope)

Variables declared inside a method have method level scope and can't be accessed outside the method.
public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}

Note : Local variables don't exist after method's execution is over.

Here's another example of method scope, except this time the variable got passed in as a parameter to
the method:

class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}

The above code uses this keyword to differentiate between the local and class variables.

As an exercise, predict the output of following Java program.

Java

public class Test


{
static int x = 11;
private int y = 33;
public void method1(int x)
{
Test t = new Test();
this.x = 22;
y = 44;

System.out.println("Test.x: " + Test.x);


System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}

Output:

Test.x: 22
t.x: 22
t.y: 33
y: 44

Loop Variables (Block Scope)


A variable declared inside pair of brackets "{" and "}" in a method has scope within the brackets only.

Java

public class Test


{
public static void main(String args[])
{
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}

// Uncommenting below line would produce


// error since variable x is out of scope.

// System.out.println(x);
}
}

Output:

10

As another example, consider following program with a for loop.

Java

class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}

// Will produce error


System.out.println(x);
}
}

Output:

11: error: cannot find symbol


System.out.println(x);

The right way of doing above is,


Java

// Above program after correcting the error


class Test
{
public static void main(String args[])
{
int x;
for (x = 0; x < 4; x++)
{
System.out.println(x);
}

System.out.println(x);
}
}

Output:

0
1
2
3
4

Let's look at tricky example of loop scope. Predict the output of following program. You may be
surprised if you are regular C/C++ programmer.

Java

class Test
{
public static void main(String args[])
{
int a = 5;
for (int a = 0; a < 5; a++)
{
System.out.println(a);
}
}
}

Output :
6: error: variable a is already defined in method go(int)
for (int a = 0; a < 5; a++)
^
1 error

Note:- In C++, it will run. But in java it is an error because in java, the name of the variable of inner and
outer loop must be different.
A similar program in C++ works. See this.

As an exercise, predict the output of the following Java program.

Java

class Test
{
public static void main(String args[])
{
{
int x = 5;
{
int x = 10;
System.out.println(x);
}
}
}
}

Q. From the above knowledge, tell whether the below code will run or not.

Java
class Test {
public static void main(String args[])
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
int i = 20;
System.out.println(i);
}
}

Output :

1
2
3
4
5
6
7
8
9
10
20

Yes, it will run!


See the program carefully, inner loop will terminate before the outer loop variable is declared.So the
inner loop variable is destroyed first and then the new variable of same name has been created.

Some Important Points about Variable scope in Java:

 In general, a set of curly brackets { } defines a scope.


 In Java we can usually access a variable as long as it was defined within the same set of brackets
as the code we are writing or within any curly brackets inside of the curly brackets where the
variable was defined.
 Any variable defined in a class outside of any method can be used by all member methods.
 When a method has the same local variable as a member, "this" keyword can be used to reference
the current class variable.
 For a variable to be read after the termination of a loop, It must be declared before the body of
the loop.

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute,
you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above

Blank Final in Java

A final variable in Java can be assigned a value only once, we can assign a value either in declaration or
later.

final int i = 10;


i = 30; // Error because i is final.

A blank final variable in Java is a final variable that is not initialized during declaration. Below is a
simple example of blank final.

// A simple blank final example


final int i;
i = 30;

How are values assigned to blank final members of objects? Values must be assigned in
constructor.

Java
// A sample Java program to demonstrate use and
// working of blank final
class Test {
// We can initialize here, but if we initialize here,
// then all objects get the same value. So we use blank
// final
final int i;

Test(int x)
{
// Since we have already declared i as final above,
// we must initialize i in constructor. If we remove
// this line, we get compiler error.
i = x;
}
}

// Driver Code
class Main {
public static void main(String args[])
{
Test t1 = new Test(10);
System.out.println(t1.i);

Test t2 = new Test(20);


System.out.println(t2.i);
}
}

Output:

10
20

If we have more than one constructors or overloaded constructor in class, then blank final variable
must be initialized in all of them. However constructor chaining can be used to initialize the blank
final variable.

Java
// A Java program to demonstrate that we can
// use constructor chaining to initialize
// final members
class Test
{
final public int i;

Test(int val) { this.i = val; }

Test()
{
// Calling Test(int val)
this(10);
}

public static void main(String[] args)


{
Test t1 = new Test();
System.out.println(t1.i);

Test t2 = new Test(20);


System.out.println(t2.i);
}
}

Output:

10
20

Blank final variables are used to create immutable objects (objects whose members can't be changed
once initialized). This article is contributed by Himanshi Gupta. If you like GeeksforGeeks and would
like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above

Bounded Types with Generics in Java

There may be times when you want to restrict the types that can be used as type arguments in a
parameterized type. For example, a method that operates on numbers might only want to accept
instances of Numbers or their subclasses. This is what bounded type parameters are for.
 Sometimes we don’t want the whole class to be parameterized. In that case, we can create a
Java generics method. Since the constructor is a special kind of method, we can use generics type
in constructors too.
 Suppose we want to restrict the type of objects that can be used in the parameterized type. For
example, in a method that compares two objects and we want to make sure that the accepted
objects are Comparables.
 The invocation of these methods is similar to the unbounded method except that if we will try to
use any class that is not Comparable, it will throw compile time error.

How to Declare a Bounded Type Parameter in Java?

1. List the type parameter's name,


2. Along with the extends keyword
3. And by its upper bound. (which in the below example c is A.)

Syntax
<T extends superClassName>

Note that, in this context, extends is used in a general sense to mean either “extends” (as in classes).
Also, This specifies that T can only be replaced by superClassName or subclasses of superClassName.
Thus, a superclass defines an inclusive, upper limit.

Let’s take an example of how to implement bounded types (extend superclass) with generics.

Java
// This class only accepts type parameters as any class
// which extends class A or class A itself.
// Passing any other type will cause compiler time error

class Bound<T extends A>


{

private T objRef;

public Bound(T obj){


this.objRef = obj;
}

public void doRunTest(){


this.objRef.displayClass();
}
}

class A
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}

class B extends A
{
public void displayClass()
{
System.out.println("Inside sub class B");
}
}

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

public class BoundedClass


{
public static void main(String a[])
{

// Creating object of sub class C and


// passing it to Bound as a type parameter.
Bound<C> bec = new Bound<C>(new C());
bec.doRunTest();

// Creating object of sub class B and


// passing it to Bound as a type parameter.
Bound<B> beb = new Bound<B>(new B());
beb.doRunTest();

// similarly passing super class A


Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();

}
}
Output
Inside sub class C
Inside sub class B
Inside super class A

Now, we are restricted to only type A and its subclasses, So it will throw an error for any other type of
subclasses.

Java
// This class only accepts type parameters as any class
// which extends class A or class A itself.
// Passing any other type will cause compiler time error

class Bound<T extends A>


{

private T objRef;

public Bound(T obj){


this.objRef = obj;
}

public void doRunTest(){


this.objRef.displayClass();
}
}

class A
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}

class B extends A
{
public void displayClass()
{
System.out.println("Inside sub class B");
}
}
class C extends A
{
public void displayClass()
{
System.out.println("Inside sub class C");
}
}

public class BoundedClass


{
public static void main(String a[])
{
// Creating object of sub class C and
// passing it to Bound as a type parameter.
Bound<C> bec = new Bound<C>(new C());
bec.doRunTest();

// Creating object of sub class B and


// passing it to Bound as a type parameter.
Bound<B> beb = new Bound<B>(new B());
beb.doRunTest();

// similarly passing super class A


Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();

Bound<String> bes = new Bound<String>(new String());


bea.doRunTest();
}
}

Output :

error: type argument String is not within bounds of type-variable T

Multiple Bounds

Bounded type parameters can be used with methods as well as classes and interfaces.

Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class,
then B and C should be interfaces. We can’t have more than one class in multiple bounds.

Syntax:
<T extends superClassName & Interface>

Java
class Bound<T extends A & B>
{

private T objRef;

public Bound(T obj){


this.objRef = obj;
}

public void doRunTest(){


this.objRef.displayClass();
}
}

interface B
{
public void displayClass();
}

class A implements B
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}

public class BoundedClass


{
public static void main(String a[])
{
//Creating object of sub class A and
//passing it to Bound as a type parameter.
Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();

}
}
Output
Inside super class A

This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you
can also write an article using contribute.geeksforgeeks.org or mail your article to
contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help
other Geeks. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Operators in Java

Java provides many types of operators which can be used according to the need. They are classified
based on the functionality they provide. Some of the types are:

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

Let's take a look at them in detail.

1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data
types.

 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 - : Subtraction

2. Unary Operators: Unary operators need only one operand. They are used to increment, decrement
or negate a value.

 - : Unary minus, used for negating the values.


 + : Unary plus indicates the positive value (numbers are positive without this, however). It
performs an automatic conversion to int when the type of its operand is the byte, char, or short.
This is called unary numeric promotion.
 ++ : Increment operator, used for incrementing the value by 1. There are two varieties of
increment operators.

o Post-Increment: Value is first used for computing the result and then incremented.
o Pre-Increment: Value is incremented first, and then the result is computed.
 -- : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.

o Post-decrement: Value is first used for computing the result and then decremented.
o Pre-Decrement: Value is decremented first, and then the result is computed.
 ! : Logical not operator, used for inverting a boolean value.

3. Assignment Operator: '=' Assignment operator is used to assigning a value to any variable. It has a
right to left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable
on the left, and therefore right-hand side value must be declared before using it or should be a constant.

The general format of the assignment operator is:

variable = value;

In many cases, the assignment operator can be combined with other operators to build a shorter version
of the statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5.

 +=, for adding left operand with right operand and then assigning it to the variable on the left.
 -=, for subtracting right operand from left operand and then assigning it to the variable on the
left.
 *=, for multiplying left operand with right operand and then assigning it to the variable on the
left.
 /=, for dividing left operand by right operand and then assigning it to the variable on the left.
 %=, for assigning modulo of left operand by right operand and then assigning it to the variable
on the left.

4. Relational Operators: These operators are used to check for relations like equality, greater than,
and less than. They return boolean results after the comparison and are extensively used in looping
statements as well as conditional if-else statements. The general format is,

variable relation_operator value

 Some of the relational operators are-

o ==, Equal to returns true if the left-hand side is equal to the right-hand side.
o !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
o <, less than: returns true if the left-hand side is less than the right-hand side.
o <=, less than or equal to returns true if the left-hand side is less than or equal to the
right-hand side.
o >, Greater than: returns true if the left-hand side is greater than the right-hand side.
o >=, Greater than or equal to returns true if the left-hand side is greater than or equal to
the right-hand side.

5. Logical Operators: These operators are used to perform "logical AND" and "logical OR" operations,
i.e., a function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the
second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has "Logical NOT", which
returns true when the condition is false and vice-versa

Conditional operators are:

 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It has three
operands and hence the name ternary.

The general format is:

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the statements after
the '?' else execute the statements after the ':'.

Java
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

Output
Max of three numbers = 30

7. Bitwise Operators: These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when performing update and
query operations of the Binary indexed trees.

 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one's
complement representation of the input value, i.e., with all bits inverted.

8. Shift Operators: These operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when we have to multiply or
divide a number by two. General format-

number shift_op number_of_places_to_shift;


 <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as multiplying the number with some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids
left as a result. The leftmost bit depends on the sign of the initial number. Similar effect as
dividing the number with some power of two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit is set to 0.

9. instanceof operator: The instance of the operator is used for type checking. It can be used to test if
an object is an instance of a class, a subclass, or an interface. General format-

object instance of class/subclass/interface

Java
// Java program to illustrate
// instance of operator
class operators {
public static void main(String[] args)
{

Person obj1 = new Person();


Person obj2 = new Boy();

// As obj is of type person, it is not an


// instance of Boy or interface
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy,


// whose parent class is person
// and it implements the interface Myinterface
// it is instance of all of these classes
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Person {
}

class Boy extends Person implements MyInterface {


}

interface MyInterface {
}

Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

Precedence and Associativity of Operators

Precedence and associative rules are used when dealing with hybrid equations involving more than one
type of operator. In such cases, these rules determine which part of the equation to consider first, as
there can be many different valuations for the same equation. The below table depicts the precedence
of operators in decreasing order as magnitude, with the top representing the highest precedence and
the bottom showing the lowest precedence.
Interesting Questions about Operators

1. Precedence and Associativity: There is often confusion when it comes to hybrid equations which
are equations having multiple operators. The problem is which part to solve first. There is a golden rule
to follow in these situations. If the operators have different precedence, solve the higher precedence
first. If they have the same precedence, solve according to associativity, that is, either from right to left
or from left to right. The explanation of the below program is well written in comments within the
program itself.

Java
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;

// precedence rules for arithmetic operators.


// (* = / = %) > (+ = -)
// prints a+(b/d)
System.out.println("a+b/d = " + (a + b / d));

// if same precedence then associative


// rules are followed.
// e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)
System.out.println("a+b*d-e/f = "
+ (a + b * d - e / f));
}
}

Output
a+b/d = 20
a+b*d-e/f = 219

2. Be a Compiler: Compiler in our systems uses a lex tool to match the greatest match when generating
tokens. This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too
many of the readers might seem to create a compiler error. But this statement is absolutely correct as
the token created by lex are a, =, b, ++, +, c. Therefore, this statement has a similar effect of first assigning
b+c to a and then incrementing b. Similarly, a=b+++++c; would generate an error as tokens generated
are a, =, b, ++, ++, +, c. which is actually an error as there is no operand after the second unary operand.

Java
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0;
// a=b+++c is compiled as
// b++ +c
// a=b+c then b=b+1
a = b++ + c;
System.out.println("Value of a(b+c), "
+ " b(b+1), c = " + a + ", " + b
+ ", " + c);

// a=b+++++c is compiled as
// b++ ++ +c
// which gives error.
// a=b+++++c;
// System.out.println(b+++++c);
}
}

Output
Value of a(b+c), b(b+1), c = 10, 11, 0

3. Using + over (): When using + operator inside system.out.println() make sure to do addition using
parenthesis. If we write something before doing addition, then string addition takes place, that is,
associativity of addition is left to right, and hence integers are added to a string first producing a string,
and string objects concatenate when using +. Therefore it can create unwanted results.

Java
public class operators {
public static void main(String[] args)
{

int x = 5, y = 8;

// concatenates x and y as
// first x is added to "concatenation (x+y) = "
// producing "concatenation (x+y) = 5"
// and then 8 is further concatenated.
System.out.println("Concatenation (x+y)= " + x + y);

// addition of x and y
System.out.println("Addition (x+y) = " + (x + y));
}
}

Output
Concatenation (x+y)= 58
Addition (x+y) = 13

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks. Please write comments if you find anything incorrect or if you want to share more information
about the topic discussed above.
new operator in Java

When you are declaring a class in java, you are just creating a new data type. A class provides the
blueprint for objects. You can create an object from a class. However obtaining objects of a class is a
two-step process :

1. Declaration : First, you must declare a variable of the class type. This variable does not
define an object. Instead, it is simply a variable that can refer to an object. Below is general
syntax of declaration with an example :
2. Syntax :
3. class-name var-name;
4.
5. Example :
6. // declare reference to an object of class Box
7. Box mybox;
8.

A variable in this state, which currently references no object, can be illustrated as follows
(the variable name, mybox, plus a reference pointing to nothing):

9. Instantiation and Initialization : Second, you must acquire an actual, physical copy of
the object and assign it to that variable. You can do this using the new operator.
The new operator instantiates a class by dynamically allocating(i.e, allocation at run
time) memory for a new object and returning a reference to that memory. This reference
is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated. The new operator is also followed by a call to a class constructor, which
initializes the new object. A constructor defines what occurs when an object of a class is
created. Constructors are an important part of all classes and have many significant
attributes. In below example we will use the default constructor. Below is general syntax
of instantiation and initialization with an example :
10. Syntax :
11. var-name = new class-name();
12.
13. Example :
14. // instantiation via new operator and
15. // initialization via default constructor of class Box
16. mybox = new Box();
17.

Before understanding, how new dynamically allocates memory, let us see


class Box prototype.

class Box
{
double width;
double height;
double depth;
}

A variable after second step, currently refer to a class object, can be illustrated as follows
(the variable name, mybox, plus a reference pointing to Box object):

Hence declaration of a class variable, instantiation of a class and initialization of an object of class can
be together illustrated as follows :
Important points :

1. The above two statements can be rewritten as one statement.


2. Box mybox = new Box();
3.

4. The reference returned by the new operator does not have to be assigned to a class variable. It
can also be used directly in an expression. For example:
5. double height = new Box().height;
6.

7. Since arrays are object in java, hence while instantiating arrays, we use new operator. For
example:
8. int arr[] = new int[5];
9.

10. At this point, you might be wondering why you do not need to use new operator for primitives
data types. The answer is that Java’s primitive types are not implemented as objects. Rather, they
are implemented as "normal" variables. This is done in the interest of efficiency. For object
versions of the primitive data types, refer Wrapper Classes.
11. The phrase "instantiating a class" means the same thing as "creating an object." When you create
an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Assigning object reference variables

When you assign one object reference variable to another object reference variable, you are not creating
a copy of the object, you are only making a copy of the reference. Let us understand this with an example.

Java

// Java program to demonstrate assigning


// of object reference variables

// Box class
class Box
{
double width;
double height;
double depth;
}

// Driver class
public class Test
{
// Driver method
public static void main(String[] args)
{
// creating box object
Box b1 = new Box();

// assigning b2 to b1
Box b2 = b1;

// height via b1 and b2


System.out.println(b1.height);
System.out.println(b2.height);

// changing height via b2


b2.height = 20;

// height via b1 and b2


// after modification through b2
System.out.println(b1.height);
System.out.println(b2.height);
}

}
Output :

0.0
0.0
20.0
20.0

Explanation :

First let us understand what the following fragment does in above program.

Box b1 = new Box();


Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is,
you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong.
Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment
of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer
to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to
which b1 is referring, since they are the same object. Same can be verified by output when we
change height of box via b2.

This situation can be illustrated as follows :


Note : Although b1 and b2 both refer to the same object, they are not linked in any other way. For
example, a subsequent assignment to b1 will simply unhook b1 from the original object without
affecting the object or affecting b2.For example :

Box b1 = new Box();


Box b2 = b1;
// ...
b1 = null;

Here, b1 has been set to null, but b2 still points to the original object.

Passing object references variables to methods

When we pass object reference to a method, the parameter that receives it will refer to the same object
as that referred to by the argument. To know more with examples, refer Passing and Returning Objects
in Java.

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute,
you can also write an article using write.geeksforgeeks.org or mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other
Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.

Bitwise Operators in Java

Operators constitute the basic building block of any programming language. Java too provides many
types of operators which can be used according to the need to perform various calculations and
functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
provide. Here are a few types:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

This article explains all that one needs to know regarding Bitwise Operators.

Bitwise Operators

Bitwise operators are used to performing the manipulation of individual bits of a number. They can be
used with any integral type (char, short, int, etc.). They are used when performing update and query
operations of the Binary indexed trees.

Now let's look at each one of the bitwise operators in Java:

1. Bitwise OR (|)

This operator is a binary operator, denoted by '|'. It returns bit by bit OR of input values, i.e., if either of
the bits is 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

2. Bitwise AND (&)


This operator is a binary operator, denoted by '&.' It returns bit by bit AND of input values, i.e., if both
bits are 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

3. Bitwise XOR (^)

This operator is a binary operator, denoted by '^.' It returns bit by bit XOR of input values, i.e., if
corresponding bits are different, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

4. Bitwise Complement (~)

This operator is a unary operator, denoted by '~.' It returns the one's complement representation of the
input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0.

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)

Note: Compiler will give 2's complement of that number, i.e., 2's complement of 10 will be -6.
Java
// Java program to illustrate
// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111 11111111
11111010
// will give 1's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}

Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5

Java
// Demonstrating the bitwise logical operators

class GFG {
public static void main (String[] args) {

String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};

// initializing the values of a and b


int a=3; // 0+2+1 or 0011 in binary
int b=6; // 4+2+0 or 0110 in binary

// bitwise or
int c= a | b;

// bitwise and
int d= a & b;

// bitwise xor
int e= a ^ b;

// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;

System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}

Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100

Bit-Shift Operators (Shift Operators)

Shift operators are used to shift the bits of a number left or right, thereby multiplying or dividing the
number by two, respectively. They can be used when we have to multiply or divide a number by two.

Syntax:

number shift_op number_of_places_to_shift;

Types of Shift Operators:

Shift Operators are further divided into 4 types. These are:

1. Signed Right shift operator (>>)


2. Unsigned Right shift operator (>>>)
3. Left shift operator (<<)
4. Unsigned Left shift operator (<<<)

Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java.
Bitwise Right Shift Operators in Java

In C/C++ there is only one right shift operator '>>' which should be used only for positive integers or
unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++,
and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports
following two right shift operators.

Here we will be discussing both of right shift operators as listed:

 Signed right shift ">>"


 Unsigned right shift ">>>"

Type 1: Signed Right Shift

In Java, the operator '>>' is signed right shift operator. All integers are signed in Java, and it is fine to
use >> for negative numbers. The operator '>>' uses the sign bit (leftmost bit) to fill the trailing positions
after the shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is
used as a filler. For example, if the binary representation of a number is 10....100, then right shifting it
by 2 using >> will make it 11.......1.

Example:

Java
// Java Program to Illustrate Signed Right Shift Operator

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

int x = -4;
System.out.println(x >> 1);

int y = 4;
System.out.println(y >> 1);
}
}

Output
-2
2

Type 2: Unsigned Right Shift Operator

In Java, the operator '>>>' denotes unsigned right shift operator and always fill 0 irrespective of the sign
of the number.

Example:

Java
// Java Program to Illustrate Unsigned Right Shift Operator

// Main class
class GFG {

// main driver method


public static void main(String args[])
{
// x is stored using 32 bit 2's complement form.
// Binary representation of -1 is all 1s (111..1)
int x = -1;

// The value of 'x>>>29' is 00...0111


System.out.println(x >>> 29);

// The value of 'x>>>30' is 00...0011


System.out.println(x >>> 30);

// The value of 'x>>>31' is 00...0001


System.out.println(x >>> 31);
}
}

Output
7
3
1

instanceof Keyword in Java

instanceof is a keyword that is used for checking if a reference variable is containing a given type of
object reference or not. Following is a Java program to show different behaviors of instanceof.
Henceforth it is known as a comparison operator where the instance is getting compared
to type returning boolean true or false as in java we do not have 0 and 1 boolean return types.

Example:

Java
// Java Program to Illustrate instanceof Keyword

// Importing required I/O classes


import java.io.*;

// Main class
class GFG {
public static void main(String[] args)
{

// Creating object of class inside main()


GFG object = new GFG();
// Returning instanceof
System.out.println(object instanceof GFG);
}
}

Output
true

Implementation: Here we will be creating sample classes with a parent-child relationship.

Example 1:

Java
// Java program to demonstrate working of instanceof Keyword

// Class 1
// Parent class
class Parent {}

// Class 2
// Child class
class Child extends Parent {}

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of child class


Child cobj = new Child();

// A simple case
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println(
"cobj is NOT instance of Child");

// instanceof returning true for Parent class also


if (cobj instanceof Parent)
System.out.println(
"cobj is instance of Parent");
else
System.out.println(
"cobj is NOT instance of Parent");

// instanceof returns true for all ancestors

// Note : Object is ancestor of all classes in Java


if (cobj instanceof Object)
System.out.println(
"cobj is instance of Object");
else
System.out.println(
"cobj is NOT instance of Object");
}
}

Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object

Example 2: instanceof returning false for null

Java

// Java program to demonstrate that instanceof


// returns false for null

class Test { }

class Main
{
public static void main(String[] args)
{
Test tobj = null;

// A simple case
if (tobj instanceof Test)
System.out.println("tobj is instance of Test");
else
System.out.println("tobj is NOT instance of Test");
}
}

Output:

tobj is NOT instance of Test

Example 3: Parent object is not an instance of Child

Java

// A Java program to show that a parent object is


// not an instance of Child

class Parent { }
class Child extends Parent { }

class Test
{
public static void main(String[] args)
{
Parent pobj = new Parent();
if (pobj instanceof Child)
System.out.println("pobj is instance of Child");
else
System.out.println("pobj is NOT instance of Child");
}
}

Output:

pobj is NOT instance of Child

Example 4: Parent reference referring to a Child is an instance of Child

Java

// A Java program to show that a parent reference


// referring to a Child is an instance of Child

class Parent { }
class Child extends Parent { }

class Test
{
public static void main(String[] args)
{
// Reference is Parent type but object is
// of child type.
Parent cobj = new Child();
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");
}
}

Output:
cobj is an instance of Child

Now, the application of instanceof keyword is as follows:

We have seen here that a parent class data member is accessed when a reference of parent type refers
to a child object. We can access child data members using typecasting.

Syntax:

((child_class_name) Parent_Reference_variable).func.name()

When we do typecast, it is always a good idea to check if the typecasting is valid or not. instanceof helps
us here. We can always first check for validity using instancef, then do typecasting.

Example

Java
// Java program to demonstrate that non-method
// members are accessed according to reference
// type (Unlike methods which are accessed according
// to the referred object)

class Parent
{
int value = 1000;
}

class Child extends Parent


{
int value = 10;
}

// Driver class
class Test
{
public static void main(String[] args)
{
Parent cobj = new Child();
Parent par = cobj;

// Using instanceof to make sure that par


// is a valid reference before typecasting
if (par instanceof Child)
{
System.out.println("Value accessed through " +
"parent reference with typecasting is " +
((Child)par).value);
}
}
}

Output:

Value accessed through parent reference with typecasting is 10

Comparison of Autoboxed Integer objects in Java

When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For
example the statement "Integer x = 10" creates an object 'x' with value 10.

Following are some interesting output questions based on comparison of Autoboxed Integer objects.

Predict the output of following Java Program


Java

// file name: Main.java


public class Main {
public static void main(String args[]) {
Integer x = 400, y = 400;
if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output:
Not Same

Since x and y refer to different objects, we get the output as "Not Same"
The output of following program is a surprise from Java.
Java

// file name: Main.java


public class Main {
public static void main(String args[]) {
Integer x = 40, y = 40;
if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output:
Same

In Java, values from -128 to 127 are cached, so the same objects are returned. The implementation of
valueOf() uses cached objects if the value is between -128 to 127.

If we explicitly create Integer objects using new operator, we get the output as "Not Same". See the
following Java program. In the following program, valueOf() is not used.

Java

// file name: Main.java


public class Main {
public static void main(String args[]) {
Integer x = new Integer(40), y = new Integer(40);
if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output:
Not Same

Predict the output of the following program. This example is contributed by Bishal Dubey.

JAVA

class GFG
{
public static void main(String[] args)
{
Integer X = new Integer(10);
Integer Y = 10;

// Due to auto-boxing, a new Wrapper object


// is created which is pointed by Y
System.out.println(X == Y);
}
}
Output:

false

Explanation: Two objects will be created here. First object which is pointed by X due to calling of new
operator and second object will be created because of Auto-boxing.

Addition and Concatenation Using + Operator in Java

Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves
the same way as it was supposed to because the decimal system was getting added up deep down at
binary level and the resultant binary number is thrown up at console in the generic decimal system. But
geeks even wondered what if we play this + operator between integer and string.

Example
Java
// Java Program to Illustrate Addition and Concatenation

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Print statements to illustrate


// addition and Concatenation
// using + operators over string and integer
// combination
System.out.println(2 + 0 + 1 + 6 + "GeeksforGeeks");
System.out.println("GeeksforGeeks" + 2 + 0 + 1 + 6);
System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + 2 + 0 + 1 + 6);
System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + (2 + 0 + 1 + 6));
}
}

Output
9GeeksforGeeks
GeeksforGeeks2016
8GeeksforGeeks2016
8GeeksforGeeks9

Output Explanation: This unpredictable output is due to the fact that the compiler evaluates the given
expression from left to right given that the operators have the same precedence. Once it encounters the
String, it considers the rest of the expression as of a String (again based on the precedence order of the
expression).

System.out.println(2 + 0 + 1 + 6 + "GeeksforGeeks");

It prints the addition of 2,0,1 and 6 which is equal to 9

System.out.println("GeeksforGeeks" + 2 + 0 + 1 + 6);

It prints the concatenation of 2,0,1 and 6 which is 2016 since it encounters the string initially. Basically,
Strings take precedence because they have a higher casting priority than integers do.

System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + 2 + 0 + 1 + 6);


it prints the addition of 2,0,1 and 5 while the concatenation of 2,0,1 and 6 is based on the above-given ex
amples.
System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + (2 + 0 + 1 + 6));

It prints the addition of both 2,0,1 and 5 and 2,0,1 and 6 based due to the precedence of ( ) over +. Hence
expression in ( ) is calculated first and then further evaluation takes place.

Java Numeric Promotion in Conditional Expression

With recurrence use of if-else condition in programming which is tend to occur no matter how much
we optimize our code. So taking this factor into consideration, conditional operator was introduced
making our job of writing code easier as it do have a specific syntax in accordance to which it does check
the condition passed to it. The conditional operator ? : uses the boolean value of one expression to
decide which of two other expressions should be evaluated. Let us do have an illustration to get used to
with its syntax.

Illustration:

Object obj ;
if (true) {
obj = new Integer(4) ;
} else {
obj = new Float(2.0);
}

So, with the usage of conditional operator we expect the expression whose syntax is as follows:

Object obj = true ? new Integer(4) : new Float(2.0));

Note: But the result of running the code gives an unexpected result.
Example:

Java
// Java Program to Demonstrate
// Replacing of Conditional Operator
// with If-else and viceversa

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main (String[] args) {

// Expression 1 (using ?: )
// Automatic promotion in conditional expression
Object o1 = true ? new Integer(4) : new Float(2.0);

// Printing the output using conditional operator


System.out.println(o1);

// Expression 2 (Using if-else)


// No promotion in if else statement
Object o2;
if (true)
o2 = new Integer(4);
else
o2 = new Float(2.0);

// Printing the output using if-else statement


System.out.println(o2);
}
}

Output:

According to Java Language Specification Section 15.25, the conditional operator will implement
numeric type promotion if there are two different types as 2nd and 3rd operand. The rules of
conversion are defined at Binary Numeric Promotion. Therefore, according to the rules given, If either
operand is of type double, the other is converted to double and hence 4 becomes 4.0. Whereas, the,
if/else construct, does not perform numeric promotion and hence behaves as expected.

Scanner Class 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. It 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.
 To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream. We may pass an object of class File if we want to read
input from a file.
 To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function returns the next token/word
in the input as a string and charAt(0) function returns the first character in that string.
 The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements
that have some meaning to the Java compiler. For example, Suppose there is an input string: How
are you
In this case, the scanner object will read the entire line and divides the string into tokens: "How",
"are" and "you". The object then iterates over each token and reads each token using its different
methods.

Let us look at the code snippet to read data of various data types.

Java

// Java program to read data of various types using Scanner class.


import java.util.Scanner;
public class ScannerDemo1
{
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();

// Character input
char gender = sc.next().charAt(0);

// Numerical data input


// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();

// Print the values to check if the input was correctly obtained.


System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}

Input :

Geek
F
40
9876543210
9.9

Output :

Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9

Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF
marker encountered).

Then, we check if the scanner's input is of the type we want with the help of hasNextXYZ() functions
where XYZ is the type we are interested in. The function returns true if the scanner has a token of that
type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string,
we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

Let us look at the code snippet to read some numbers from console and print their mean.

Java

// Java program to read some values using Scanner


// class and print their mean.
import java.util.Scanner;

public class ScannerDemo2


{
public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// Initialize sum and count of input elements
int sum = 0, count = 0;

// Check if an int value is available


while (sc.hasNextInt())
{
// Read an int value
int num = sc.nextInt();
sum += num;
count++;
}
int mean = sum / count;
System.out.println("Mean: " + mean);
}
}

Input:

101
223
238
892
99
500
728

Output:

Mean: 397

Command Line Arguments in Java

Java command-line argument is an argument i.e. passed at the time of running the Java program. In
the command line, the arguments passed from the console can be received in the java program and they
can be used as input. The users can pass the arguments during the execution bypassing the command-
line arguments inside the main() method.

We need to pass the arguments as space-separated values. We can pass both strings and primitive data
types(int, double, float, char, etc) as command-line arguments. These arguments convert into a string
array and are provided to the main() function as a string array argument.

When command-line arguments are supplied to JVM, JVM wraps these and supplies them to args[]. It
can be confirmed that they are wrapped up in an args array by checking the length of args using
args.length.
Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass into the
main() function. We can check these arguments using args.length method. JVM stores the first
command-line argument at args[0], the second at args[1], the third at args[2], and so on.

Illustration:

Java
// Java Program to Illustrate First Argument

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Printing the first argument
System.out.println(args[0]);
}
}

Output:

Implementation:

If we run a Java Program by writing the command "java Hello Geeks At GeeksForGeeks" where the
name of the class is "Hello", then it will run up to Hello. It is a command up to "Hello" and after that i.e
"Geeks At GeeksForGeeks", these are command-line arguments.

Example:

Java
// Java Program to Check for Command Line Arguments

// Class
class GFG {
// Main driver method
public static void main(String[] args)
{

// Checking if length of args array is


// greater than 0
if (args.length > 0) {

// Print statements
System.out.println("The command line"
+ " arguments are:");

// Iterating the args array


// using for each loop
for (String val : args)

// Printing command line arguments


System.out.println(val);
}

else

// Print statements
System.out.println("No command line "
+ "arguments found.");
}
}

Output
No command line arguments found.

Steps to Run the Above Program are: To compile and run a java program in the command prompt,
follow the steps written below.

 Save the program as Hello.java


 Open the command prompt window and compile the program- javac Hello.java
 After a successful compilation of the program, run the following command by writing the
arguments- java Hello
 For example - java Hello Geeks at GeeksforGeeks
 Press Enter and you will get the desired output.

Output:
Character Stream Vs Byte Stream in Java

A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially
access a file. I/O Stream means an input source or output destination representing different types of
sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode
character streams and byte streams of non-Unicode text.

 Input Stream: reads data from the source.


 Output Stream: writes data to a destination.

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. 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.
Key points while using and dealing with any of the above streams are as follows:

1. Names of character streams typically end with Reader/Writer and names of byte streams end
with InputStream/OutputStream
2. The streams used in example codes are unbuffered streams and less efficient. We typically use
them with buffered readers/writers for efficiency. We will soon be discussing use
BufferedReader/BufferedWriter (for character stream) and
BufferedInputStream/BufferedOutputStream (for byte stream) classes.
3. It is always recommended to close the stream if it is no longer in use. This ensures that the
streams won't be affected if any error occurs.
4. The above codes may not run in online compilers as files may not exist.

Character Stream

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to
read/write data character by character. For example, FileReader and FileWriter are character streams
used to read from the source and write to the destination.
Example

Java
// Java Program illustrate Reading
// a File in Human Readable
// Format Using FileReader Class

// Importing required classes


import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
throws IOException
{

// Initially assigning null as we have not read


// anything
FileReader sourceStream = null;

// Try block to check for exceptions


try {

// Reading from file


sourceStream = new FileReader(
"/Users/mayanksolanki/Desktop/demo.rtf");

// Reading sourcefile and writing content to


// target file character by character.

int temp;

// If there is content inside file


// than read
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);

// Display message for successful execution of program


System.out.print("Program successfully executed");
}

// finally block that executes for sure


// where we are closing file connections
// to avoid memory leakage
finally {

// Closing stream as no longer in use


if (sourceStream != null)
sourceStream.close();
}
}
}

Output: Writes content to the target file character by character

Program successfully executed

Byte Stream

Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the
source and FileOutputStream to write to the destination.

Example:

Java
// Java Program Illustrate ByteStream Class to
// Copy Contents of One File to Another File

// Importing required classes


import java.io.*;
// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
throws IOException
{

// Initially assigning null ot objects for


// reading and writing to file
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;

// Try block to check for exceptions


try {

// Passing the files via local directory


sourceStream = new FileInputStream(
"/Users/mayanksolanki/Desktop/demo.rtf");
targetStream = new FileOutputStream(
"/Users/mayanksolanki/Desktop/democopy.rtf");

// Reading source file and writing content to


// target file byte by byte
int temp;

// If there is content inside file


// than read
while ((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);

// Display message for successful execution of program


System.out.print("Program successfully executed");
}

// finally block that executes for sure


// where we are closing file connections
// to avoid memory leakage
finally {

if (sourceStream != null)
sourceStream.close();

if (targetStream != null)
targetStream.close();
}
}
}

Output:

Program successfully executed

DoubleStream mapToObj() in Java

DoubleStream mapToObj() returns an object-valued Stream consisting of the results of applying the
given function.

Syntax:

<U> Stream<U>
mapToObj(DoubleFunction<?
extends U> mapper)

Parameters: This method accepts following parameters:

1. U: The element type of the new stream.


2. Stream : A sequence of elements supporting sequential and parallel aggregate operations.
3. DoubleFunction : Represents a function that accepts an double-valued argument and produces
a result.
4. mapper : A stateless function to apply to each element.

Return Value: The function returns an object-valued Stream consisting of the results of applying the
given function.

Below examples illustrate the mapToObj() method:

Example 1 :
Java

// Java code for DoubleStream mapToObj


// (DoubleFunction mapper)
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.DoubleStream;

class GFG {

// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(3.4, 4.5,
6.7, 8.9);

// Using DoubleStream mapToObj(DoubleFunction mapper)


// and displaying an object-valued Stream
// consisting of the results of
// applying the given function
stream.mapToObj(num ->{return num * num * num ;})
.forEach(System.out::println);

}
}

Output:

39.303999999999995
91.125
300.76300000000003
704.969

Example 2 :
Java

// Java code for DoubleStream mapToObj


// (DoubleFunction mapper)

import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Stream;
import java.util.stream.DoubleStream;

class GFG {

// Driver code
public static void main(String[] args)
{
// Creating a DoubleStream
DoubleStream stream = DoubleStream.of(3.4, 4.5,
6.7, 8.9);

// Creating a Stream
// Using DoubleStream mapToObj(DoubleFunction mapper)
Stream<BigDecimal> stream1 = stream
.mapToObj(BigDecimal::valueOf);

// Displaying an object-valued Stream


// consisting of the results of
// applying the given function.
stream1.forEach(num -> System.out.println
(num.add(BigDecimal.TEN)));
}
}

Output:

13.4
14.5
16.7
18.9

Related Articles :

 IntStream mapToObj() in Java


 Stream map() in Java with examples
 LongStream mapToObj() in Java
 Scanner and nextChar() in Java

 Scanner class in Java supports nextInt(), nextLong(), nextDouble() etc. But there is no nextChar()
(See this for examples)

To read a char, we use next().charAt(0). next() function returns the next token/word in the
input as a string and charAt(0) function returns the first character in that string.

Java

 // Java program to read character using Scanner
 // class
 import java.util.Scanner;
 public class ScannerDemo1
 {
 public static void main(String[] args)
 {
 // Declare the object and initialize with
 // predefined standard input object
 Scanner sc = new Scanner(System.in);

 // Character input
 char c = sc.next().charAt(0);

 // Print the read value
 System.out.println("c = "+c);
 }
 }
 Input :
 g

Output :
 c = g

Difference Between Scanner and BufferedReader Class in Java

In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner
class is a simple text scanner that can parse primitive types and strings. It internally uses regular
expressions to read different types while on the other hand BufferedReader class reads text from a
character-input stream, buffering characters so as to provide for the efficient reading of the sequence
of characters

The eccentric difference lies in reading different ways of taking input via the next() method that is
justified in the below programs over the similar input set.

Example 1:

Java
// Java Program to Illustrate Scanner Class

// Importing Scanner class from


// java.util package
import java.util.Scanner;
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Creating object of Scanner class to


// read input from keyboard
Scanner scn = new Scanner(System.in);

System.out.println("Enter an integer");

// Using nextInt() to parse integer values


int a = scn.nextInt();

System.out.println("Enter a String");

// Using nextLine() to parse string values


String b = scn.nextLine();

// Display name and age entered above


System.out.printf("You have entered:- " + a + " "
+ "and name as " + b);
}
}

Output:

Let us try the same using Buffer class and same Input below as follows:

Example 2:
Java
// Java Program to Illustrate BufferedReader Class

// Importing required class


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
throws IOException
{

// Creating object of class inside main() method


BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("Enter an integer");

// Taking integer input


int a = Integer.parseInt(br.readLine());

System.out.println("Enter a String");

String b = br.readLine();

// Printing input entities above


System.out.printf("You have entered:- " + a
+ " and name as " + b);
}
}

Output:
Outputs explanation: In Scanner class if we call nextLine() method after any one of the seven
nextXXX() method then the nextLine() does not read values from console and cursor will not come into
console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(),
nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for the Scanner class,
due to nextXXX() methods ignoring newline character and nextLine() only reads till the first newline
character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this
problem will not occur because nextLine() will consume the newline character.

Tip: See this for the corrected program. This problem is same as scanf() followed by gets() in
C/C++. This problem can also be solved by using next() instead of nextLine() for taking input of
strings as shown here.
Following are the Major Differences between Scanner and BufferedReader Class in Java

 BufferedReader is synchronous while Scanner is not. BufferedReader should be used if we are


working with multiple threads.
 BufferedReader has a significantly larger buffer memory than Scanner.
 The Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte
buffer), but it's more than enough.
 BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of
input data and BufferedReader simply reads a sequence of characters.

Formatted output in Java

Sometimes in Competitive programming, it is essential to print the output in a given specified format.
Most users are familiar with printf function in C. Let us discuss how we can format the output in Java.

There are different ways in which we can format output in Java. Some of them are given below.

 Using System.out.printf()
 Using DecimalFormat class
 Using SimpleDateFormat class (for formatting Dates)

1. Formatting output using System.out.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.

Java
// Java program to demonstrate working of printf()

class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf(
"Printing simple integer: x = %d\n", x);

// this will print it upto 2 decimal places


System.out.printf(
"Formatted with precision: PI = %.2f\n",
Math.PI);

float n = 5.2f;

// automatically appends zero to the rightmost part


// of decimal
System.out.printf(
"Formatted to specific width: n = %.4f\n", n);

n = 2324435.3f;

// here number is formatted from right margin and


// occupies a width of 20 characters
System.out.printf(
"Formatted to right margin: n = %20.4f\n", n);
}
}

Output
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

Note: System.out.format() is equivalent to printf() and can also be used.

2. Formatting using DecimalFormat class


DecimalFormat is used to format decimal numbers.

Java
// Java program to demonstrate working of DecimalFormat
import java.text.DecimalFormat;

class JavaFormatter2 {
public static void main(String args[])
{
double num = 123.4567;

// prints only numeric part of a floating number


DecimalFormat ft = new DecimalFormat("####");
System.out.println("Without fraction part: num = "
+ ft.format(num));

// this will print it upto 2 decimal places


ft = new DecimalFormat("#.##");
System.out.println(
"Formatted to Give precision: num = "
+ ft.format(num));

// automatically appends zero to the rightmost part


// of decimal instead of #,we use digit 0
ft = new DecimalFormat("#.000000");
System.out.println(
"appended zeroes to right: num = "
+ ft.format(num));

// automatically appends zero to the leftmost of


// decimal number instead of #,we use digit 0
ft = new DecimalFormat("00000.00");
System.out.println(
"formatting Numeric part : num = "
+ ft.format(num));

// formatting money in dollars


double income = 23456.789;
ft = new DecimalFormat("$###,###.##");
System.out.println("your Formatted Dream Income : "
+ ft.format(income));
}
}

Output
Without fraction part: num = 123
Formatted to Give precision: num = 123.46
appended zeroes to right: num = 123.456700
formatting Numeric part : num = 00123.46
your Formatted Dream Income : $23,456.79

3. Formatting dates and parsing using SimpleDateFormat class

This class is present in java.text package.

Java
// Java program to demonstrate working of SimpleDateFormat

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Formatter3 {
public static void main(String args[])
throws ParseException
{
// Formatting as per given pattern in the argument
SimpleDateFormat ft
= new SimpleDateFormat("dd-MM-yyyy");
String str = ft.format(new Date());
System.out.println("Formatted Date : " + str);

// parsing a given String


str = "02/18/1995";
ft = new SimpleDateFormat("MM/dd/yyyy");
Date date = ft.parse(str);

// this will print the date as per parsed string


System.out.println("Parsed Date : " + date);
}
}

Output
Formatted Date : 24-01-2022
Parsed Date : Sat Feb 18 00:00:00 UTC 1995
Fast I/O in Java in Competitive Programming

Using Java in competitive programming is not something many people would suggest just because of its
slow input and output, and well indeed it is slow.

In this article, we have discussed some ways to get around the difficulty and change the verdict from
TLE to (in most cases) AC.

Example:
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4

1. Scanner Class (easy, less typing, but not recommended very slow, refer this for reasons of
slowness):

In most of the cases, we get TLE while using scanner class. It uses built-in nextInt(), nextLong(),
nextDouble methods to read the desired object after initiating scanner object with the input stream(e.g.
System.in). The following program many times gets time limit exceeded verdict and therefore not of
much use.

Java
// Working program using Scanner
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

2. BufferedReader (fast, but not recommended as it requires a lot of typing):

The Java.io.BufferedReader class reads text from a character-input stream, buffering characters to
provide for the efficient reading of characters, arrays, and lines. With this method, we will have to parse
the value every time for the desired type. Reading multiple words from a single line adds to its
complexity because of the use of Stringtokenizer and hence this is not recommended. These get
accepted with a running time of approx 0.89 s.but still as you can see it requires a lot of typing altogether
and therefore method 3 is recommended.

Java
// Working program using BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {


public static void main(String[] args)
throws IOException
{

BufferedReader br = new BufferedReader(


new InputStreamReader(System.in));

StringTokenizer st
= new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int count = 0;
while (n-- > 0) {
int x = Integer.parseInt(br.readLine());
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

3.Userdefined FastReader Class (which uses bufferedReader and StringTokenizer):

This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of
user-defined methods for less typing and therefore a faster input altogether. These get accepted with a
time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough
to meet the needs of most of the question in competitive coding.

Java
// Working program with FastReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {


static class FastReader {
BufferedReader br;
StringTokenizer st;

public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}

String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}

int nextInt() { return Integer.parseInt(next()); }

long nextLong() { return Long.parseLong(next()); }

double nextDouble()
{
return Double.parseDouble(next());
}

String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}

public static void main(String[] args)


{
FastReader s = new FastReader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

4.Using Reader Class:

There is yet another fast way through the problem, I would say the fastest way but is not recommended
since it requires very cumbersome methods in its implementation. It uses inputDataStream to read
through the stream of data and uses read() method and nextInt() methods for taking inputs. This is by
far the fastest ways of taking input but is difficult to remember and is cumbersome in its approach.
Below is the sample program using this method. These get accepted with a surprising time of just 0.28
s. Although this is ultra-fast, it is clearly not an easy method to remember.

Java
// Working program using Reader Class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {


static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public Reader(String file_name) throws IOException


{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}

public int nextInt() throws IOException


{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');

if (neg)
return -ret;
return ret;
}

public long nextLong() throws IOException


{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}

public double nextDouble() throws IOException


{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();

do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');

if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}

if (neg)
return -ret;
return ret;
}

private void fillBuffer() throws IOException


{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException


{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}

public void close() throws IOException


{
if (din == null)
return;
din.close();
}
}

public static void main(String[] args)


throws IOException
{
Reader s = new Reader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0) {
int x = s.nextInt();
if (x % k == 0)
count++;
}
System.out.println(count);
}
}

Ways to read input from console in Java

In Java, there are four different ways for reading input from the user in the command line
environment(console).

1.Using Buffered Reader Class


This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping
the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader,
we can read input from the user in the command line.

 The input is buffered for efficient reading.


 The wrapping code is hard to remember.

Implementation:

Java
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));

// Reading data using readLine


String name = reader.readLine();

// Printing the read line


System.out.println(name);
}
}

Input:

Geek

Output:

Auxiliary Space : O(1)

Geek
Note:

To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple
values, we use split().

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however, it is also can be used to read input
from the user in the command line.

 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
 Regular expressions can be used to find tokens.
 The reading methods are not synchronized

To see more differences, please see this article.

Java
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;

class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string " + s);

int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}

Input:

GeeksforGeeks
12
3.4

Output:

You entered string GeeksforGeeks


You entered integer 12
You entered float 3.4

3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it
can be used for reading password-like input without echoing the characters entered by the user; the
format string syntax can also be used (like System.out.printf()).

Advantages:

 Reading password without echoing the entered characters.


 Reading methods are synchronized.
 Format string syntax can be used.
 Does not work in non-interactive environment (such as in an IDE).
Java
// Java program to demonstrate working of System.console()
// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println("You entered string " + name);


}
}

Input:

GeeksforGeeks

Output:

You entered string GeeksforGeeks

4. Using Command line argument

Most used user input for competitive coding. The command-line arguments are stored in the String
format. The parseInt method of the Integer class converts string argument into Integer. Similarly, for
float and others during execution. The usage of args[] comes into existence in this input form. The
passing of information takes place during the program run. The command line is given to args[]. These
programs have to be run on cmd.
Code:

Java
// Program to check for command line arguments
class Hello {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if (args.length > 0) {
System.out.println(
"The command line arguments are:");

// iterating the args array and printing


// the command line arguments
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}

Command Line Arguments:

javac GFG1.java
java Main Hello World

Output:

The command line arguments are:


Hello
World

Please refer this for more faster ways of reading input.

Loops in Java

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for
executing the loops. While all the ways provide similar basic functionality, they differ in their syntax
and condition checking time.

 while loop: A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Syntax :

while (boolean condition)


{
loop statements...
}

 Flowchart:

o While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this
reason it is also called Entry control loop
o Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for the
next iteration.
o When the condition becomes false, the loop terminates which marks the end of its life
cycle.
 for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.

Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}

 Flowchart:
o Initialization condition: Here, we initialize the variable in use. It marks the start of a for
loop. An already declared variable can be used or a variable can be declared, local to loop
only.
o Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
o Statement execution: Once the condition is evaluated to true, the statements in the loop
body are executed.
o Increment/ Decrement: It is used for updating the variable for next iteration.
o Loop termination:When the condition becomes false, the loop terminates marking the
end of its life cycle.
 do while: do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.

Syntax:

do
{
statements..
}
while (condition);
 Flowchart:
o do while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
o After the execution of the statements, and update of the variable value, the condition is
checked for true or false value. If it is evaluated to true, next iteration of loop starts.
o When the condition becomes false, the loop terminates which marks the end of its life
cycle.
o It is important to note that the do-while loop will execute its statements atleast once
before any condition is checked, and therefore is an example of exit control loop.

Pitfalls of Loops

 Infinite loop: One of the most common mistakes while implementing any sort of looping is that
it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails
for some reason. Examples:

Java

//Java program to illustrate various pitfalls.


public class LooppitfallsDemo
{
public static void main(String[] args)
{

// infinite loop because condition is not apt


// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
int x = 5;

// infinite loop because update statement


// is not provided.
while (x == 5)
{
System.out.println("In the loop");
}
}
}

Another pitfall is that you might be adding something into you collection object through loop and you
can run out of memory. If you try and execute the below program, after some time, out of memory
exception will be thrown.

Java

//Java program for out of memory exception.


import java.util.ArrayList;
public class Integer1
{
public static void main(String[] args)
{
ArrayList<Integer> ar = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++)
{
ar.add(i);
}
}
}

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space


at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)

For-each loop in Java


Prerequisite: Decision making in Java
For-each is another array traversing technique like for loop, while loop, do-while loop introduced in
Java5.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you declare a variable that is the
same type as the base type of the array, followed by a colon, which is then followed by the array
name.
 In the loop body, you can use the loop variable you created rather than using an indexed array
element.

 It's commonly used to iterate over an array or a Collections class (eg, ArrayList)

Syntax:

for (type var : array)


{
statements using var;
}

is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}

Java

// Java program to illustrate


// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };

int highest_marks = maximum(marks);


System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
}

Output:

The highest score is 132

Limitations of for-each loop


decision-making

1. For-each loops are not appropriate when you want to modify the array:

for (int num : marks)


{
// only changes num, not the array element
num = num*2;
}

2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop
for (int num : numbers)
{
if (num == target)
{
return ???; // do not know the index of num
}
}

3. For-each only iterates forward over the array in single steps

// cannot be converted to a for-each loop


for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}

4. For-each cannot process two decision making statements at once

// cannot be easily converted to a for-each loop


for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}

5. For-each also has some performance overhead over simple iteration:


Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime - startTime) + "
ms");

// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime -
startTime) + " ms");

// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: " +
(endTime - startTime) + " ms");

// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] :: " +
(endTime - startTime) + " ms");
}
}

// This code is contributed by Ayush Choudhary @gfg(code_ayush)

Decision Making in Java (if, if-else, switch, break, continue, jump)

Decision Making in programming is similar to decision-making in real life. In programming also face
some situations where we want a certain block of code to be executed when some condition is fulfilled.

A programming language uses control statements to control the flow of execution of a program based
on certain conditions. These are used to cause the flow of execution to advance and branch based on
changes to the state of a program.

Java's Selection statements:

 if
 if-else
 nested-if
 if-else-if
 switch-case
 jump - break, continue, return

1. if: if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.

Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts boolean values - if
the value is true then it will execute the block of statements under it.
If we do not provide the curly braces '{' and '}' after if( condition ) then by default if statement will
consider the immediate one statement to be inside its block. For example,

if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.

Example:

Java
// Java program to illustrate If statement
class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}

Output
I am Not in if

2. if-else: The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won't. But what if we want to do something else if the condition is false.
Here comes the else statement. We can use the else statement with if statement to execute a block of
code when the condition is false.

Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:

Java
// Java program to illustrate if-else statement
class IfElseDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

Output
i is smaller than 15

Time Complexity: O(1)

Auxiliary Space : O(1)

3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements
mean an if statement inside an if statement. Yes, java allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.
Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:

Java
// Java program to illustrate nested-if statement

class NestedIfDemo {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15) {
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}

Output
i is smaller than 15
i is smaller than 12 too

Time Complexity: O(1)

Auxiliary Space: O(1)

4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:

Java
// Java program to illustrate if-else-if ladder

class ifelseifDemo {
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

Output
i is 20

Time Complexity: O(1)

Auxiliary Space: O(1)


5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.

Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

 The expression can be of type byte, short, int char, or an enumeration. Beginning with
JDK7, expression can also be of type String.
 Duplicate case values are not allowed.
 The default statement is optional.
 The break statement is used inside the switch to terminate a statement sequence.
 The break statement is optional. If omitted, execution will continue on into the next case.

6. jump: Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.

 Break: In Java, a break is majorly used for:

o Terminate a sequence in a switch statement (discussed above).


o To exit a loop.
o Used as a "civilized" form of goto.
 Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. The
continue statement performs such an action.
Example:

Java
// Java program to illustrate using
// continue in an if statement
class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}

Output
1 3 5 7 9

Time Complexity: O(1)

Auxiliary Space: O(1)


 Return: The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method.

Example:

Java
// Java program to illustrate using return
class Return {
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}

Output
Before the return.

Time Complexity: O(1)

Auxiliary Space: O(1)

Switch Statement in Java

The switch statement is a multi-way branch statement. In simple words, the Java switch statement
executes one statement from multiple conditions. It is like an if-else-if ladder statement. It provides an
easy way to dispatch execution to different parts of code based on the value of the expression. Basically,
the expression can be a byte, short, char, and int primitive data types. It basically tests the equality of
variables against multiple values.

Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums
and string. Beginning with JDK7, it also works with enumerated types (Enums in java),
the String class, and Wrapper classes.
Some Important Rules for Switch Statements

1. There can be any number of cases just imposing condition check but remember duplicate case/s
values are not allowed.
2. The value for a case must be of the same data type as the variable in the switch.
3. The value for a case must be constant or literal. Variables are not allowed.
4. The break statement is used inside the switch to terminate a statement sequence.
5. The break statement is optional. If omitted, execution will continue on into the next case.
6. The default statement is optional and can appear anywhere inside the switch block. In case, if it
is not at the end, then a break statement must be kept after the default statement to omit the
execution of the next case statement.

Flow Diagram of Switch-Case Statement


Syntax: Switch-case
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional

case value2 :
// Statements
break; // break is optional

// We can have any number of case statements


// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}

Note: Java switch statement is a fall through statement that means it executes all statements
if break keyword is not used, so it is highly essential to use break keyword inside each case.
Example: Consider the following java program, it declares an int named day whose value represents a
day(1-7). The code displays the name of the day, based on the value of the day, using the switch
statement.

Java
// Java program to Demonstrate Switch Case
// with Primitive(int) Data Type

// Class
public class GFG {

// Main driver method


public static void main(String[] args)
{
int day = 5;
String dayString;

// Switch statement with int data type


switch (day) {
// Case
case 1:
dayString = "Monday";
break;

// Case
case 2:
dayString = "Tuesday";
break;

// Case
case 3:
dayString = "Wednesday";
break;

// Case
case 4:
dayString = "Thursday";
break;

// Case
case 5:
dayString = "Friday";
break;

// Case
case 6:
dayString = "Saturday";
break;

// Case
case 7:
dayString = "Sunday";
break;

// Default case
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}
Output
Friday

Omitting the break Statement

A break statement is optional. If we omit the break, execution will continue on into the next case. It is
sometimes desirable to have multiple cases without break statements between them. For instance, let
us consider the updated version of the above program, it also displays whether a day is a weekday or a
weekend day.

Example:

Java
// Java Program to Demonstrate Switch Case
// with Multiple Cases Without Break Statements

// Class
public class GFG {

// main driver method


public static void main(String[] args)
{
int day = 2;
String dayType;
String dayString;

// Switch case
switch (day) {

// Case
case 1:
dayString = "Monday";
break;

// Case
case 2:
dayString = "Tuesday";
break;

// Case
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
}

switch (day) {
// Multiple cases without break statements

case 1:
case 2:
case 3:
case 4:
case 5:
dayType = "Weekday";
break;
case 6:
case 7:
dayType = "Weekend";
break;

default:
dayType = "Invalid daytype";
}

System.out.println(dayString + " is a " + dayType);


}
}

Output
Tuesday is a Weekday
Nested Switch Case statements

We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch.
Since a switch statement defines its own block, no conflicts arise between the case constants in the inner
switch and those in the outer switch.

Example:

Java
// Java Program to Demonstrate
// Nested Switch Case Statement

// Class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Custom input string
String Branch = "CSE";
int year = 2;

// Switch case
switch (year) {

// Case
case 1:
System.out.println(
"elective courses : Advance english, Algebra");

// Break statement to hault execution here


// itself if case is matched
break;

// Case
case 2:

// Switch inside a switch


// Nested Switch
switch (Branch) {

// Nested case
case "CSE":
case "CCE":
System.out.println(
"elective courses : Machine Learning, Big Data");
break;

// Case
case "ECE":
System.out.println(
"elective courses : Antenna Engineering");
break;

// default case
// It will execute if above cases does not
// execute
default:

// Print statement
System.out.println(
"Elective courses : Optimization");
}
}
}
}

Output
elective courses : Machine Learning, Big Data

Example:

Java
// Java Program to Illustrate Use of Enum
// in Switch Statement

// Class
public class GFG {

// Enum
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }

// Main driver method


public static void main(String args[])
{
// Enum
Day[] DayNow = Day.values();

// Iterating using for each loop


for (Day Now : DayNow) {

// Switch case
switch (Now) {

// Case 1
case Sun:
System.out.println("Sunday");

// break statement that hault further


// execution once case is satisfied
break;

// Case 2
case Mon:
System.out.println("Monday");
break;

// Case 3
case Tue:
System.out.println("Tuesday");
break;

// Case 4
case Wed:
System.out.println("Wednesday");
break;

// Case 5
case Thu:
System.out.println("Thursday");
break;

// Case 6
case Fri:
System.out.println("Friday");
break;
// Case 7
case Sat:
System.out.println("Saturday");
break;
}
}
}
}

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

String in Switch Case in Java

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression. Basically, the expression can be a byte,
short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types
( Enums in java), the String class, and Wrapper classes.

Hence the concept of string in switch statement arises into play in JDK 7 as we can use a string literal or
constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an
improvement over using the equivalent sequence of if/else statements. We now declare a string as a
String class object only as depicted below:

Illustration:

String geeks = "GeeksforGeeks" ; // Valid from JDK7 and onwards


Object geeks = "GeeksforGeeks" ; // Invalid from JDK7 and onwards

There are certain key points that are needed to be remembered while using switch statement as it does
provide convenience but at the same time acts as a double sword, hence we better go through traits as
listed:

1. Expensive operation: Switching on strings can be more expensive in terms of execution than
switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the
controlling data is already in string form.

2. String should not be NULL: Ensure that the expression in any switch statement is not null while
working with strings to prevent a NullPointerException from being thrown at run-time.
3. Case Sensitive Comparison: The switch statement compares the String object in its expression with
the expressions associated with each case label as if it were using the equals() method of String class
consequently, the comparison of String objects in switch statements is case sensitive.

4. Better than if-else: The Java compiler generates generally more efficient bytecode from switch
statements that use String objects than from chained if-then-else statements.

Example 1:

Java
// Java Program to Demonstrate use of String to
// Control a Switch Statement

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Custom input string


String str = "two";

// Switch statement over above string


switch (str) {

// Case 1
case "one":

// Print statement corresponding case


System.out.println("one");

// break keyword terminates the


// code execution here itself
break;

// Case 2
case "two":

// Print statement corresponding case


System.out.println("two");
break;
// Case 3
case "three":

// Print statement corresponding case


System.out.println("three");
break;

// Case 4
// Default case
default:

// Print statement corresponding case


System.out.println("no match");
}
}
}

Output
two

Example 2:

Java
// Java Program to Demonstrate use of String to
// Control a Switch Statement

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Custom input string


// Null string is passed
String str = "";

// Switch statement over above string


switch (str) {

// Case 1
case "one":
// Print statement corresponding case
System.out.println("one");

// break keyword terminates the


// code execution here itself
break;

// Case 2
case "two":

// Print statement corresponding case


System.out.println("two");
break;

// Case 3
case "three":

// Print statement corresponding case


System.out.println("three");
break;

// Case 4
// Default case
default:

// Print statement corresponding case


System.out.println("no match");
}
}
}

Output
no match

Do we need forward declarations in Java?

Predict output of the following Java program.

Java
// filename: Test2.java

// main() function of this class uses Test1 which is declared later in


// this file
class Test2 {
public static void main(String[] args) {
Test1 t1 = new Test1();
t1.fun(5);
}
}
class Test1 {
void fun(int x) {
System.out.println("fun() called: x = " + x);
}
}
Output:
fun() called: x = 5

Type conversion in Java with Examples

Java provides various data types just likely any other dynamic languages such as boolean, char, int,
unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype acquires
different space while storing in memory. When you assign a value of one data type to another, the two
types might not be compatible with each other. If the data types are compatible, then Java will perform
the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast
or converted explicitly. For example, assigning an int value to a long variable.

Datatype Bits Acquired In Memory

boolean 1

byte 8 (1 byte)

char 16 (2 bytes)
Datatype Bits Acquired In Memory

short 16(2 bytes)

int 32 (4 bytes)

long 64 (8 bytes)

float 32 (4 bytes)

double 64 (8 bytes)

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This happens
when:

 The two data types are compatible.


 When we assign a value of a smaller data type to a bigger data type.

For Example, in java, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Example:

Java
// Java Program to Illustrate Automatic Type Conversion

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
int i = 100;

// Automatic type conversion


// Integer to long type
long l = i;

// Automatic type conversion


// long to float type
float f = l;

// Print and display commands


System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}

Output
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit Conversion


If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting
or narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, the target type specifies the desired type to convert the specified value to.

char and number are not compatible with each other. Let's see when we try to convert one into another.

Java
// Java program to illustrate Incompatible data Type
// for Explicit Type Conversion

// Main class
public class GFG {
// Main driver method
public static void main(String[] argv)
{

// Declaring character variable


char ch = 'c';
// Declaringinteger variable
int num = 88;
// Trying to insert integer to character
ch = num;
}
}

Output: An error will be generated

This error is generated as an integer variable takes 4 bytes while character datatype requires 2 bytes.
We are trying to plot data from 4 bytes into 2 bytes which is not possible.

How to do Explicit Conversion?

Java
// Java program to Illustrate Explicit Type Conversion

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;

// Explicit type casting


int i = (int)l;

// Print statements
System.out.println("Double value " + d);

// While printing we will see that


// fractional part lost
System.out.println("Long value " + l);

// While printing we will see that


// fractional part lost
System.out.println("Int value " + i);
}
}

Output
Double value 100.04
Long value 100
Int value 100

Note: While assigning value to byte type the fractional part is lost and is reduced to modulo
256(range of byte).
Example:

Java
// Java Program to Illustrate Conversion of
// Integer and Double to Byte

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring byte variable
byte b;
// Declaring and initializing integer and double
int i = 257;
double d = 323.142;

// Display message
System.out.println("Conversion of int to byte.");

// i % 256
b = (byte)i;

// Print commands
System.out.println("i = " + i + " b = " + b);
System.out.println(
"\nConversion of double to byte.");

// d % 256
b = (byte)d;

// Print commands
System.out.println("d = " + d + " b= " + b);
}
}

Output
Conversion of int to byte.
i = 257 b = 1

Conversion of double to byte.


d = 323.142 b= 67

Type Promotion in Expressions


While evaluating expressions, the intermediate value may exceed the range of operands and hence the
expression value will be promoted. Some conditions for type promotion are:

1. Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
2. If one operand is long, float or double the whole expression is promoted to long, float, or double
respectively.

Example:

Java
// Java program to Illustrate Type promotion in Expressions

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initializing primitive types


byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);

// Printing the result obtained after


// all the promotions are done
System.out.println("result = " + result);
}
}

Output
result = 626.7784146484375

Explicit Type Casting in Expressions


While evaluating expressions, the result is automatically updated to a larger data type of the operand.
But if we store that result in any smaller data type it generates a compile-time error, due to which we
need to typecast the result.

Example:

Java
// Java program to Illustrate Type Casting
// in Integer to Byte

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring byte array
byte b = 50;

// Type casting int to byte


b = (byte)(b * 2);

// Display value in byte


System.out.println(b);
}
}

Output
100

Note: In case of single operands the result gets converted to int and then it is typecast
accordingly, as in the above example.

Widening Primitive Conversion in Java

Whenever we do use double quotes around a letter or string as we all know it is treated as a string but
when we do use a single quote round letter alongside performing some computations then they are
treated as integers values while printing for which we must have knowledge of ASCII table concept as
in computer for every character being case sensitive there is a specific integer value assigned to it at the
backend which pops out widening of primitive datatype conversion. Refer to this ASCII table and just
peek out as you no longer need to remember the value corresponding to each just remember popular
values as it is sequentially defined over some intervals such as "a", "A" and so on.

Illustration:

Widening primitive conversion is applied to convert either or both operands as specified by the
following rules. The result of adding Java chars, shorts, or bytes is an int datatype under the following
conditions as listed:
 If either operand is of type double, the other is converted to double.
 Otherwise, if either operand is of type float, the other is converted to float.
 Otherwise, if either operand is of type long, the other is converted to long.
 Otherwise, both operands are converted to type int

Example 1:

Java
// Java Program to Illustrate
// Widening Datatype Conversion
// No Computations

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Printing values on console
System.out.print("Y"
+ "O");
System.out.print('L');
System.out.print('O');
}
}

Output
YOLO

Output explanation:

This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion
happens only when an operator like '+' is present which expects at least an integer on both sides. Now
let us adhere forward proposing another case as follows:

Example 2:
Java
// Java Program to Illustrate
// Widening Datatype Conversion
// Computations is Carried Out

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Printing values on console
System.out.print("Y"
+ "O");

// here computations is carried between letter


// literal
System.out.print('L' + 'O');
}
}

Output
YO155

Output explanation:

When we use double quotes, the text is treated as a string and “YO” is printed, but when we use single
quotes, the characters ‘L’ and ‘O’ are converted to int. This is called widening primitive conversion. After
conversion to integer, the numbers are added ( ‘L’ is 76 and ‘O’ is 79) and 155 is printed.

Comments in Java

In a program, comments are like indents one makes, they are used so that it is easier for someone who
isn't familiar with the language to be able to understand the code. It will also make the job easier for
you, as a coder, to find errors in the code since you will be easily able to find the location of the bug.
Comments are ignored by the compiler while compiling a code, which makes the job more complex in
the long run when they have to go through so much code to find one line.

In Java there are three types of comments:

1. Single-line comments.
2. Multi-line comments.
3. Documentation comments.
A. Single-line comments

A beginner-level programmer uses mostly single-line comments for describing the code functionality.
It's the easiest typed comments.

Syntax:

//Comments here( Text in this line only is considered as comment )

Illustration:

Examples in an actual code


Example:

Java
// Java program to show single line comments

class Scomment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}

B. Multi-line Comments:

To describe a full method in a code or a complex snippet single line comments can be tedious to write
since we have to give '//' at every line. So to overcome this multi-line comments can be used.

Syntax:

/*Comment starts
continues
continues
.
.
.
Comment ends*/

Example:

Java

//Java program to show multi line comments


class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}

We can also accomplish single line comments by using the above syntax as shown below:

/*Comment line 1*/

C. Documentation Comments:

This type of comment is used generally when writing code for a project/software package, since it helps
to generate a documentation page for reference, which can be used for getting information about
methods present, its parameters, etc. For
example, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto-generated
documentation page that is generated by using documentation comments and a javadoc tool for
processing the comments.

Syntax:

/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/

Available tags to use:


Tag Description Syntax

@author Adds the author of a class. @author name-text

Displays text in code font without interpreting the


{@code} {@code text}
text as HTML markup or nested javadoc tags.

Represents the relative path to the generated


{@docRoot} document's root directory from any generated {@docRoot}
page.

Adds a comment indicating that this API should no


@deprecated @deprecated deprecatedtext
longer be used.

Adds a Throws subheading to the generated


@exception class-name
@exception documentation, with the classname and description
description
text.

Inherits a comment from the nearest inheritable Inherits a comment from the
{@inheritDoc}
class or implementable interface. immediate surperclass.

Inserts an in-line link with the visible text label


{@link
that points to the documentation for the specified
{@link} package.class#member
package, class, or member name of a referenced
label}
class.

{@linkplain
Identical to {@link}, except the link's label is
{@linkplain} package.class#member
displayed in plain text than code font.
label}
Tag Description Syntax

Adds a parameter with the specified parameter-


@param parameter-name
@param name followed by the specified description to the
description
"Parameters" section.

@return Adds a "Returns" section with the description text. @return description

Adds a "See Also" heading with a link or text entry


@see @see reference
that points to reference.

Used in the doc comment for a default serializable @serial field-description |


@serial
field. include | exclude

Documents the data written by the writeObject( )


@serialData @serialData data-description
or writeExternal( ) methods.

@serialField field-name
@serialField Documents an ObjectStreamField component.
field-type field-description

Adds a "Since" heading with the specified since-


@since @since release
text to the generated documentation.

@throws class-name
@throws The @throws and @exception tags are synonyms.
description

When {@value} is used in the doc comment of a {@value


{@value}
static field, it displays the value of that constant. package.class#field}
Tag Description Syntax

Adds a "Version" subheading with the specified


@version version-text to the generated docs when the - @version version-text
version option is used.

Implementation:

Java
// Java program to illustrate frequently used
// Comment tags

/**
* <h1>Find average of three numbers!</h1>
* The FindAvg program implements an application that
* simply calculates average of three integers and Prints
* the output on the screen.
*
* @author Pratik Agarwal
* @version 1.0
* @since 2017-02-18
*/
public class FindAvg
{
/**
* This method is used to find average of three integers.
* @param numA This is the first parameter to findAvg method
* @param numB This is the second parameter to findAvg method
* @param numC This is the second parameter to findAvg method
* @return int This returns average of numA, numB and numC.
*/
public int findAvg(int numA, int numB, int numC)
{
return (numA + numB + numC)/3;
}

/**
* This is the main method which makes use of findAvg method.
* @param args Unused.
* @return Nothing.
*/
public static void main(String args[])
{
FindAvg obj = new FindAvg();
int avg = obj.findAvg(10, 20, 30);

System.out.println("Average of 10, 20 and 30 is :" + avg);


}
}

Output:
Average of 10, 20 and 30 is :20

For the above code documentation can be generated by using the tool 'javadoc':

Javadoc can be used by running the following command in the terminal.


javadoc FindAvg.java

Important Keywords in Java

Keywords refer to the reserved set of words of a language. These are used for some predefined actions.

1. abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve
abstraction. For more, refer to abstract keyword in java
2. enum: It is used to define enum in Java
3. instanceof: It is used to know whether the object is an instance of the specified type (class or
subclass or interface).
4. private: It is an access modifier. Anything declared private cannot be seen outside of its class.
5. protected: If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
6. public: Anything declared public can be accessed from anywhere. For more on Access Modifiers,
refer to Access Modifiers in Java
7. static: It is used to create a member(block, method, variable, nested classes) that can be used by
itself, without reference to a specific instance. For more, refer static keyword in java
8. strictfp: It is used for restricting floating-point calculations and ensuring the same result on
every platform while performing operations in the floating-point variable. For more
refer strictfp keyword in Java
9. synchronized: Applicable for blocks methods. It is used to get synchronization in java. For more,
refer to Synchronized in Java
10. transient: transient is a variables modifier used in serialization. At the time of serialization, if
we don’t want to save the value of a particular variable in a file, then we use the transient
keyword. For more refer transient keyword in Java
11. volatile: The volatile modifier tells the compiler that the variable modified by volatile can be
changed unexpectedly by other parts of your program. For more, refer to volatile keyword in
java
Articles (12)

Introduction to Arrays

Arrays in Java

Jagged Array in Java

Multidimensional Arrays in Java

Program for Fibonacci numbers

Find the element that appears once in an array where every other element appears twice

Count set bits in an integer

Subset array sum by generating all the subsets

Count total set bits in all numbers from 1 to n

Swap bits in a given number

String class in Java | Set 1

Methods in Java

Introduction to Arrays

What is an Array?

An array is a collection of items of same data type stored at contiguous memory locations.

This makes it easier to calculate the position of each element by simply adding an offset to a
base value, i.e., the memory location of the first element of the array (generally denoted by the
name of the array). The base value is index 0 and the difference between the two indexes is
the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let's say
one of your friends). Here, you can identify the location of any of your friends by simply knowing the
count of the step they are on.
Remember: "Location of next index depends on the data type we use".
Is the array always of fixed size?

In C language, the array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you
can’t shrink it nor can you expand it. The reason was that for expanding if we change the size we can’t
be sure ( it’s not possible every time) that we get the next memory location to us for free. The shrinking
will not work because the array, when declared, gets memory statically allocated, and thus compiler is
the only one that can destroy it.

Types of indexing in an array:

 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.


 1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
 n (N-based indexing): The base index of an array can be freely chosen. Usually, programming
languages allowing n-based indexing also allow negative index values, and other scalar data
types like enumerations, or characters may be used as an array index.
How an Array is initialized?

By default the array is uninitialized, and no elements of the array are set to any value. However, for the
proper working of the array, array initialization becomes important. Array initialization can be done by
the following methods:

1. Passing no value within the initializer: One can initialize the array by defining the size of the array
and passing no values within the initializer.

Syntax:

int arr[ 5 ] = { };
2. By passing specific values within the initializer: One can initialize the array by defining the size
of the array and passing specific values within the initializer.

Syntax:

int arr[ 5 ] = { 1 , 2 , 3 , 4 , 5 };
Note: The count of elements within the "{ }", must be less than the size of the array
If the count of elements within the "{ }" is less than the size of the array, the remaining positions are
considered to be '0'.

Syntax:

int arr[ 5 ] = { 1 , 2 , 3 } ;
3. By passing specific values within the initializer but not declaring the size: One can initialize the
array by passing specific values within the initializer and not particularly mentioning the size, the size
is interpreted by the compiler.

Syntax:
int arr[ ] = { 1 , 2 , 3 , 4 , 5 };
4. Universal Initialization: After the adoption of universal initialization in C++, one can avoid using
the equals sign between the declaration and the initializer.

Syntax:

int arr[ ] { 1 , 2 , 3 , 4 , 5 };
To know more about array initialization, click here.

What are the different operations on the array?

Arrays allow random access to elements. This makes accessing elements by position faster. Hence
operation like searching, insertion, and access becomes really efficient. Array elements can be accessed
using the loops.

1. Insertion in Array:

We try to insert a value to a particular array index position, as the array provides random access it can
be done easily using the assignment operator.

Pseudo Code:

// to insert a value= 10 at index position 2;

arr[ 2 ] = 10;
Time Complexity:

 O(1) to insert a single element


 O(N) to insert all the array elements [where N is the size of the array]

2. Access elements in Array:

Accessing array elements become extremely important, in order to perform operations on arrays.

Pseudo Code:

// to access array element at index position 2, we simply can write

return arr[ 2 ] ;
Time Complexity: O(1)

3. Searching in Array:

We try to find a particular value in the array, in order to do that we need to access all the array elements
and look for the particular value.

Pseudo Code:
// searching for value 2 in the array;

Loop from i = 0 to 5:
check if arr[i] = 2:
return true;
Time Complexity: O(N), where N is the size of the array.

Here is the code for working with an array:

C++CJava
#include <iostream>
using namespace std;

int main()
{
// Creating an integer array
// named arr of size 10.
int arr[10];
// accessing element at 0 index
// and setting its value to 5.
arr[0] = 5;
// access and print value at 0
// index we get the output as 5.
cout << arr[0];
return 0;
}

Output
5

Here the value 5 is printed because the first element has index zero and at the zeroth index, we already
assigned the value 5.

Types of arrays :

1. One dimensional array (1-D arrays)


2. Multidimensional array

To learn about the differences between One-dimensional and Multidimensional arrays, click here.

Advantages of using arrays:

 Arrays allow random access to elements. This makes accessing elements by position faster.
 Arrays have better cache locality which makes a pretty big difference in performance.
 Arrays represent multiple data items of the same type using a single name.

Disadvantages of using arrays:


You can’t change the size i.e. once you have declared the array you can’t change its size because of static
memory allocation. Here Insertion(s) and deletion(s) are difficult as the elements are stored in
consecutive memory locations and the shifting operation is costly too.

Now if take an example of the implementation of data structure Stack using array there are some
obvious flaws.
Let’s take the POP operation of the stack. The algorithm would go something like this.

1. Check for the stack underflow


2. Decrement the top by 1

What we are doing here is, that the pointer to the topmost element is decremented, which means we
are just bounding our view, and actually that element stays there taking up the memory space. If you
have an array (as a Stack) of any primitive data type then it might be ok. But in the case of an array of
Objects, it would take a lot of memory.

Examples -

// A character array in C/C++/Java


char arr1[] = {'g', 'e', 'e', 'k', 's'};

// An Integer array in C/C++/Java


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

// Item at i'th index in array is typically accessed as "arr[i]".


For example:
arr1[0] gives us 'g'
arr2[3] gives us 40
Usually, an array of characters is called a 'string', whereas an array of ints or floats is simply called an
array.

Applications on Array

 Array stores data elements of the same data type.


 Arrays are used when the size of the data set is known.
 Used in solving matrix problems.
 Applied as a lookup table in computer.
 Databases records are also implemented by the array.
 Helps in implementing sorting algorithm.
 The different variables of the same type can be saved under one name.
 Arrays can be used for CPU scheduling.
 Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.

To learn more about the advantage, disadvantages, and applications of arrays, click here.

Frequently asked questions (FAQs) about Array Data Structures

1. What is an array in data structure with example?


An array is a collection of items of the same data type stored at contiguous memory locations. Ex. int
arr[5] = {1,2,3,4,5};

2. What are the 3 types of arrays?

 Indexed arrays
 Multidimensional arrays
 Associative arrays

3. What data structure is an array?

An array is a linear data structure.

4. Difference between array and structure?

The structure can contain variables of different types but an array only contain variables of the same
type.

Arrays in Java

Unlike C++, arrays are first class objects in Java. For example, in the following program, size of array is
accessed using length which is a member of arr[] object.

Java

// file name: Main.java


public class Main {
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
for(int i=0; i < arr.length; i++)
{
System.out.print(" " + arr[i]);
}
}
}
Output:
10 20 30 40 50

Jagged Array in Java

Prerequisite: Arrays in Java

A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create
a 2-D array but with a variable number of columns in each row. These types of arrays are also known
as Jagged arrays.
Pictorial representation of Jagged array in Memory:

Jagged_array

Declaration and Initialization of Jagged array :

Syntax: data_type array_name[][] = new data_type[n][]; //n: no. of rows


array_name[] = new data_type[n1] //n1= no. of columns in row-1
array_name[] = new data_type[n2] //n2= no. of columns in row-2
array_name[] = new data_type[n3] //n3= no. of columns in row-3
.
.
.
array_name[] = new data_type[nk] //nk=no. of columns in row-n

Alternative, ways to Initialize a Jagged array :

int arr_name[][] = new int[][] {


new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
{10, 20, 30 ,40},
{50, 60, 70, 80, 90, 100},
{110, 120}
};

Following are Java programs to demonstrate the above concept.

Java
// Program to demonstrate 2-D jagged array in Java
class Main {
public static void main(String[] args)
{
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];

// Making the above array Jagged

// First row has 3 columns


arr[0] = new int[3];

// Second row has 2 columns


arr[1] = new int[2];

// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;

// Displaying the values of 2D Jagged array


System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Output
Contents of 2D Jagged Array
0 1 2
3 4

Following is another example where i'th row has i columns, i.e., the first row has 1 element, the second
row has two elements and so on.

Java
// Another Java program to demonstrate 2-D jagged
// array such that first row has 1 element, second
// row has two elements and so on.
class Main {
public static void main(String[] args)
{
int r = 5;

// Declaring 2-D array with 5 rows


int arr[][] = new int[r][];

// Creating a 2D array such that first row


// has 1 element, second row has two
// elements and so on.
for (int i = 0; i < arr.length; i++)
arr[i] = new int[i + 1];

// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;

// Displaying the values of 2D Jagged array


System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Output
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14

Multidimensional Arrays in Java

Array-Basics in Java
Multidimensional Arrays can be defined in simple words as array of arrays. Data in multidimensional
arrays are stored in tabular form (in row major order).

Syntax:

data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new


data_type[size1][size2]....[sizeN];

where:

 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created. For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, ..., sizeN: Sizes of the dimensions respectively.

Examples:

Two dimensional array:


int[][] twoD_arr = new int[10][20];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];

Size of multidimensional arrays: The total number of elements that can be stored in a
multidimensional array can be calculated by multiplying the size of all the dimensions.

For example:
The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.

Two - dimensional Array (2D-Array)

Two - dimensional array is the simplest form of a multidimensional array. A two - dimensional array
can be seen as an array of one - dimensional array for easier understanding.

Indirect Method of Declaration:

 Declaration - Syntax:

data_type[][] array_name = new data_type[x][y];


For example: int[][] arr = new int[10][20];

 Initialization - Syntax:

array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;

Example:

Java

class GFG {
public static void main(String[] args)
{

int[][] arr = new int[10][20];


arr[0][0] = 1;

System.out.println("arr[0][0] = " + arr[0][0]);


}
}
Output:
arr[0][0] = 1

Direct Method of Declaration: Syntax:

data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};

For example: int[][] arr = {{1, 2}, {3, 4}};

Example:

Java

class GFG {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "
+ arr[i][j]);
}
}
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4

Accessing Elements of Two-Dimensional Arrays

Elements in two-dimensional arrays are commonly referred by x[i][j] where 'i' is the row number and
'j' is the column number. Syntax:

x[row_index][column_index]

For example:
int[][] arr = new int[10][20];
arr[0][0] = 1;

The above example represents the element present in first row and first column. Note: In arrays if size
of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 =
3. Example:

Java

class GFG {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

System.out.println("arr[0][0] = " + arr[0][0]);


}
}
Output:
arr[0][0] = 1

Representation of 2D array in Tabular Format: A two - dimensional array can be seen as a table with
'x' rows and 'y' columns where the row number ranges from 0 to (x-1) and column number ranges from
0 to (y-1). A two - dimensional array 'x' with 3 rows and 3 columns is shown below:

Print 2D array in tabular format: To output all the elements of a Two-Dimensional array, use nested
for loops. For this two for loops are required, One to traverse the rows and another to traverse columns.
Example:

Java

class GFG {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}

System.out.println();
}
}
}
Output:
1 2
3 4

Three - dimensional Array (3D-Array)


Three - dimensional array is a complex form of a multidimensional array. A three - dimensional array
can be seen as an array of two - dimensional array for easier understanding. Indirect Method of
Declaration:

 Declaration - Syntax:

data_type[][][] array_name = new data_type[x][y][z];


For example: int[][][] arr = new int[10][20][30];

 Initialization - Syntax:
array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;

Example:

Java

class GFG {
public static void main(String[] args)
{

int[][][] arr = new int[10][20][30];


arr[0][0][0] = 1;

System.out.println("arr[0][0][0] = " + arr[0][0][0]);


}
}
Output:
arr[0][0][0] = 1

Direct Method of Declaration: Syntax:

data_type[][][] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};

For example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };

Example:

Java

class GFG {
public static void main(String[] args)
{

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
for (int z = 0; z < 2; z++)
System.out.println("arr[" + i
+ "]["
+ j + "]["
+ z + "] = "
+ arr[i][j][z]);
}
}
Output:
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

Accessing Elements of Three-Dimensional Arrays

Elements in three-dimensional arrays are commonly referred by x[i][j][k] where 'i' is the array
number, 'j' is the row number and 'k' is the column number. Syntax:

x[array_index][row_index][column_index]

For example:

int[][][] arr = new int[10][20][30];


arr[0][0][0] = 1;

The above example represents the element present in the first row and first column of the first array in
the declared 3D array. Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for
row_index 2, actual row number is 2+1 = 3. Example:

Java

class GFG {
public static void main(String[] args)
{

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

System.out.println("arr[0][0][0] = " + arr[0][0][0]);


}
}
Output:
arr[0][0][0] = 1

Representation of 3D array in Tabular Format: A three - dimensional array can be seen as a tables
of arrays with 'x' rows and 'y' columns where the row number ranges from 0 to (x-1) and column
number ranges from 0 to (y-1). A three - dimensional array with 3 array containing 3 rows and 3
columns is shown below:

Print 3D array in tabular format: To output all the elements of a Three-Dimensional array, use nested
for loops. For this three for loops are required, One to traverse the arrays, second to traverse the rows
and another to traverse columns. Example:

Java

class GFG {
public static void main(String[] args)
{

int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

System.out.print(arr[i][j][k] + " ");


}

System.out.println();
}
System.out.println();
}
}
}
Output:
1 2
3 4

5 6
7 8

Inserting a Multi-dimensional Array during Runtime: This topic is forced n taking user-defined
input into a multidimensional array during runtime. It is focused on the user first giving all the input to
the program during runtime and after all entered input, the program will give output with respect to
each input accordingly. It is useful when the user wishes to make input for multiple Test-Cases with
multiple different values first and after all those things done, program will start providing output. As an
example, let's find the total number of even and odd numbers in an input array. Here, we will use the
concept of a 2-dimensional array. Here are a few points that explain the use of the various elements in
the upcoming code:

 Row integer number is considered as the number of Test-Cases and Column values are considered as
values in each Test-Case.
 One for() loop is used for updating Test-Case number and another for() loop is used for taking respective
array values.
 As all input entry is done, again two for() loops are used in the same manner to execute the program
according to the condition specified.
 The first line of input is the total number of TestCases.
 The second line shows the total number of first array values.
 The third line gives array values and so on.

Implementation:

Java

import java.util.Scanner;
public class GFGTestCase {
public static void main(
String[] args)
{
// Scanner class to take
// values from console
Scanner scanner = new Scanner(System.in);

// totalTestCases = total
// number of TestCases
// eachTestCaseValues =
// values in each TestCase as
// an Array values
int totalTestCases, eachTestCaseValues;

// takes total number of


// TestCases as integer number
totalTestCases = scanner.nextInt();

// An array is formed as row


// values for total testCases
int[][] arrayMain = new int[totalTestCases][];

// for loop to take input of


// values in each TestCase
for (int i = 0; i < arrayMain.length; i++) {
eachTestCaseValues = scanner.nextInt();
arrayMain[i] = new int[eachTestCaseValues];
for (int j = 0; j < arrayMain[i].length; j++) {
arrayMain[i][j] = scanner.nextInt();
}
} // All input entry is done.

// Start executing output


// according to condition provided
for (int i = 0; i < arrayMain.length; i++) {

// Initialize total number of


// even & odd numbers to zero
int nEvenNumbers = 0, nOddNumbers = 0;

// prints TestCase number with


// total number of its arguments
System.out.println(
"TestCase " + i + " with "
+ arrayMain[i].length + " values:");
for (int j = 0; j < arrayMain[i].length; j++) {
System.out.print(arrayMain[i][j] + " ");

// even & odd counter updated as


// eligible number is found
if (arrayMain[i][j] % 2 == 0) {
nEvenNumbers++;
}
else {
nOddNumbers++;
}
}
System.out.println();

// Prints total numbers of


// even & odd
System.out.println(
"Total Even numbers: " + nEvenNumbers
+ ", Total Odd numbers: " + nOddNumbers);
}
}
}
// This code is contributed by Udayan Kamble.
Input:
2
2
1 2
3
1 2 3

Output:
TestCase 0 with 2 values:
1 2
Total Even numbers: 1, Total Odd numbers: 1
TestCase 1 with 3 values:
1 2 3
Total Even numbers: 1, Total Odd numbers: 2
Input:
3
8
1 2 3 4 5 11 55 66
5
100 101 55 35 108
6
3 80 11 2 1 5

Output:
TestCase 0 with 8 values:
1 2 3 4 5 11 55 66
Total Even numbers: 3, Total Odd numbers: 5
TestCase 1 with 5 values:
100 101 55 35 108
Total Even numbers: 2, Total Odd numbers: 3
TestCase 2 with 6 values:
3 80 11 2 1 5
Total Even numbers: 2, Total Odd numbers: 4

Subset array sum by generating all the subsets

Given an array of size N and a sum, the task is to check whether some array elements can be added to
sum to N .
Note: At least one element should be included to form the sum.(i.e. sum cant be zero)
Examples:

Input: array = -1, 2, 4, 121, N = 5


Output: YES
The array elements 2, 4, -1 can be added to sum to N

Input: array = 1, 3, 7, 121, N = 5


Output:NO

Approach: The idea is to generate all subsets using Generate all subsequences of array and
correspondingly check if any subsequence has the sum equal to the given sum.
Below is the implementation of the above approach:

CPPJavaPython3C#PHPJavascript

// Java implementation of the above approach


class GFG
{

// Find way to sum to N using array elements atmost once


static void find(int [] arr, int length, int s)
{
// loop for all 2^n combinations
for (int i = 1; i <= (Math.pow(2, length)); i++) {

// sum of a combination
int sum = 0;

for (int j = 0; j < length; j++)

// if the bit is 1 then add the element


if (((i >> j) & 1) % 2 == 1)
sum += arr[j];

// if the sum is equal to given sum print yes


if (sum == s) {
System.out.println("YES");
return;
}
}

// else print no
System.out.println("NO");
}

// driver code
public static void main(String[] args)
{
int sum = 5;
int []array = { -1, 2, 4, 121 };
int length = array.length;
// find whether it is possible to sum to n
find(array, length, sum);

// This code is contributed by ihritik

Output:

YES

Note: This program would not run for the large size of the array.

Program for Fibonacci numbers

The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

Fn = Fn-1 + Fn-2

with seed values

F0 = 0 and F1 = 1.
Given a number n, print n-th Fibonacci Number.

Examples:

Input : n = 2
Output : 1

Input : n = 9
Output : 34

Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1,
then it should return 1. For n > 1, it should return Fn-1 + Fn-2

For n = 9
Output:34

Following are different methods to get the nth Fibonacci number.

Method 1 (Use recursion)


A simple method that is a direct recursive implementation mathematical recurrence relation is given
above.

C++CJavaPython3C#PHPJavascript

//Fibonacci Series using Recursion


#include<bits/stdc++.h>
using namespace std;

int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}

int main ()
{
int n = 9;
cout << fib(n);
getchar();
return 0;
}
// This code is contributed
// by Akanksha Rai

Output
34

Time Complexity: Exponential, as every function calls two other functions.

If the original recursion tree were to be implemented then this would have been the tree but now for n
times the recursion function is called

Original tree for recursion

fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)

Optimized tree for recursion for code above

fib(5)

fib(4)

fib(3)

fib(2)

fib(1)

Extra Space: O(n) if we consider the function call stack size, otherwise O(1).

Method 2 (Use Dynamic Programming)


We can avoid the repeated work done in method 1 by storing the Fibonacci numbers calculated so far.

C++CJavaPython3C#PHPJavascript

// Fibonacci Series using Dynamic Programming


class fibonacci
{
static int fib(int n)
{
/* Declare an array to store Fibonacci numbers. */
int f[] = new int[n+2]; // 1 extra to handle case, n = 0
int i;

/* 0th and 1st number of the series are 0 and 1*/


f[0] = 0;
f[1] = 1;

for (i = 2; i <= n; i++)


{
/* Add the previous 2 numbers in the series
and store it */
f[i] = f[i-1] + f[i-2];
}

return f[n];
}

public static void main (String args[])


{
int n = 9;
System.out.println(fib(n));
}
}
/* This code is contributed by Rajat Mishra */

Output
34

Method 3 (Space Optimized Method 2)


We can optimize the space used in method 2 by storing the previous two numbers only because that is
all we need to get the next Fibonacci number in series.

C++CJavaPython3C#PHPJavascript

// Java program for Fibonacci Series using Space


// Optimized Method
class fibonacci
{
static int fib(int n)
{
int a = 0, b = 1, c;
if (n == 0)
return a;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}

public static void main (String args[])


{
int n = 9;
System.out.println(fib(n));
}
}

// This code is contributed by Mihir Joshi

Output
34

Time Complexity:O(n)
Extra Space: O(1)

Method 4 (Using power of the matrix {{1, 1}, {1, 0}})


This another O(n) which relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself
(in other words calculate power(M, n)), then we get the (n+1)th Fibonacci number as the element at
row and column (0, 0) in the resultant matrix.
The matrix representation gives the following closed expression for the Fibonacci numbers:

[1101]n=[Fn+1FnFnFn+1]

C++CJavaPython3C#PHPJavascript

class fibonacci
{

static int fib(int n)


{
int F[][] = new int[][]{{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);

return F[0][0];
}

/* Helper function that multiplies 2 matrices F and M of size 2*2, and


puts the multiplication result back to F[][] */
static void multiply(int F[][], int M[][])
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];

F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}

/* Helper function that calculates F[][] raise to the power n and puts the
result in F[][]
Note that this function is designed only for fib() and won't work as
general
power function */
static void power(int F[][], int n)
{
int i;
int M[][] = new int[][]{{1,1},{1,0}};

// n - 1 times multiply the matrix to {{1,0},{0,1}}


for (i = 2; i <= n; i++)
multiply(F, M);
}

/* Driver program to test above function */


public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
/* This code is contributed by Rajat Mishra */

Output
34

Time Complexity: O(n)


Extra Space: O(1)

Method 5 (Optimized Method 4)


The method 4 can be optimized to work in O(Logn) time complexity. We can do recursive multiplication
to get power(M, n) in the previous method (Similar to the optimization done in this post)

C++CJavaPython3C#Javascript

//Fibonacci Series using Optimized Method


class fibonacci
{
/* function that returns nth Fibonacci number */
static int fib(int n)
{
int F[][] = new int[][]{{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);

return F[0][0];
}

static void multiply(int F[][], int M[][])


{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];

F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/* Optimized version of power() in method 4 */
static void power(int F[][], int n)
{
if( n == 0 || n == 1)
return;
int M[][] = new int[][]{{1,1},{1,0}};

power(F, n/2);
multiply(F, F);

if (n%2 != 0)
multiply(F, M);
}

/* Driver program to test above function */


public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
/* This code is contributed by Rajat Mishra */

Output
34

Time Complexity: O(Logn)


Extra Space: O(Logn) if we consider the function call stack size, otherwise O(1).

Method 6 (O(Log n) Time)


Below is one more interesting recurrence formula that can be used to find n'th Fibonacci Number in
O(Log n) time.

If n is even then k = n/2:


F(n) = [2*F(k-1) + F(k)]*F(k)

If n is odd then k = (n + 1)/2


F(n) = F(k)*F(k) + F(k-1)*F(k-1)

How does this formula work?


The formula can be derived from above matrix equation.
[1101]n=[Fn+1FnFnFn+1]

Taking determinant on both sides, we get

(-1)n = Fn+1Fn-1 - Fn2

Moreover, since AnAm = An+m for any square matrix A,


the following identities can be derived (they are obtained
from two different coefficients of the matrix product)

FmFn + Fm-1Fn-1 = Fm+n-1 ---------------------------(1)

By putting n = n+1 in equation(1),


FmFn+1 + Fm-1Fn = Fm+n --------------------------(2)

Putting m = n in equation(1).
F2n-1 = Fn2 + Fn-12
Putting m = n in equation(2)

F2n = (Fn-1 + Fn+1)Fn = (2Fn-1 + Fn)Fn (Source: Wiki) --------


( By putting Fn+1 = Fn + Fn-1 )
To get the formula to be proved, we simply need to do the following
If n is even, we can put k = n/2
If n is odd, we can put k = (n+1)/2

Below is the implementation of above idea.

C++JavaPython3C#PHPJavascript

// Java Program to find n'th fibonacci


// Number with O(Log n) arithmetic operations
import java.util.*;

class GFG {

static int MAX = 1000;


static int f[];

// Returns n'th fibonacci number using


// table f[]
public static int fib(int n)
{
// Base cases
if (n == 0)
return 0;

if (n == 1 || n == 2)
return (f[n] = 1);

// If fib(n) is already computed


if (f[n] != 0)
return f[n];

int k = (n & 1) == 1? (n + 1) / 2
: n / 2;

// Applying above formula [Note value


// n&1 is 1 if n is odd, else 0.
f[n] = (n & 1) == 1? (fib(k) * fib(k) +
fib(k - 1) * fib(k - 1))
: (2 * fib(k - 1) + fib(k))
* fib(k);

return f[n];
}

/* Driver program to test above function */


public static void main(String[] args)
{
int n = 9;
f= new int[MAX];
System.out.println(fib(n));
}
}

// This code is contributed by Arnav Kr. Mandal.

Output
34

Time complexity of this solution is O(Log n) as we divide the problem to half in every recursive call.

Method 7
Another approach(Using formula) :
In this method we directly implement the formula for nth term in the fibonacci series.
Fn = {[(√5 + 1)/2] ^ n} / √5

Reference: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html

C++CJavaPython3C#PHPJavascript

// Java Program to find n'th fibonacci Number


import java.util.*;

class GFG {

static int fib(int n) {


double phi = (1 + Math.sqrt(5)) / 2;
return (int) Math.round(Math.pow(phi, n)
/ Math.sqrt(5));
}

// Driver Code
public static void main(String[] args) {
int n = 9;
System.out.println(fib(n));
}
}
// This code is contributed by PrinciRaj1992

Output
34

Time Complexity: O(logn), this is because calculating phi^n takes logn time
Space Complexity: O(1)

Method 8

DP using memoization(Top down approach)

We can avoid the repeated work done in method 1 by storing the Fibonacci numbers calculated so far.
We just need to store all the values in an array.

C++JavaPython3C#Javascript
import java.util.*;

class GFG{
// Initialize array of dp
static int[] dp = new int[10];

static int fib(int n)


{
if (n <= 1)
return n;

// Temporary variables to store


// values of fib(n-1) & fib(n-2)
int first, second;

if (dp[n - 1] != -1)
first = dp[n - 1];
else
first = fib(n - 1);

if (dp[n - 2] != -1)
second = dp[n - 2];
else
second = fib(n - 2);

// Memoization
return dp[n] = first + second;
}

// Driver Code
public static void main(String[] args)
{
int n = 9;

Arrays.fill(dp, -1);

System.out.print(fib(n));
}
}

// This code is contributed by sujitmeshram

Output
34
https://www.youtube.com/watch?v=LwZRsM7qhrI
This method is contributed by Chirag Agarwal.
Method 9 ( Using Binet's Formula for the Nth Fibonacci )
It involves the usage of our golden section number Phi.
Phi = ( sqrt(5) + 1 ) / 2
Using approximation equation is good enough here, since we know N >= 0 && N <= 30, we can safely
use the following rounded function
Fib(N) = round( ( Phi^N ) / sqrt(5) )

Full mathematical explanation of Binet's Formula - https://r-


knott.surrey.ac.uk/Fibonacci/fibFormula.html

C++
// Fibonacci Series using Binet's Nth-term Formula
#include<bits/stdc++.h>
using namespace std;

int fib(int n)
{
double phi = (sqrt(5) + 1) / 2;
return round(pow(phi, n) / sqrt(5));
}

// Driver code
int main()
{
int n = 9;

cout << fib(n);


return 0;
}

// This code is contributed by Sapna Kul

Time Complexity: O(1)


Space Complexity: O(1)

Related Articles:
Large Fibonacci Numbers in Java
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the
same problem.
References:
http://en.wikipedia.org/wiki/Fibonacci_number
http://www.ics.uci.edu/~eppstein/161/960109.html

Find the element that appears once in an array where every other element appears twice

Given an array of integers. All numbers occur twice except one number which occurs once. Find the
number in O(n) time & constant extra space.

Example :

Input: ar[] = {7, 3, 5, 4, 5, 3, 4}


Output: 7

One solution is to check every element if it appears once or not. Once an element with a single
occurrence is found, return it. Time complexity of this solution is O(n2).

A better solution is to use hashing.

1. Traverse all elements and put them in a hash table. Element is used as key and the count of
occurrences is used as the value in the hash table.
2. Traverse the array again and print the element with count 1 in the hash table.

This solution works in O(n) time but requires extra space.

The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence.
The idea is based on the following two facts.

1. XOR of a number with itself is 0.


2. XOR of a number with 0 is number itself.

Let us consider the above example.


Let ^ be xor operator as in C and C++.

res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above


expression can be written as:
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
= 7 ^ 0 ^ 0 ^ 0
= 7 ^ 0
= 7

Below are implementations of above algorithm.

C++CJavaPython3C#PHPJavascript
// Java program to find the array
// element that appears only once
class MaxSum
{
// Return the maximum Sum of difference
// between consecutive elements.
static int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];

return res;
}

// Driver code
public static void main (String[] args)
{
int ar[] = {2, 3, 5, 4, 5, 3, 4};
int n = ar.length;
System.out.println("Element occurring once is " +
findSingle(ar, n) + " ");
}
}
// This code is contributed by Prakriti Gupta

Output
Element occurring once is 2

Time Complexity: O(n)


Auxiliary Space: O(1)

Another approach:
This is not an efficient approach but just another way to get the desired results. If we add each number
once and multiply the sum by 2, we will get twice the sum of each element of the array. Then we will
subtract the sum of the whole array from the twice_sum and get the required number (which appears
once in the array).
Array [] : [a, a, b, b, c, c, d]
Mathematical Equation = 2*(a+b+c+d) - (a + a + b + b + c + c + d)

In more simple words: 2*(sum_of_array_without_duplicates) - (sum_of_array)


let arr[] = {7, 3, 5, 4, 5, 3, 4}
Required no = 2*(sum_of_array_without_duplicates) - (sum_of_array)
= 2*(7 + 3 + 5 + 4) - (7 + 3 + 5 + 4 + 5 + 3 + 4)
= 2* 19 - 31
= 38 - 31
= 7 (required answer)

As we know that set does not contain any duplicate element we will be using the set here.

Below is the implementation of above approach:

C++JavaPython3C#Javascript

// Java program to find


// element that appears once
import java.io.*;
import java.util.*;

class GFG
{

// function which find number


static int singleNumber(int[] nums, int n)
{
HashMap<Integer, Integer> m = new HashMap<>();
long sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++)
{
if (!m.containsKey(nums[i]))
{
sum1 += nums[i];
m.put(nums[i], 1);
}
sum2 += nums[i];
}

// applying the formula.


return (int)(2 * (sum1) - sum2);
}

// Driver code
public static void main(String args[])
{
int[] a = {2, 3, 5, 4, 5, 3, 4};
int n = 7;
System.out.println(singleNumber(a,n));

int[] b = {15, 18, 16, 18, 16, 15, 89};


System.out.println(singleNumber(b,n));
}
}

// This code is contributed by rachana soma

Output
2
89

Time Complexity: O(nlogn)


Auxiliary Space: O(n)

Another approach:

This is an efficient approach for finding the single element in a list of duplicate elements. In this
approach, we are using binary search algorithm to find the single element in the list of duplicates
elements. Before that, we need to make sure if the array is sorted. The first step is to sort the array
because binary search algorithm wont work if the array is not sorted.

Now let us move to the binary search implementation:

There are two halfs that are created by the only single element present in the array which are left half
and right half. Now if there are duplicates present in the left half, then the 1st instance of the duplicate
element in the left half is an even index and the 2nd instance is an odd index. The opposite of the left
half happens in the right half(1st instance is odd index and the second instance is even index). Now
apply binary search algorithm:

1. The solution is to take two indexes of the array(low and high) where low points to array-index
0 and high points to array-index (array size-2). We take out the mid index from the values by
(low+high)/2.
2. Now check if the mid index value falls in the left half or the right half. If it falls in the left half then
we change the low value to mid+1 and if it falls in the right half, then we change the high index
to mid-1. To check it , we used a logic (if(arr[mid]==arr[mid^1]). If mid is an even number then
mid^1 will be the next odd index , and if the condition gets satisfied, then we can say that we are
in the left index, else we can say we are in the right half. But if mid is an odd index, then mid^1
takes us to mid-1 which is the previous even index , which is gets equal means we are in the right
half else left half.
3. This is done because the aim of this implementation is to find the single element in the list of
duplicates. It is only possible if low value is more than high value because at that moment low
will be pointing to the index that contains the single element in the array.
4. After the loop ends, we return the value with low index.

Implementation:

C++CJavaPython3C#Javascript
import java.io.*;
import java.util.Arrays;

class GFG{

static int singleelement(int arr[], int n)


{
int low = 0, high = n - 2;
int mid;

while (low <= high)


{
mid = (low + high) / 2;
if (arr[mid] == arr[mid ^ 1])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return arr[low];
}

// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
int size = 7;
Arrays.sort(arr);
System.out.println(singleelement(arr, size));
}
}

// This code is contributed by dassohom5

Output
2

Time Complexity: O(nlogn)


Auxiliary Space: O(1)

Count set bits in an integer

Write an efficient program to count the number of 1s in the binary representation of an integer.

Examples :

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 13 is 1101 and has 3 set bits
1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is, then increment the
set bit count. See the program below.

C++CJavaPython3C#PHPJavascript

// Java program to Count set


// bits in an integer
import java.io.*;

class countSetBits {
/* Function to get no of set
bits in binary representation
of positive integer n */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}

// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}

// This code is contributed by Anshika Goyal.

Output :

Time Complexity: O(logn)

Auxiliary Space: O(1)

Recursive Approach:

C++CJavaPython3C#PHPJavascript

// Java implementation of recursive


// approach to find the number
// of set bits in binary representation
// of positive integer n
import java.io.*;

class GFG {

// recursive function to count set bits


public static int countSetBits(int n)
{

// base case
if (n == 0)
return 0;

else

// if last bit set add 1 else add 0


return (n & 1) + countSetBits(n >> 1);
}

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

// get value from user


int n = 9;

// function calling
System.out.println(countSetBits(n));
}
}

// This code is contributes by sunnysingh

Output :

Time Complexity: O(log n)

Auxiliary Space: O(1)

2. Brian Kernighan's Algorithm:


Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including
the rightmost set bit.
for example :
10 in binary is 00001010
9 in binary is 00001001
8 in binary is 00001000
7 in binary is 00000111
So if we subtract a number by 1 and do it bitwise & with itself (n & (n-1)), we unset the rightmost set
bit. If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit
count.
The beauty of this solution is the number of times it loops is equal to the number of set bits in a given
integer.

1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count

Implementation of Brian Kernighan's Algorithm:

C++CJavaPython3C#PHPJavascript
// Java program to Count set
// bits in an integer
import java.io.*;

class countSetBits {
/* Function to get no of set
bits in binary representation
of passed binary no. */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}

// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}

// This code is contributed by Anshika Goyal.

Output :

Example for Brian Kernighan's Algorithm:

n = 9 (1001)
count = 0

Since 9 > 0, subtract by 1 and do bitwise & with (9-1)


n = 9&8 (1001 & 1000)
n = 8
count = 1

Since 8 > 0, subtract by 1 and do bitwise & with (8-1)


n = 8&7 (1000 & 0111)
n = 0
count = 2

Since n = 0, return count which is 2 now.

Time Complexity: O(logn)

Auxiliary Space: O(1)

Recursive Approach:

C++JavaPython3C#PHPJavascript

// Java implementation for recursive


// approach to find the number of set
// bits using Brian Kernighan Algorithm
import java.io.*;

class GFG {

// recursive function to count set bits


public static int countSetBits(int n)
{

// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}

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

// get value from user


int n = 9;

// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributed by sunnysingh

Output :

Time Complexity: O(logn)

Auxiliary Space: O(1)

3. Using Lookup table: We can count bits in O(1) time using the lookup table.
Below is the implementation of the above approach:

C++JavaPythonC#Javascript

// Java implementation of the approach


class GFG {

// Lookup table
static int[] BitsSetTable256 = new int[256];

// Function to initialise the lookup table


public static void initialize()
{

// To initially generate the


// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++) {
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}

// Function to return the count


// of set bits in n
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}

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

// Initialise the lookup table


initialize();
int n = 9;
System.out.print(countSetBits(n));
}
}

Output:

Time Complexity: O(1)

As constant time operations are performed

Auxiliary Space: O(1)

As constant extra space is used

We can find one use of counting set bits at Count number of bits to be flipped to convert A to B
Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate
function for counting set bits.

C++JavaPython3C#PHPJavascript

// java program to demonstrate


// __builtin_popcount()

import java.io.*;

class GFG {

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

System.out.println(Integer.bitCount(4));
System.out.println(Integer.bitCount(15));
}
}

// This code is contributed by Raj


Output :

1
4

4. Mapping numbers with the bit. It simply maintains a map(or array) of numbers to bits for a nibble.
A Nibble contains 4 bits. So we need an array of up to 15.
int num_to_bits[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
Now we just need to get nibbles of a given long/int/word etc recursively.

C++CJavaPython3C#PHPJavascript

// Java program to count set bits by pre-storing


// count set bits in nibbles.

class GFG {
static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2,
3, 1, 2, 2, 3, 2, 3, 3, 4 };

/* Recursively get nibble of a given number


and map them in the array */
static int countSetBitsRec(int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];

// Find last nibble


nibble = num & 0xf;

// Use pre-stored values to find count


// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}

// Driver code
public static void main(String[] args)
{
int num = 31;
System.out.println(countSetBitsRec(num));
}
}
// this code is contributed by mits

Output :

Time Complexity: O(log n), because we have log(16, n) levels of recursion.


Storage Complexity: O(1) Whether the given number is short, int, long, or long long we require an
array of 16 sizes only, which is constant.

5. Checking each bit in a number:

Each bit in the number is checked for whether it is set or not. The number is bitwise AND with powers
of 2, so if the result is not equal to zero, we come to know that the particular bit in the position is set.

CC++JavaPython3C#Javascript
public class GFG
{

// Check each bit in a number is set or not


// and return the total count of the set bits.
static int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < 4 * 8; i++)
{
if ((N & (1 << i)) != 0)
count++;
}
return count;
}

// Driver code
public static void main(String[] args)
{
int N = 15;
System.out.println(countSetBits(N));
}
}

// This code is contributed by divyeshrabadiya07.

Output
4
Count set bits in an integer Using Lookup Table

Asked in: Adobe, Brocade, Cisco, Juniper Networks, Qualcomm

Count total set bits in all numbers from 1 to n

Given a positive integer n, count the total number of set bits in binary representation of all numbers
from 1 to n.

Examples:

Input: n = 3
Output: 4

Input: n = 6
Output: 9

Input: n = 7
Output: 12

Input: n = 8
Output: 13

Source: Amazon Interview Question

Method 1 (Simple)
A simple solution is to run a loop from 1 to n and sum the count of set bits in all numbers from 1 to n.

C++CJavaPython3C#PHPJavascript

// A simple program to count set bits


// in all numbers from 1 to n.

class GFG{

// Returns count of set bits present


// in all numbers from 1 to n
static int countSetBits( int n)
{
// initialize the result
int bitCount = 0;

for (int i = 1; i <= n; i++)


bitCount += countSetBitsUtil(i);

return bitCount;
}

// A utility function to count set bits


// in a number x
static int countSetBitsUtil( int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) +
countSetBitsUtil(x / 2);
}

// Driver program
public static void main(String[] args)
{
int n = 4;
System.out.print("Total set bit count is ");
System.out.print(countSetBits(n));
}
}

// This code is contributed by


// Smitha Dinesh Semwal

Output
Total set bit count is 5

Time Complexity: O(nLogn)

Method 2 (Simple and efficient than Method 1)


If we observe bits from rightmost side at distance i than bits get inverted after 2^i position in vertical
sequence.
for example n = 5;
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
Observe the right most bit (i = 0) the bits get flipped after (2^0 = 1)
Observe the 3rd rightmost bit (i = 2) the bits get flipped after (2^2 = 4)
So, We can count bits in vertical fashion such that at i'th right most position bits will be get flipped after
2^i iteration;

C++JavaPython3C#PHPJavascript

public class GFG {

// Function which counts set bits from 0 to n


static int countSetBits(int n)
{
int i = 0;

// ans store sum of set bits from 0 to n


int ans = 0;

// while n greater than equal to 2^i


while ((1 << i) <= n) {

// This k will get flipped after


// 2^i iterations
boolean k = false;

// change is iterator from 2^i to 1


int change = 1 << i;

// This will loop from 0 to n for


// every bit position
for (int j = 0; j <= n; j++) {

if (k == true)
ans += 1;
else
ans += 0;

if (change == 1) {

// When change = 1 flip the bit


k = !k;

// again set change to 2^i


change = 1 << i;
}
else {
change--;
}
}

// increment the position


i++;
}

return ans;
}

// Driver program
public static void main(String[] args)
{
int n = 17;

System.out.println(countSetBits(n));
}
}

// This code is contributed by Sam007.

Output
35

Time Complexity: O(k*n)


where k = number of bits to represent number n
k <= 64

Method 3 (Tricky)
If the input number is of the form 2^b -1 e.g., 1, 3, 7, 15.. etc, the number of set bits is b * 2^(b-1). This
is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same
list (half the bits are on, half off).
If the number does not have all set bits, then some position m is the position of leftmost set bit. The
number of set bits in that position is n - (1 << m) + 1. The remaining set bits are in two parts:
1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and
2) The 2^(m-1) numbers below that point, which is the closed form above.
An easy way to look at it is to consider the number 6:

0|0 0
0|0 1
0|1 0
0|1 1
-|--
1|0 0
1|0 1
1|1 0

The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what
remains is 2 (the "1 0" in the right part of the last row.) So the number of bits in the 2nd position (the
lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4.
The box in the lower right is the remaining bits we haven't yet counted, and is the number of set bits for
all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured
recursively.

C++CJavaPython3C#Javascript

// Java A O(Logn) complexity program to count


// set bits in all numbers from 1 to n
import java.io.*;

class GFG
{

/* Returns position of leftmost set bit.


The rightmost position is considered
as 0 */
static int getLeftmostBit(int n)
{
int m = 0;
while (n > 1)
{
n = n >> 1;
m++;
}
return m;
}

/* Given the position of previous leftmost


set bit in n (or an upper bound on
leftmost position) returns the new
position of leftmost set bit in n */
static int getNextLeftmostBit(int n, int m)
{
int temp = 1 << m;
while (n < temp)
{
temp = temp >> 1;
m--;
}
return m;
}

// The main recursive function used by countSetBits()


// Returns count of set bits present in
// all numbers from 1 to n

static int countSetBits(int n)


{
// Get the position of leftmost set
// bit in n. This will be used as an
// upper bound for next set bit function
int m = getLeftmostBit(n);

// Use the position


return countSetBits(n, m);
}

static int countSetBits( int n, int m)


{
// Base Case: if n is 0, then set bit
// count is 0
if (n == 0)
return 0;

/* get position of next leftmost set bit */


m = getNextLeftmostBit(n, m);

// If n is of the form 2^x-1, i.e., if n


// is like 1, 3, 7, 15, 31, .. etc,
// then we are done.
// Since positions are considered starting
// from 0, 1 is added to m
if (n == ((int)1 << (m + 1)) - 1)
return (int)(m + 1) * (1 << m);
// update n for next recursive call
n = n - (1 << m);
return (n + 1) + countSetBits(n) + m * (1 << (m - 1));
}

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

int n = 17;
System.out.println ("Total set bit count is " + countSetBits(n));
}
}

// This code is contributed by ajit..

Output
Total set bit count is 35

Time Complexity: O(Logn). From the first look at the implementation, time complexity looks more. But
if we take a closer look, statements inside while loop of getNextLeftmostBit() are executed for all 0 bits
in n. And the number of times recursion is executed is less than or equal to set bits in n. In other words,
if the control goes inside while loop of getNextLeftmostBit(), then it skips those many bits in recursion.
Thanks to agatsu and IC for suggesting this solution.
Here is another solution suggested by Piyush Kapoor.

A simple solution , using the fact that for the ith least significant bit, answer will be

(N/2^i)*2^(i-1)+ X

where

X = N%(2^i)-(2^(i-1)-1)

iff

N%(2^i)>(2^(i-1)-1)

C++JavaPython3C#Javascript
static int getSetBitsFromOneToN(int N){
int two = 2,ans = 0;
int n = N;
while(n != 0)
{
ans += (N / two)*(two >> 1);
if((N&(two - 1)) > (two >> 1) - 1)
ans += (N&(two - 1)) - (two >> 1) + 1;
two <<= 1;
n >>= 1;
}
return ans;
}

// This code is contributed by divyeshrabadiya07.

Method 4 (Recursive)

Approach:

For each number 'n', there will be a number a, where a<=n and a is perfect power of two, like 1,2,4,8.....

Let n = 11, now we can see that

Numbers till n, are:


0 -> 0000000
1 -> 0000001
2 -> 0000010
3 -> 0000011
4 -> 0000100
5 -> 0000101
6 -> 0000110
7 -> 0000111
8 -> 0001000
9 -> 0001001
10 -> 0001010
11 -> 0001011

Now we can see that, from 0 to pow(2,1)-1 = 1, we can pair elements top-most with b
ottom-most,
and count of set bit in a pair is 1

Similarly for pow(2,2)-1 = 4, pairs are:


00 and 11
01 and 10
here count of set bit in a pair is 2, so in both pairs is 4

Similarly we can see for 7, 15, ans soon.....


so we can generalise that,
count(x) = (x*pow(2,(x-1))),
here x is position of set bit of the largest power of 2 till n
for n = 8, x = 3
for n = 4, x = 2
for n = 5, x = 2

so now for n = 11,


we have added set bits count from 0 to 7 using count(x) = (x*pow(2,(x-1)))

for rest numbers 8 to 11, all will have a set bit at 3rd index, so we can add
count of rest numbers to our ans,
which can be calculated using 11 - 8 + 1 = (n-pow(2,x) + 1)

Now if notice that, after removing front bits from rest numbers, we get again numbe
r from 0 to some m
so we can recursively call our same function for next set of numbers,
by calling countSetBits(n - pow(2,x))
8 -> 1000 -> 000 -> 0
9 -> 1001 -> 001 -> 1
10 -> 1010 -> 010 -> 2
11 -> 1011 -> 011 -> 3

Code:

C++JavaPython3C#Javascript
import java.io.*;
class GFG
{
static int findLargestPower(int n)
{
int x = 0;
while ((1 << x) <= n)
x++;
return x - 1;
}

static int countSetBits(int n)


{
if (n <= 1)
return n;
int x = findLargestPower(n);
return (x * (int)Math.pow(2, (x - 1))) + (n - (int)Math.pow(2, x) + 1)
+ countSetBits(n - (int)Math.pow(2, x));
}

public static void main(String[] args)


{
int N = 17;
System.out.print(countSetBits(N));
}
}

// This code is contributed by shivanisinghss2110

Output
35

Time Complexity: O(LogN)

Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above

Method 5(Iterative)

Example:

0 -> 0000000 8 -> 001000 16 -> 010000 24 -> 011000

1 -> 0000001 9 -> 001001 17 -> 010001 25 -> 011001

2 -> 0000010 10 -> 001010 18 -> 010010 26 -> 011010

3 -> 0000011 11 -> 001011 19 -> 010010 27 -> 011011

4 -> 0000100 12 -> 001100 20 -> 010100 28 -> 011100

5 -> 0000101 13 -> 001101 21 -> 010101 29 -> 011101

6 -> 0000110 14 -> 001110 22 -> 010110 30 -> 011110

7 -> 0000111 15 -> 001111 23 -> 010111 31 -> 011111

Input: N = 4

Output: 5

Input: N = 17
Output: 35

Approach : Pattern recognition

Let 'N' be any arbitrary number and consider indexing from right to left(rightmost being 1);
then nearestPow = pow(2,i).

Now, when you write all numbers from 1 to N, you will observe the pattern mentioned below:

For every index i, there are exactly nearestPow/2 continuous elements that are unset followed by
nearestPow/2 elements that are set.

Throughout the solution, i am going to use this concept.

You can clearly observe above concept in the above table.

The general formula that i came up with:

a. addRemaining = mod - (nearestPos/2) + 1 iff mod >= nearestPow/2;

b. totalSetBitCount = totalRep*(nearestPow/2) + addRemaining

where totalRep -> total number of times the pattern repeats at index i

addRemaining -> total number of set bits left to be added after the pattern is exhausted

Eg: let N = 17

leftMostSetIndex = 5 (Left most set bit index, considering 1 based indexing)

i = 1 => nearestPos = pow(2,1) = 2; totalRep = (17+1)/2 = 9 (add 1 only for i=1)

mod = 17%2 = 1

addRemaining = 0 (only for base case)

totalSetBitCount = totalRep*(nearestPos/2) + addRemaining = 9*(2/2) + 0 = 9*1 + 0 = 9

i = 2 => nearestPos = pow(2, 2)=4; totalRep = 17/4 = 4

mod = 17%4 = 1

mod(1) < (4/2) => 1 < 2 => addRemaining = 0

totalSetBitCount = 9 + 4*(2) + 0 = 9 + 8 = 17

i = 3 => nearestPow = pow(2,3) = 8; totalRep = 17/8 = 2

mod = 17%8 = 1

mod < 4 => addRemaining = 0


totalSetBitCount = 17 + 2*(4) + 0 = 17 + 8 + 0 = 25

i = 4 => nearestPow = pow(2, 4) = 16; totalRep = 17/16 = 1

mod = 17%16 = 1

mod < 8 => addRemaining = 0

totalSetBitCount = 25 + 1*(8) + 0 = 25 + 8 + 0 = 33

We cannot simply operate on the next power(32) as 32>17. Also, as the first half bits will be 0s only, we
need to find the distance of the given number(17) from the last power to directly get the number of 1s
to be added

i = 5 => nearestPow = (2, 5) = 32 (base case 2)

lastPow = pow(2, 4) = 16

mod = 17%16 = 1

totalSetBit = 33 + (mod+1) = 33 + 1 + 1 = 35

Therefore, total num of set bits from 1 to 17 is 35

Try iterating with N = 30, for better understanding of the solution.

Solution

C++JavaPython3C#Javascript
import java.io.*;
import java.util.*;
class GFG{
static int GetLeftMostSetBit(int n){
int pos = 0;

while(n>0){
pos++;
n>>=1;
}

return pos;
}

static int TotalSetBitsFrom1ToN(int n){


int leftMostSetBitInd = GetLeftMostSetBit(n);

int totalRep, mod;


int nearestPow;
int totalSetBitCount = 0;
int addRemaining = 0;

int curr = 0; // denotes the number of set bits at index i

for(int i=1; i<=leftMostSetBitInd; ++i){


nearestPow = (int)Math.pow(2, i);
if(nearestPow>n){
int lastPow = (int)Math.pow(2, i-1);
mod = n%lastPow;
totalSetBitCount += mod+1;
}
else{
if(i == 1 && n % 2 == 1){
totalRep = (n + 1) / nearestPow;
mod = nearestPow % 2;
addRemaining = 0;
}
else{
totalRep = n/nearestPow;
mod = n%nearestPow;

if(mod >= (nearestPow/2))


{
addRemaining = mod - (nearestPow/2) + 1;
}
else{
addRemaining = 0;
}
}

curr = totalRep*(nearestPow/2) + addRemaining;


totalSetBitCount += curr;
}
}

return totalSetBitCount;
}

public static void main(String[] args){


System.out.println(TotalSetBitsFrom1ToN(4));
System.out.println(TotalSetBitsFrom1ToN(17));
System.out.println(TotalSetBitsFrom1ToN(30));
}
}

// This code is contributed by vikaschhonkar1


// By: Vikas Chhonkar

Output :

35

75

Time Complexity: O(log(n))


Swap bits in a given number

Given a number x and two positions (from the right side) in the binary representation of x, write a
function that swaps n bits at the given two positions and returns the result. It is also given that the two
sets of bits do not overlap.

Method 1
Let p1 and p2 be the two given positions.

Example 1

Input:
x = 47 (00101111)
p1 = 1 (Start from the second bit from the right side)
p2 = 5 (Start from the 6th bit from the right side)
n = 3 (No of bits to be swapped)
Output:
227 (11100011)
The 3 bits starting from the second bit (from the right side) are
swapped with 3 bits starting from 6th position (from the right side)

Example 2

Input:
x = 28 (11100)
p1 = 0 (Start from first bit from right side)
p2 = 3 (Start from 4th bit from right side)
n = 2 (No of bits to be swapped)
Output:
7 (00111)
The 2 bits starting from 0th position (from right side) are
swapped with 2 bits starting from 4th position (from right side)

Solution
We need to swap two sets of bits. XOR can be used in a similar way as it is used to swap 2 numbers.
Following is the algorithm.

1) Move all bits of the first set to the rightmost side


set1 = (x >> p1) & ((1U << n) - 1)
Here the expression (1U << n) - 1 gives a number that
contains last n bits set and other bits as 0. We do &
with this expression so that bits other than the last
n bits become 0.
2) Move all bits of second set to rightmost side
set2 = (x >> p2) & ((1U << n) - 1)
3) XOR the two sets of bits
xor = (set1 ^ set2)
4) Put the xor bits back to their original positions.
xor = (xor << p1) | (xor << p2)
5) Finally, XOR the xor with original number so
that the two sets are swapped.
result = x ^ xor

Implementation:

C++CJavaPython3C#PHPJavascript

// Java Program to swap bits


// in a given number

class GFG {

static int swapBits(int x, int p1, int p2, int n)


{
// Move all bits of first set
// to rightmost side
int set1 = (x >> p1) & ((1 << n) - 1);
// Move all bits of second set
// to rightmost side
int set2 = (x >> p2) & ((1 << n) - 1);

// XOR the two sets


int xor = (set1 ^ set2);

// Put the xor bits back to


// their original positions
xor = (xor << p1) | (xor << p2);

// XOR the 'xor' with the original number


// so that the two sets are swapped
int result = x ^ xor;

return result;
}

// Driver program
public static void main(String[] args)
{
int res = swapBits(28, 0, 3, 2);
System.out.println("Result = " + res);
}
}

// This code is contributed by prerna saini.

Output
Result = 7

Time Complexity: O(1), as we are using constant-time operations.

Auxiliary Space: O(1), as we are not using any extra space.

Following is a shorter implementation of the same logic

C++CJavaPython3C#Javascript
static int swapBits(int x, int p1, int p2, int n)
{
/* xor contains xor of two sets */
int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
/* To swap two sets, we need to again XOR the xor with
* original sets */
return x ^ ((xor << p1) | (xor << p2));
}

// This code is contributed by subhammahato348.

Time Complexity: O(1), as we are using constant-time operations.

Auxiliary Space: O(1), as we are not using any extra space.

Method 2 -
This solution focuses on calculating the values of bits to be swapped using AND gate. Then we can
set/unset those bits based on whether the bits are to be swapped. For the number of bits to be swapped
(n) -

 Calculate shift1 = The value after setting bit at p1 position to 1


 Calculate shift2 = The value after setting bit at p2 position to 1
 value1 = Number to check if num at position p1 is set or not.
 value2 = Number to check if num at position p2 is set or not.
 If value1 and value2 are different is when we have to swap the bits.

Example:

[28 0 3 2] num=28 (11100) p1=0 p2=3 n=2


Given = 11100
Required output = 00111 i.e. (00)1(11) msb 2 bits replaced with lsb 2 bits

n=2
p1=0, p2=3
shift1= 1, shift2= 1000
value1= 0, value2= 1000
After swap
num= 10101

n=3
p1=1, p2=4
shift1= 10, shift2= 10000
value1= 0, value2= 10000
After swap
num= 00111

Implementation

C++JavaPython3C#Javascript
class GFG
{
static int swapBits(int num, int p1, int p2, int n)
{
int shift1, shift2, value1, value2;
while (n-- > 0)
{

// Setting bit at p1 position to 1


shift1 = 1 << p1;

// Setting bit at p2 position to 1


shift2 = 1 << p2;

// value1 and value2 will have 0 if num


// at the respective positions - p1 and p2 is 0.
value1 = ((num & shift1));
value2 = ((num & shift2));

// check if value1 and value2 are different


// i.e. at one position bit is set and other it is not
if ((value1 == 0 && value2 != 0) ||
(value2 == 0 && value1 != 0))
{

// if bit at p1 position is set


if (value1 != 0)
{

// unset bit at p1 position


num = num & (~shift1);

// set bit at p2 position


num = num | shift2;
}

// if bit at p2 position is set


else
{

// set bit at p2 position


num = num & (~shift2);

// unset bit at p2 position


num = num | shift1;
}
}
p1++;
p2++;
}

// return final result


return num;
}

// Driver code
public static void main(String[] args)
{
int res = swapBits(28, 0, 3, 2);
System.out.println("Result = " + res);
}
}

// This code is contributed by divyeshrabadiya07

Output
Result = 7

Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of bits to
be swapped.

Auxiliary Space: O(1), as we are not using any extra space.

String class in Java | Set 1

String is a sequence of characters. In java, objects of String are immutable which means a constant and
cannot be changed once created.

Creating a String

There are two ways to create string in Java:

 String literal
 String s = “GeeksforGeeks”;
 Using new keyword
 String s = new String (“GeeksforGeeks”);

Constructors

1. String(byte[] byte_arr) - Construct a new String by decoding the byte array. It uses the
platform's default character set for decoding. Example:
2. byte[] b_arr = {71, 101, 101, 107, 115};
3. String s_byte =new String(b_arr); //Geeks
4.

5. String(byte[] byte_arr, Charset char_set) - Construct a new String by decoding the byte array.
It uses the char_set for decoding. Example:
6. byte[] b_arr = {71, 101, 101, 107, 115};
7. Charset cs = Charset.defaultCharset();
8. String s_byte_char = new String(b_arr, cs); //Geeks
9.

10. String(byte[] byte_arr, String char_set_name) - Construct a new String by decoding the byte
array. It uses the char_set_name for decoding. It looks similar to the above constructs and they
appear before similar functions but it takes the String(which contains char_set_name) as
parameter while the above constructor takes CharSet. Example:
11. byte[] b_arr = {71, 101, 101, 107, 115};
12. String s = new String(b_arr, "US-ASCII"); //Geeks
13.

14. String(byte[] byte_arr, int start_index, int length) - Construct a new string from the bytes
array depending on the start_index(Starting location) and length(number of characters from
starting location). Example:
15. byte[] b_arr = {71, 101, 101, 107, 115};
16. String s = new String(b_arr, 1, 3); // eek
17.

18. String(byte[] byte_arr, int start_index, int length, Charset char_set) - Construct a new string
from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding. Example:
19. byte[] b_arr = {71, 101, 101, 107, 115};
20. Charset cs = Charset.defaultCharset();
21. String s = new String(b_arr, 1, 3, cs); // eek
22.

23. String(byte[] byte_arr, int start_index, int length, String char_set_name) - Construct a new
string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set_name for decoding. Example:
24. byte[] b_arr = {71, 101, 101, 107, 115};
25. String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks
26.
27. String(char[] char_arr) - Allocates a new String from the given Character array Example:
28. char char_arr[] = {'G', 'e', 'e', 'k', 's'};
29. String s = new String(char_arr); //Geeks
30.

31. String(char[] char_array, int start_index, int count) - Allocates a String from a given character
array but choose count characters from the start_index. Example:
32. char char_arr[] = {'G', 'e', 'e', 'k', 's'};
33. String s = new String(char_arr , 1, 3); //eek
34.

35. String(int[] uni_code_points, int offset, int count) - Allocates a String from
a uni_code_array but choose count characters from the start_index. Example:
36. int[] uni_code = {71, 101, 101, 107, 115};
37. String s = new String(uni_code, 1, 3); //eek
38.

39. String(StringBuffer s_buffer) - Allocates a new string from the string in s_buffer Example:
40. StringBuffer s_buffer = new StringBuffer("Geeks");
41. String s = new String(s_buffer); //Geeks
42.

43. String(StringBuilder s_builder) - Allocates a new string from the string in s_builder Example:
44. StringBuilder s_builder = new StringBuilder("Geeks");
45. String s = new String(s_builder); //Geeks
46.

String Methods

1. int length(): Returns the number of characters in the String.


2. "GeeksforGeeks".length(); // returns 13

3. Char charAt(int i): Returns the character at ith index.


4. "GeeksforGeeks".charAt(3); // returns ‘k’

5. String substring (int i): Return the substring from the ith index character to end.
6. "GeeksforGeeks".substring(3); // returns “ksforGeeks”

7. String substring (int i, int j): Returns the substring from i to j-1 index.
8. "GeeksforGeeks".substring(2, 5); // returns “eks”

9. String concat( String str): Concatenates specified string to the end of this string.
10. String s1 = ”Geeks”;
11. String s2 = ”forGeeks”;
12. String output = s1.concat(s2); // returns “GeeksforGeeks”
13.

14. int indexOf (String s): Returns the index within the string of the first occurrence of the specified
string.
15. String s = ”Learn Share Learn”;
16. int output = s.indexOf(“Share”); // returns 6
17.
18. int indexOf (String s, int i): Returns the index within the string of the first occurrence of the
specified string, starting at the specified index.
19. String s = ”Learn Share Learn”;
20. int output = s.indexOf("ea",3);// returns 13
21.

22. Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the
specified string.
23. String s = ”Learn Share Learn”;
24. int output = s.lastIndexOf("a"); // returns 14
25.

26. boolean equals( Object otherObj): Compares this string to the specified object.
27. Boolean out = “Geeks”.equals(“Geeks”); // returns true
28. Boolean out = “Geeks”.equals(“geeks”); // returns false
29.

30. boolean equalsIgnoreCase (String anotherString): Compares string to another string,


ignoring case considerations.
31. Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
32. Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

33. int compareTo( String anotherString): Compares two string lexicographically.


34. int out = s1.compareTo(s2); // where s1 ans s2 are
35. // strings to be compared
36.
37. This returns difference s1-s2. If :
38. out < 0 // s1 comes before s2
39. out = 0 // s1 and s2 are equal.
40. out > 0 // s1 comes after s2.
41.

42. int compareToIgnoreCase( String anotherString): Compares two string lexicographically,


ignoring case considerations.
43. int out = s1.compareToIgnoreCase(s2);
44. // where s1 ans s2 are
45. // strings to be compared
46.
47. This returns difference s1-s2. If :
48. out < 0 // s1 comes before s2
49. out = 0 // s1 and s2 are equal.
50. out > 0 // s1 comes after s2.
51.

Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or
lowercase).

52. String toLowerCase(): Converts all the characters in the String to lower case.
53. String word1 = “HeLLo”;
54. String word3 = word1.toLowerCase(); // returns “hello"
55.

56. String toUpperCase(): Converts all the characters in the String to upper case.
57. String word1 = “HeLLo”;
58. String word2 = word1.toUpperCase(); // returns “HELLO”
59.

60. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.
61. String word1 = “ Learn Share Learn “;
62. String word2 = word1.trim(); // returns “Learn Share Learn”
63.

64. String replace (char oldChar, char newChar): Returns new string by replacing all
occurrences of oldChar with newChar.
65. String s1 = “feeksforfeeks“;
66. String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
67.

Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks

Program to illustrate all string methods:Java

// Java code to illustrate different constructors and methods


// String class.

import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = "
+ s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));
// Returns the substring from i to j-1 index.
System.out.println("Substring = " + s.substring(2,5));

// Concatenates string2 to the end of string1.


String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " +
s1.concat(s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +
s4.indexOf("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +
s4.indexOf('a',3));

// Checking equality of Strings


Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);

out = "Geeks".equalsIgnoreCase("gEeks ");


System.out.println("Checking Equality " + out);

//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value
is="+out1);
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +
word1.toLowerCase());

// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
word2.toUpperCase());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output :
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality false
the difference between ASCII value is=-31
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks

For Set - 2 you can refer: Java.lang.String class in Java | Set 2


Methods in Java

A method is a collection of statements that perform some specific task and return result to the caller. A
method can perform some specific task without returning anything. Methods allow us to reuse the code
without retyping the code. In Java, every method must be part of some class which is different from
languages like C, C++ and Python.

Method Declaration
In general, method declarations has six components :

 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
o public: accessible in all class in your application.
o protected: accessible within the class in which it is defined and in its subclass(es)
o private: accessible only within the class in which it is defined.
o default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
 The return type : The data type of the value returned by the the method or void if does not
return a value.
 Method Name : the rules for field names apply to method names as well, but the convention is
a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
 Method body : it is enclosed between braces. The code you need to be executed to perform your
intended operations.

Method signature: It consists of method name and parameter list (number of parameters, type of the
parameters and order of the parameters). Return type and exceptions are not considered as part of it.
Method Signature of above function:

max(int x, int y)

How to name a Method?: A method name is typically a single word that should be a verb in lowercase
or multi-word, that begins with a verb in lowercase followed by adjective, noun..... After the first word,
first letter of each word should be capitalized. For example, findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is defined but sometime a method
might have same name as other method name within the same class due to method overloading.

Calling a method

A method needs to be called for using its functionality. There can be three situations when a method is
called:
A method returns to the code that invoked it when it

 It completes all the statements in the method


 It reaches a return statement
 Throws an exception

Java

// Java program to illustrate different ways of calling a method


import java.io.*;

class Test
{
public static int i = 0;

// constructor of class which counts


// the number of the objects of the class.
Test()
{
i++;
}

// static method is used to access static members of


// the class and for getting total no of objects
// of the same class created so far
public static int get()
{
// statements to be executed....
return i;
}

// Instance method calling object directly


// that is created inside another class 'GFG'.
// Can also be called by object directly created in the
// ame class and from another method defined in the
// same class and return integer value as return type
// is int.
public int m1()
{
System.out.println("Inside the method m1 by object of GFG
class");

// calling m2() method within the same class.


this.m2();

// statements to be executed if any


return 1;
}

// It doesn't return anything as


// return type is 'void'.
public void m2()
{
System.out.println("In method m2 came from method m1");
}
}

class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();

// Calling the m1() method by the object created in above step.


int i = obj.m1();
System.out.println("Control returned after method m1 :" + i);

// Call m2() method


// obj.m2();
int no_of_objects = Test.get();

System.out.print("No of instances created till now : ");


System.out.println(no_of_objects);
}
}
Output :
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1

Control flow of above program

Memory allocation for methods calls: Methods calls are implemented through stack.
Whenever a method is called a stack frame is created within the stack area and after that the
arguments passed to and the local variables and value to be returned by this called method are
stored in this stack frame and when execution of the called method is finished the
allocated stack frame would be deleted. There is a stack pointer register that tracks the top of
the stack. It is adjusted accordingly.
Method Overloading

Java programming supports method overloading. Java can distinguish the methods
with different method signatures. i.e. the methods can have same name but with different
parameters list (i.e. number of the parameters, order of the parameters, and data types of the
parameters) within the same class.

o Overloaded methods are differentiated based on the number and type of the parameters
passed as an arguments to the methods.
o You can not define more than one method with the same name and the same number and
the type of the arguments. It would be compiler error.
o The compiler does not consider the return type while differentiating the overloaded
method. You can declare the methods with the same signature and different return type.
Java

// Java program to illustrate method overloading


import java.io.*;

class Addition{

// adding two integer values.


public int add(int a, int b){

int sum = a+b;


return sum;
}

// adding three integer values.


public int add(int a, int b, int c){

int sum = a+b+c;


return sum;
}

// adding three double values.


public double add(double a, double b, double c){

double sum = a+b+c;


return sum;
}
}

class GFG {
public static void main (String[] args) {

Addition ob = new Addition();

int sum1 = ob.add(1,2);


System.out.println("sum of the two integer value :" + sum1);
int sum2 = ob.add(1,2,3);
System.out.println("sum of the three integer value :" + sum2);
double sum3 = ob.add(1.0,2.0,3.0);
System.out.println("sum of the three double value :" + sum3);
}
}
Output:
sum of the two integer value :3
sum of the three integer value :6
sum of the three double value :6.0

What happens when method signature is same and the return type is different?

The compiler will give error as the return value alone is not sufficient for the compiler to figure
out which function it has to call. More details:Java Language Specification: §8.4.2. Only if both
methods has different parameter types (so, they have different signature), then Method
overloading is possible.Java

// Example to show error when method signature is same


// and return type is different.
import java.io.*;

class Addition
{
// adding two integer value.
public int add(int a, int b)
{

int sum = a+b;


return sum;
}

// adding three integer value.


public double add(int a, int b)
{
double sum = a+b+0.0;
return sum;
}

class GFG
{
public static void main (String[] args)
{
Addition ob = new Addition();

int sum1 = ob.add(1,2);


System.out.println("sum of the two integer value :" + sum1);

int sum2 = ob.add(1,2);


System.out.println("sum of the three integer value :" + sum2);

}
}
Important Points:

o A method can be declared abstract using the abstract keyword and final using the final
keyword but can not be both simultaneously.
o A method can also be declared static using the static keyword and static method(s)
belongs to the class not to the objects of the same class and can be called without making
the object of the class within which they are declared.

Articles (12)

Classes and Objects in Java

Java is Strictly Pass by Value!

Types of References in Java

Important Keywords in Java

How are Java objects stored in memory?

'this' reference in Java

final Keyword in Java

Java.lang.Math Class in Java | Set 1

Math pow() method in Java with Example

Java sqrt() method with Examples

BigInteger Class in Java

BigInteger mod() Method in Java


Classes and Objects in Java

Classes and Objects are basic concepts of Object Oriented Programming that revolve around real life
entities.

Class

A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:

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

Constructors are used for initializing new objects. Fields are variables that provide the state of the class
and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

Object
It is a basic unit of Object-Oriented Programming and represents real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of
:

1. State: It is represented by attributes of an object. It also reflects the properties of an object.


2. Behavior: It is represented by methods of an object. It also reflects the response of an object
with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics program may have objects
such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping
cart", "customer", and "product".
Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.

Example:

As we declare variables like (type name;). This notifies the compiler that we will use the name to refer
to data whose type is type. With a primitive variable, this declaration also reserves the proper amount
of memory for the variable. So for reference variable, the type must be strictly a concrete class name. In
general, we can't create objects of an abstract class or an interface.

Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference
to that memory. The new operator also invokes the class constructor.

Java

// Class Declaration

public class Dog


{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}

// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

// method 4
public String getColor()
{
return color;
}

@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output:

Hi my name is tuffy.
My breed,age and color are papillon,5,white

 This class contains a single constructor. We can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments. The constructor in
the Dog class takes four arguments. The following statement provides
"tuffy","papillon",5,"white" as values for those arguments:

Dog tuffy = new Dog("tuffy","papillon",5, "white");

 The result of executing this statement can be illustrated as :


Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument constructor, also called the default constructor. This
default constructor calls the class parent's no-argument constructor (as it contains only one statement
i.e super();), or the Object class constructor if the class has no other parent (as the Object class is the
parent of all classes either directly or indirectly).

Ways to create an object of a class

There are four ways to create objects in java. Strictly speaking there is only one way(by
using new keyword), and the rest internally use new keyword.

 Using new keyword: It is the most common and general way to create an object in java.
Example:
// creating object of class Test
Test t = new Test();

 Using Class.forName(String className) method: There is a pre-defined class in java.lang


package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name. We have to give a fully qualified name for
a class. On calling new Instance() method on this Class object returns new instance of the class
with the given string name.

// creating object of public class Test


// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

 Using clone() method: clone() method is present in Object class. It creates and returns a copy
of the object.

// creating object of class Test


Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();

 Deserialization: De-serialization is a technique of reading an object from the saved state in a


file. Refer Serialization/De-Serialization in java

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

 In real-time, we need different objects of a class in different methods. Creating a number of


references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case, the wastage of memory is less. The objects
that are not referenced anymore will be destroyed by Garbage Collector of java. Example:

Test test = new Test();


test = new Test();

 In inheritance system, we use parent class reference variable to store a sub-class object. In this
case, we can switch into different subclass objects using same referenced variable. Example:

class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{
// using Dog object
Animal obj = new Dog();

// using Cat object


obj = new Cat();
}

Anonymous objects

Anonymous objects are objects that are instantiated but are not stored in a reference variable.

 They are used for immediate method calling.


 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are used to
perform some action on capturing an event(eg a key press).
 In the example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.

btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});

Java is Strictly Pass by Value!

Consider the following Java program that passes a primitive type to function.

Java

public class Main


{
public static void main(String[] args)
{
int x = 5;
change(x);
System.out.println(x);
}
public static void change(int x)
{
x = 10;
}
}

Output:

We pass an int to the function “change()” and as a result the change in the value of that integer is not
reflected in the main method. Like C/C++, Java creates a copy of the variable being passed in the method
and then do the manipulations. Hence the change is not reflected in the main method.

How about objects or references?

In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any
class) are always references. So it gets tricky when we pass object references to methods. Java creates
a copy of references and pass it to method, but they still point to same memory reference. Mean if set
some other reference to object passed inside method, the object from calling method as well its
reference will remain unaffected. The changes are not reflected back if we change the object itself
to refer some other location or object If we assign reference to some other location, then changes are
not reflected back in main().

Java

// A Java program to show that references are also passed


// by value.
class Test
{
int x;
Test(int i) { x = i; }
Test() { x = 0; }
}

class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);

// Reference is passed and a copy of reference


// is created in change()
change(t);
// Old value of t.x is printed
System.out.println(t.x);
}
public static void change(Test t)
{
// We changed reference to refer some other location
// now any changes made to reference are not reflected
// back in main
t = new Test();

t.x = 10;
}
}

Output:

Changes are reflected back if we do not assign reference to a new location or object: If we do not
change the reference to refer some other object (or memory location), we can make changes to the
members and these changes are reflected back.

Java

// A Java program to show that we can change members using


// reference if we do not change the reference itself.
class Test
{
int x;
Test(int i) { x = i; }
Test() { x = 0; }
}

class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);

// Reference is passed and a copy of reference


// is created in change()
change(t);
// New value of x is printed
System.out.println(t.x);
}

// This change() doesn't change the reference, it only


// changes member of object referred by reference
public static void change(Test t)
{
t.x = 10;
}
}

Output:

10

Exercise: Predict the output of following Java program

Java

// Test.java
class Main {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j)
{
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}
}

Types of References in Java

In Java there are four types of references differentiated on the way by which they are garbage collected.

1. Strong References
2. Weak References
3. Soft References
4. Phantom References

Prerequisite: Garbage Collection

 Strong References: This is the default type/class of Reference Object. Any object which has an
active strong reference are not eligible for garbage collection. The object is garbage collected
only when the variable which was strongly referenced points to null.
 MyClass obj = new MyClass ();

Here 'obj' object is strong reference to newly created instance of MyClass, currently obj is active
object so can't be garbage collected.

obj = null;
//'obj' object is no longer referencing to the instance.
So the 'MyClass type object is now available for garbage collection.

Java

// Java program to illustrate Strong reference


class Gfg
{
//Code..
}
public class Example
{
public static void main(String[] args)
{
//Strong Reference - by default
Gfg g = new Gfg();

//Now, object to which 'g' was pointing earlier is


//eligible for garbage collection.
g = null;
}
}

 Weak References: Weak Reference Objects are not the default type/class of Reference Object
and they should be explicitly specified while using them.
o This type of reference is used in WeakHashMap to reference the entry objects .
o If JVM detects an object with only weak references (i.e. no strong or soft references linked
to any object object), this object will be marked for garbage collection.
o To create such references java.lang.ref.WeakReference class is used.
o These references are used in real time applications while establishing a DBConnection
which might be cleaned up by Garbage Collector when the application using the database
gets closed.

Java

//Java Code to illustrate Weak reference


import java.lang.ref.WeakReference;
class Gfg
{
//code
public void x()
{
System.out.println("GeeksforGeeks");
}
}
public class Example
{
public static void main(String[] args)
{
// Strong Reference
Gfg g = new Gfg();
g.x();

// Creating Weak Reference to Gfg-type object to which 'g'


// is also pointing.
WeakReference<Gfg> weakref = new WeakReference<Gfg>(g);

//Now, Gfg-type object to which 'g' was pointing earlier


//is available for garbage collection.
//But, it will be garbage collected only when JVM needs memory.
g = null;

// You can retrieve back the object which


// has been weakly referenced.
// It successfully calls the method.
g = weakref.get();

g.x();
}
}

Output:

GeeksforGeeks
GeeksforGeeks

Two different levels of weakness can be enlisted: Soft and Phantom

 Soft References: In Soft reference, even if the object is free for garbage collection then also its
not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the
memory when JVM runs out of memory.To create such
references java.lang.ref.SoftReference class is used.
Java

 //Code to illustrate Soft reference
 import java.lang.ref.SoftReference;
 class Gfg
 {
 //code..
 public void x()
 {
 System.out.println("GeeksforGeeks");
 }
 }

 public class Example
 {
 public static void main(String[] args)
 {
 // Strong Reference
 Gfg g = new Gfg();
 g.x();

 // Creating Soft Reference to Gfg-type object to which 'g'
 // is also pointing.
 SoftReference<Gfg> softref = new SoftReference<Gfg>(g);

 // Now, Gfg-type object to which 'g' was pointing
 // earlier is available for garbage collection.
 g = null;

 // You can retrieve back the object which
 // has been weakly referenced.
 // It successfully calls the method.
 g = softref.get();

 g.x();
 }
 }

Output:

GeeksforGeeks
GeeksforGeeks

 Phantom References: The objects which are being referenced by phantom references are
eligible for garbage collection. But, before removing them from the memory, JVM puts them in a
queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method
on them.To create such references java.lang.ref.PhantomReference class is used.Java

 //Code to illustrate Phantom reference
 import java.lang.ref.*;
 class Gfg
 {
 //code
 public void x()
 {
 System.out.println("GeeksforGeeks");
 }
 }

 public class Example
 {
 public static void main(String[] args)
 {
 //Strong Reference
 Gfg g = new Gfg();
 g.x();

 //Creating reference queue
 ReferenceQueue<Gfg> refQueue = new ReferenceQueue<Gfg>();

 //Creating Phantom Reference to Gfg-type object to which 'g'
 //is also pointing.
 PhantomReference<Gfg> phantomRef = null;

 phantomRef = new PhantomReference<Gfg>(g,refQueue);

 //Now, Gfg-type object to which 'g' was pointing
 //earlier is available for garbage collection.
 //But, this object is kept in 'refQueue' before
 //removing it from the memory.
 g = null;

 //It always returns null.
 g = phantomRef.get();

 //It shows NullPointerException.
 g.x();
 }
 }

Runtime Error:

Exception in thread "main" java.lang.NullPointerException


at Example.main(Example.java:31)

Output:

GeeksforGeeks

Important Keywords in Java

Keywords refer to the reserved set of words of a language. These are used for some predefined actions.

1. abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve
abstraction. For more, refer to abstract keyword in java
2. enum: It is used to define enum in Java
3. instanceof: It is used to know whether the object is an instance of the specified type (class or
subclass or interface).
4. private: It is an access modifier. Anything declared private cannot be seen outside of its class.
5. protected: If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
6. public: Anything declared public can be accessed from anywhere. For more on Access Modifiers,
refer to Access Modifiers in Java
7. static: It is used to create a member(block, method, variable, nested classes) that can be used by
itself, without reference to a specific instance. For more, refer static keyword in java
8. strictfp: It is used for restricting floating-point calculations and ensuring the same result on
every platform while performing operations in the floating-point variable. For more
refer strictfp keyword in Java
9. synchronized: Applicable for blocks methods. It is used to get synchronization in java. For more,
refer to Synchronized in Java
10. transient: transient is a variables modifier used in serialization. At the time of serialization, if
we don’t want to save the value of a particular variable in a file, then we use the transient
keyword. For more refer transient keyword in Java
11. volatile: The volatile modifier tells the compiler that the variable modified by volatile can be
changed unexpectedly by other parts of your program. For more, refer to volatile keyword in
java

How are Java objects stored in memory?

In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be
allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the
object is allocated on Heap, otherwise on Stack if not global or static.
In Java, when we only declare a variable of a class type, only a reference is created (memory is not
allocated for the object). To allocate memory to an object, we must use new(). So the object is always
allocated memory on the heap (See this for more details).

There are two ways to create an object of string in java:

1. By string literal
2. By new keyword

i) By string literal:

This is done using double-quotes.

For example:

String str1="GFG";
String str2="GFG";
By String Literal
Every time when a string literal is created, JVM will check whether that string already exists in the string
constant pool or not. If the string already exists in the string literal pool then a reference to the pooled
instance is returned. If the string does not exist, then a new string instance is created in the pool. Hence,
only one object will get created.

Here, the JVM is not bonded to create a new memory.

ii) By new keyword:

This is done using a new keyword.

For example:

String str1=new String("Hello");


String str2=new String("Hello");

By new Keyword
Both str1 and str2 are objects of String.

Every time when a string object is created, JVM will create it in a heap memory. In this case, the JVM will
not check whether the string already exists or not. If a string already exist , then also for every string
object the memory will get created separately.

Here, the JVM is bond to create a new memory. For example, the following program fails in the
compilation. Compiler gives error "Error here because t is not initialized".

java

class Test {

// class contents
void show()
{
System.out.println("Test::show() called");
}
}

public class Main {

// Driver Code
public static void main(String[] args)
{
Test t;

// Error here because t


// is not initialized
t.show();
}
}

Output:

Allocating memory using new() makes the above program work.

java

class Test {

// class contents
void show()
{
System.out.println("Test::show() called");
}
}

public class Main {


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

// all objects are dynamically


// allocated
Test t = new Test();
t.show(); // No error
}
}

Output
Test::show() called

'this' reference in Java

'this' is a reference variable that refers to the current object.

Following are the ways to use 'this' keyword in java :


1. Using 'this' keyword to refer current class instance variables

Java

//Java code for using 'this' keyword to


//refer current class instance variables
class Test
{
int a;
int b;

// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
}

Output:

a = 10 b = 20

2. Using this() to invoke current class constructor

Java

// Java code for using this() to


// invoke current class constructor
class Test
{
int a;
int b;

//Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}

//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test();
}
}

Output:

Inside parameterized constructor


Inside default constructor

3. Using 'this' keyword to return the current class instance

Java

//Java code for using 'this' keyword


//to return the current class instance
class Test
{
int a;
int b;

//Default constructor
Test()
{
a = 10;
b = 20;
}

//Method that returns current class instance


Test get()
{
return this;
}

//Displaying value of variables a and b


void display()
{
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test();
object.get().display();
}
}

Output:
a = 10 b = 20

4. Using 'this' keyword as method parameter

Java

// Java code for using 'this'


// keyword as method parameter
class Test
{
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}

// Method that receives 'this' keyword as parameter


void display(Test obj)
{
System.out.println("a = " +obj.a + " b = " + obj.b);
}

// Method that returns current class instance


void get()
{
display(this);
}

public static void main(String[] args)


{
Test object = new Test();
object.get();
}
}

Output:

a = 10 b = 20

5. Using 'this' keyword to invoke current class method

Java

// Java code for using this to invoke current


// class method
class Test {

void display()
{
// calling function show()
this.show();

System.out.println("Inside display function");


}

void show() {
System.out.println("Inside show function");
}

public static void main(String args[]) {


Test t1 = new Test();
t1.display();
}
}

Output:

Inside show function


Inside display function

6. Using 'this' keyword as an argument in the constructor call

Java

// Java code for using this as an argument in constructor


// call
// Class with object of Class B as its data member
class A
{
B obj;

// Parameterized constructor with object of B


// as a parameter
A(B obj)
{
this.obj = obj;

// calling display method of class B


obj.display();
}

class B
{
int x = 5;

// Default Constructor that create a object of A


// with passing this as an argument in the
// constructor
B()
{
A obj = new A(this);
}

// method to show value of x


void display()
{
System.out.println("Value of x in Class B : " + x);
}

public static void main(String[] args) {


B obj = new B();
}
}

Output:
Value of x in Class B : 5

final Keyword in Java

final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to
a variable, a method, or a class. The following are different contexts where final is used.

Final Variables

When a variable is declared with the final keyword, its value can't be modified, essentially, a constant.
This also means that you must initialize a final variable. If the final variable is a reference, this means
that the variable cannot be re-bound to reference another object, but the internal state of the object
pointed by that reference variable can be changed i.e. you can add or remove elements from the final
array or final collection. It is good practice to represent final variables in all uppercase, using
underscore to separate words.
Illustration:

final int THRESHOLD = 5;


// Final variable
final int THRESHOLD;
// Blank final variable
static final double PI = 3.141592653589793;
// Final static variable PI
static final double PI;
// Blank final static variable

Initializing a final Variable

We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final
variable can only be initialized once, either via an initializer or an assignment statement. There are
three ways to initialize a final variable:

1. You can initialize a final variable when it is declared. This approach is the most common. A final variable
is called a blank final variable if it is not initialized while declaration. Below are the two ways to
initialize a blank final variable.
2. A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If
you have more than one constructor in your class then it must be initialized in all of them, otherwise, a
compile-time error will be thrown.
3. A blank final static variable can be initialized inside a static block.

Let us see these two different ways of initializing a final variable:

Java
// Java Program to demonstrate Different
// Ways of Initializing a final Variable
// Main class
class GFG {

// a final variable
// direct initialize
final int THRESHOLD = 5;

// a blank final variable


final int CAPACITY;

// another blank final variable


final int MINIMUM;

// a final static variable PI


// direct initialize
static final double PI = 3.141592653589793;

// a blank final static variable


static final double EULERCONSTANT;

// instance initializer block for


// initializing CAPACITY
{
CAPACITY = 25;
}

// static initializer block for


// initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
}

// constructor for initializing MINIMUM


// Note that if there are more than one
// constructor, you must initialize MINIMUM
// in them also
public GFG()
{
MINIMUM = -1;
}

}
Geeks there was no main method in the above code as it was simply for illustration purposes to get a
better understanding in order to draw conclusions:

Observation 1: When to use a final variable?

The only difference between a normal variable and a final variable is that we can re-assign the value to
a normal variable but we cannot change the value of a final variable once assigned. Hence final variables
must be used only for the values that we want to remain constant throughout the execution of the
program.

Observation 2: Reference final variable?

When a final variable is a reference to an object, then this final variable is called the reference final
variable. For example, a final StringBuffer variable looks defined below as follows:

final StringBuffer sb;


As we all know that a final variable cannot be re-assign. But in the case of a reference final variable, the
internal state of the object pointed by that reference variable can be changed. Note that this is not re-
assigning. This property of final is called non-transitivity. To understand what is meant by the internal
state of the object as shown in the below example as follows:

Example 1:

Java
// Java Program to demonstrate
// Reference of Final Variable

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating sn object of StringBuilder class
// Final reference variable
final StringBuilder sb = new StringBuilder("Geeks");

// Printing the element in StringBuilder object


System.out.println(sb);

// changing internal state of object reference by


// final reference variable sb
sb.append("ForGeeks");

// Again printing the element in StringBuilder


// object after appending above element in it
System.out.println(sb);
}
}

Output
Geeks
GeeksForGeeks

The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with
the final keyword are also called final arrays.

Note: As discussed above, a final variable cannot be reassign, doing it will throw compile-time
error.

Example 2:

Java
// Java Program to Demonstrate Re-assigning
// Final Variable will throw Compile-time Error

// Main class
class GFG {

// Declaring and customly initializing


// static final variable
static final int CAPACITY = 4;

// Main driver method


public static void main(String args[])
{

// Re-assigning final variable


// will throw compile-time error
CAPACITY = 5;
}
}

Output:

Remember: When a final variable is created inside a method/constructor/block, it is called


local final variable, and it must initialize once where it is created. See below program for local
final variable.

Example:

Java
// Java program to demonstrate
// local final variable
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring local final variable
final int i;

// Now initializing it with integer value


i = 20;

// Printing the value on console


System.out.println(i);
}
}

Output
20

Remember the below key points as perceived before moving forward as listed below as follows:

1. Note the difference between C++ const variables and Java final variables. const variables in C++ must be
assigned a value when declared. For final variables in Java, it is not necessary as we see in the above
examples. A final variable can be assigned value later, but only once.
2. final with foreach loop: final with for-each statement is a legal statement.

Example:

Java
// Java Program to demonstrate Final
// with for-each Statement
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Declaring and initializing


// custom integer array
int arr[] = { 1, 2, 3 };

// final with for-each statement


// legal statement
for (final int i : arr)
System.out.print(i + " ");
}
}

Output
1 2 3

Output explanation: Since the "i" variable goes out of scope with each iteration of the loop, it is actually
re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables.

Final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be
extended(inherited).
There are two uses of a final class:

Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example,
all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them.

final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}

Usage 2: The other use of final with classes is to create an immutable class like the
predefined String class. One can not make a class immutable without making it final.

Final Methods

When a method is declared with final keyword, it is called a final method. A final method cannot
be overridden. The Object class does this—a number of its methods are final. We must declare methods
with the final keyword for which we are required to follow the same implementation throughout all the
derived classes.

Illustration: Final keyword with a method


class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}

class B extends A
{
void m1()
{
// Compile-error! We can not override
System.out.println("Illegal!");
}
}

For more examples and behavior of final methods and final classes, please see Using final with
inheritance. Please see the abstract in java article for differences between the final and abstract.
Related Interview Question(Important): Difference between final, finally, and finalize in Java

Java.lang.Math Class in Java | Set 1

Math Class methods helps to perform the numeric operations like square, square root, cube, cube root,
exponential and trigonometric operations

Declaration :
public final class Math
extends Object

What is NaN argument?


A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned
by Double.longBitsToDouble(0x7ff8000000000000L).

Methods of lang.math class :

1. abs() : java.lang.Math.abs() method returns the absolute value of any type of argument passed. This
method can handle all the data types.

 Result is positive zero, if the argument is positive zero or negative zero.


 Result is positive infinity if the argument is infinite.
 Result is NaN, if passed argument is NaN.

Syntax:

public static datatype abs(datatype arg)


Parameters:
arg - the argument whose absolute value we need
Returns:
absolute value of the passed argument.

2. acos() : java.lang.Math.acos() method returns the arc cosine value of the passed argument.
arc cosine is inverse cosine of the argument passed.
acos(arg) = cos-1 of arg

Special Case: Result is NaN, if the argument is NaN or its absolute value is greater than 1.
Syntax:

public static double acos(double a)


Parameters:
a - the argument whose arc cosine value we need.
argument is taken as radian
Returns:
arc cosine value of the argument.

3. toRadians() : java.lang.Math.toRadians(double deg) method converts argument (degree) to


radians.
Note: Math class usually takes radians as an input which is very much different in real life applications
since angles is usually represented in degrees.

Syntax:

public static double toRadians(double deg)


Parameters:
deg - degree angle needs to be in radian.
Returns:
radians equivalent of the degree-argument passed.

Java code explaining abs(), acos(), toRadians() method in lang.Math class.

Java

// Java program explaining lang.Math class methods


// abs(), acos(), toRadians()

import java.lang.*;
public class NewClass
{
public static void main(String[] args)
{
// Declaring the variables
int Vali = -1;
float Valf = .5f;

// Printing the values


System.out.println("Initial value of int : "+Vali);
System.out.println("Initial value of int : "+Valf);

// Use of .abs() method to get the absoluteValue


int Absi = Math.abs(Vali);
float Absf = Math.abs(Valf);

System.out.println("Absolute value of int : "+Absi);


System.out.println("Absolute value of int : "+Absf);
System.out.println("");

// Use of acos() method


// Value greater than 1, so passing NaN
double Acosi = Math.acos(60);
System.out.println("acos value of Acosi : "+Acosi);
double x = Math.PI;

// Use of toRadian() method


x = Math.toRadians(x);
double Acosj = Math.acos(x);
System.out.println("acos value of Acosj : "+Acosj);

}
}

Output :

Initial value of int : -1


Initial value of int : 0.5
Absolute value of int : 1
Absolute value of int : 0.5

acos value of Acosi : NaN


acos value of Acosj : 1.5159376794536454
4. asin() : java.lang.Math.asin() method returns the arc sine value of the method argument passed.
Returned angle is in the range -pi/2 to pi/2.
arc sine is inverse sine of the argument passed.
asin(arg) = sine of arg
-1

Special Case :

 Result is NaN,if the argument is NaN or its absolute value is greater than 1.
 Result is a zero, if the argument is zero.

Syntax:

public static double asin(double arg)


Parameters:
arg - argument passed.
Returns:
arc sine of the argument passed.

5. cbrt() : java.lang.Math.cbrt() method returns the cube root of the passed argument.
Special Point :

 Result is NaN, if the argument is NaN.


 Result is an infinity with the same sign as the argument, if the argument is infinite.
 Result is a zero, if the argument is zero.

Syntax:

public static double cbrt(double arg)


Parameters:
arg - argument passed.
Returns:
cube root of the argument passed

Java code explaining asin(), cbrt() method in lang.Math class.

Java

// Java program explaining lang.Math class methods


// asin(), cbrt()

import java.lang.*;
public class NewClass
{

public static void main(String[] args)


{
int a = 1, b = 8;
int radd = a+b;

// Use of asin() method


// Value greater than 1, so passing NaN
double Asini = Math.asin(radd);
System.out.println("asin value of Asini : " + Asini);
double x = Math.PI;

// Use of toRadian() method


x = Math.toRadians(x);
double Asinj = Math.asin(x);
System.out.println("asin value of Asinj : " + Asinj);
System.out.println("");

// Use of cbrt() method


double cbrtval = Math.cbrt(216);
System.out.println("cube root : " + cbrtval);

}
}

Output :
asin value of Asini : NaN
asin value of Asinj : 0.054858647341251204

cube root : 6.0

6. floor() : java.lang.Math.floor() method returns the floor value of an argument i.e. the closest integer
value which is either less or equal to the passed argument.
eg : 101.23 has floor value = 101

Important point : Same argument is resulted if if passed an NaN or infinite argument.

Syntax:
public static double floor(double arg)
Parameters:
arg - the argument whose floor value we need
Returns:closest possible value that is either less than
or equal to the argument passed
7. hypot() : java.lang.Math.hypot(double p, double b) method returns hypotenuse of a right triangle
on passing the triangle's base and perpendicular as arguments.
hypotenuse = [perpendicular2 + base2]1/2

Important Point :

 If either argument is infinite, then the result is positive infinity.


 If either argument is NaN and neither argument is infinite, then the result is NaN.

Syntax:
public static double hypot(double p, double b)
Parameters:
p - perpendicular of the right triangle
b - base of the right triangle
Returns:
hypotenuse of the right triangle

8. IEEEremainder() : java.lang.Math.IEEERemainder(double d1, double d2) method returns the


remainder value by applying remainder operation on two arguments w.r.t IEEE 754 standard.
Remainder value = d1 - d2 * n
where,
n = closest exact value of d1/d2

Syntax:
public static double IEEEremainder(double d1,double d2)
Parameters:
d1 - dividend
d2 - divisor
Returns:
remainder when f1(dividend) is divided by(divisor)

9. log() : java.lang.Math.log() method returns the logarithmic value of the passed argument.

Syntax:
public static double log(double arg)
Parameters:
arg - argument passed.
Returns:
logarithmic value of the argument passed.

Java code explaining floor(), hypot(), IEEEremainder(), log() method in lang.Math class.

Java

// Java program explaining lang.MATH class methods


// floor(), hypot(), IEEEremainder(), log()

import java.lang.*;
public class NewClass
{

public static void main(String[] args)


{
// Use of floor method
double f1 = 30.56, f2 = -56.34;
f1 =Math.floor(f1);
System.out.println("Floor value of f1 : "+f1);

f2 =Math.floor(f2);
System.out.println("Floor value of f2 : "+f2);
System.out.println("");

// Use of hypot() method


double p = 12, b = -5;
double h = Math.hypot(p, b);
System.out.println("Hypotenuse : "+h);
System.out.println("");

// Use of IEEEremainder() method


double d1 = 105, d2 = 2;
double r = Math.IEEEremainder(d1,d2);
System.out.println("Remainder : "+r);
System.out.println("");

// Use of log() method


double l = 10;
l = Math.log(l);
System.out.println("Log value of 10 : "+l);

}
}

Output :

Floor value of f1 : 30.0


Floor value of f2 : -57.0

Hypotenuse : 13.0
Remainder : 1.0

Log value of 10 : 2.302585092994046

10. ceil() : java.lang.Math.ceil(double a) method returns the smallest possible value which is either
greater or equal to the argument passed. The returned value is a mathematical integer.

 Result is same, if the returned value is already a mathematical integer.


 Result is same, if the passed argument is NaN or infinite or zero.
 Result is negative zero, if the passed argument is less than zero but greater than -1.0

Syntax:

public static double ceil(double arg)


Parameters:
arg - the argument value
Returns:
smallest possible value(mathematical integer)
which is either greater or equal to the argument passed

11. atan() : java.lang.Math.atan() method returns returns the arc tangent of the method argument
value. The returned angle is in the range -pi/2 through pi/2.
arc tan is inverse tan of the argument passed.
atan(arg) = tan inverse of arg

Special Case :

 Result is NaN, if the passed argument is NaN or its absolute value is > 1.
 Result is zero, if argument is zero.

Syntax:

public static double atan(double a)


Parameters:
a - the argument whose arc tangent value we need.
argument is taken as radian
Returns:
arc tan value of the argument.

12. copySign() : java.lang.Math.copySign() method returns first floating-point argument but having
the sign of second argument.

Syntax:

public static double copySign(double m, double s)


or
public static float copySign(float m, float s)
Parameters:
m - magnitude
s - sign
Returns:
returns first argument with sign of second floating-point argument.

Java code explaining atan(), ceil(), copySign() method in lang.Math class.

Java

// Java program explaining lang.Math class methods


// atan(), ceil(), copySign()

import java.math.*;
public class NewClass
{
public static void main(String[] args)
{
// Use of atan() method
double Atani = Math.atan(0);
System.out.println("atan value of Atani : "+Atani);
double x = Math.PI/2;

// Use of toRadian() method


x = Math.toRadians(x);
double Atanj = Math.atan(x);
System.out.println("atan value of Atanj : "+Atanj);
System.out.println("");

// Use of ceil() method


double val = 15.34 ,ceilval;
ceilval = Math.ceil(val);
System.out.println("ceil value of val : "+ceilval);
System.out.println("");

double dblMag = val;


double dblSign1 = 3;
double dblSign2 = -3;

// Use of copySign() method


double result1 = Math.copySign(dblMag,dblSign1);
System.out.println("copySign1 : "+result1);

double result2 = Math.copySign(dblMag,dblSign2);


System.out.println("copySign2 : "+result2);

}
}

Output :

atan value of Atani : 0.0


atan value of Atanj : 0.0274087022410345

ceil value of val : 16.0

copySign1 : 15.34
copySign2 : -15.34

Java.lang.Math Class in Java | Set 2


 Difficulty Level : Medium
 Last Updated : 01 Sep, 2021

 Read

 Discuss

 Courses

 Practice

 Video

Java.lang.Math Class in Java | Set 1


More Methods:
13. cosh() : java.lang.Math.cosh() method returns the hyperbolic cosine of the
argument passed.
Special cases :
 Result is NaN, if argument is NaN.
 Result is 1.0, if the argument is zero.
 Result is +ve infinity, if argument is infinite.
Syntax:
public static double cosh(double arg)
Parameters:
arg - The number whose hyperbolic cosine is to be returned.
Returns:
the hyperbolic cosine of the argument arg.
14. decrementExact() : java.lang.Math.decrementExact() method decrements the
value of passed argument by one.
Syntax:
15. public static int decrementExact(int arg)
16. or
17. public static long decrementExact(long arg)
18. Parameters:
19. arg - argument passed.
20. Returns:
21. return argument decremented by one.
22. Throws:
23. Exception if the result overflows long or int datatype, according
to the
24. argumented data type.
25. exp() : java.lang.Math.exp(double arg) method returns the Euler’s number raised
to the power of double argument.
Important cases:
 Result is NaN, if argument is NaN.
 Result is +ve infinity, if the argument is +ve infinity.
 Result is +ve zero, if argument is -ve infinity.
Syntax:
public static double exp(double arg)
Parameters:
arg - argument passed.
Returns:
Euler’s number raised to the power of passed argument
Java code explaining exp(), decrementExact(), cosh() method in lang.Math class.
// Java program explaining lang.Math class methods

// exp(), decrementExact(), cosh()

import java.math.*;

public class NewClass

public static void main(String[] args)

// Use of cosh() method

double value = 2;

double coshValue = Math.cosh(value);

System.out.println("Hyperbolic Cosine of " + coshValue);

System.out.println("");
// Use of decrementExact() method

int result = Math.decrementExact(3051);

System.out.println("Use of decrementExact() : " + result);

System.out.println("");

// Use of exp() method

// declare the exponent to be used

double exponent = 34;

// raise e to exponent declared

double expVal = Math.exp(exponent);

System.out.println("Value of exp : "+ expVal);

Output:
Using addExact() : 9

acos value of Asini : NaN


acos value of Asinj : 0.054858647341251204

cube root : 6.0


26. incrementExact() : java.lang.Math.incrementExact() method returns the
argument by incrementing it’s value.
27. Syntax:
28. public static int incrementExact(int arg)
29. or
30. public static long incrementExact(long arg)
31. Parameters:
32. arg - the argument
33. Returns:
incremented value of the argument
34. log10() : java.lang.Math.log10() method returns the base10 logarithmic value of
the passed argument.
35. Syntax:
36. public static double log(double arg)
37. Parameters:
38. arg - argument passed.
39. Returns:
40. base10 logarithmic value of the argument passed.
41. pow() : java.lang.Math.pow(double b, double e) method returns the value as be
42. Syntax:
43. public static double pow(double b,double e)
44. Parameters:
45. b : base
46. e : exponent
47. Returns:
48. value as baseexponent
JAVA code explaining incrementExact(), log10(), pow() method in lang.Math class.
// Java program explaining lang.MATH class methods

// incrementExact(), log10(), pow()

import java.lang.*;

public class NewClass

public static void main(String[] args)

// Use of incrementExact() method

int f1 = 30, f2 = -56;

f1 =Math.incrementExact(f1);

System.out.println("Incremented value of f1 : "+f1);

f2 =Math.incrementExact(f2);

System.out.println("Incremented value of f2 : "+f2);

System.out.println("");

// Use of log10() method

double value = 10;

double logValue = Math.log10(value);

System.out.println("Log10 value of 10 : "+logValue);

System.out.println("");

// Use of pow() method

double b = 10, e = 2;

double power = Math.pow(b,e);


System.out.println("Use of pow() : "+power);

Output :
Incremented value of f1 : 31
Incremented value of f2 : -55

Log10 value of 10 : 1.0

Use of pow() : 100.0


49. signum() : java.lang.Math.signum() method returns the signum value of the
argument passed.
50. -1 if x < 0
51. signum fun(x) = 0 if x = 0
52. 1 if x > 0
Note:Result is NaN, if passed the argument is NaN.;
Syntax:
public static double signum(double x)
or
public static float signum(float x)
Parameters:
x - the argument whose signum value we need
Returns:
signum value of x
53. round() : java.lang.Math.round() method round off the passed argument upto
closest decimal places.
Note: Result is 0, if the argument is NaN.
Syntax:
54. public static long round(long arg)
55. or
56. public static double round(double arg)
57. Parameters:
58. arg - argument needs to round off
59. Returns:
60. round off value of the argument
61. max() : java.lang.Math.max(double v1, double v2) method returns the greater
value out of the two passed argument values.
This method just compares using magnitude without considering any sign.
Syntax:
62. public static double max(double v1, double v2)
63. Parameters:
64. v1 - first value
65. v2 - second value
66. Returns:
67. v1 or v2 based on which number is greater.
68. It can return either of the two if v1 = v2.
Java code explaining signum(), round(), max() method in lang.Math class.
// Java code explaining the lang.Math Class methods

// signum(), round(), max()

import java.lang.*;

public class NewClass

public static void main(String args[])

// Use of signum() method

double x = 10.4556, y = -23.34789;

double signm = Math.signum(x);

System.out.println("Signum of 10.45 = "+signm);

signm = Math.signum(y);

System.out.println("Signum of -23.34 = "+signm);

System.out.println("");

// Use of round() method

double r1 = Math.round(x);

System.out.println("Round off 10.4556 = "+r1);

double r2 = Math.round(y);

System.out.println("Round off 23.34789 = "+r2);

System.out.println("");

// Use of max() method on r1 and r2

double m = Math.max(r1, r2);

System.out.println("Max b/w r1 and r2 = "+r2);


}

Output:
Signum of 10.45 = 1.0
Signum of -23.34 = -1.0

Round off 10.4556 = 10.0


Round off 23.34789 = -23.0

Max b/w r1 and r2 = -23.0


69. log1p() : java.lang.Math.log1p() method returns natural log of (passed argument +
1).
Syntax:
70. public static double log1p(double arg)
71. Parameters:
72. arg - the argument
73. Returns:
74. log of (argument + 1).
75. This result is within 1 unit in the last place of exact result.
76. ulp() : java.lang.Math.ulp() method returns Unit of least precision(ulp) ie. the
least distance between two floating point numbers.
Here, it is the least distance b/w the argument and next larger value.
Syntax:
77. public static double ulp(double arg)
78. or
79. public static float ulp(float arg)
80. Parameters:
81. arg - argument passed.
82. Returns:
83. least distance b/w the argument and next larger value.
Java code explaining ulp(), log1p() method in lang.Math class.
// Java code explaining the lang.Math Class methods

// ulp(), log1p()

import java.lang.*;

public class NewClass

public static void main(String args[])


{

// Use of ulp() method

double x = 34.652, y = -23.34789;

double u = Math.ulp(x);

System.out.println("ulp of 34.652 : "+u);

u = Math.ulp(y);

System.out.println("ulp of -23.34789 : "+u);

System.out.println("");

// Use of log() method

double l = 99;

double l1 = Math.log1p(l);

System.out.println("Log of (1 + 99) : "+l1);

l1 = Math.log(100);

System.out.println("Log of 100 : "+l1);

Output:
ulp of 34.652 : 7.105427357601002E-15
ulp of -23.34789 : 3.552713678800501E-15

Log of (1 + 99) : 4.605170185988092


Log of 100 : 4.605170185988092

Math pow() method in Java with Example

The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This
function accepts two parameters and returns the value of first parameter raised to the second
parameter. There are some special cases as listed below:

 If the second parameter is positive or negative zero then the result will be 1.0.
 If the second parameter is 1.0 then the result will be same as that of the first parameter.
 If the second parameter is NaN then the result will also be NaN.
Syntax:

public static double pow(double a, double b)


Parameter:
a : this parameter is the base
b : this parameter is the exponent.
Return :
This method returns ab.

Example 1: To show working of java.lang.Math.pow() method.


Java

// Java program to demonstrate working


// of java.lang.Math.pow() method

import java.lang.Math;

class Gfg {

// driver code
public static void main(String args[])
{
double a = 30;
double b = 2;
System.out.println(Math.pow(a, b));

a = 3;
b = 4;
System.out.println(Math.pow(a, b));

a = 2;
b = 6;
System.out.println(Math.pow(a, b));
}
}
Output:

900.0
81.0
64.0

Example 2: To show working of java.lang.Math.pow() method when argument is NaN.


Java

// Java program to demonstrate working


// of java.lang.Math.pow() method
import java.lang.Math; // importing java.lang package

public class GFG {


public static void main(String[] args)
{

double nan = Double.NaN;


double result;

// Here second argument is NaN,


// output will be NaN
result = Math.pow(2, nan);
System.out.println(result);

// Here second argument is zero


result = Math.pow(1254, 0);
System.out.println(result);

// Here second argument is one


result = Math.pow(5, 1);
System.out.println(result);
}
}
Output:

NaN
1.0
5.0

BigInteger Class in Java

BigInteger class is used for the mathematical operation which involves very big integer calculations that
are outside the limit of all available primitive data types.

In this way, BigInteger class is very handy to use because of its large method library and it is also used
a lot in competitive programming.
Now below is given a list of simple statements in primitive arithmetic and its analogous statement in
terms of BigInteger objects.

Example:

int a, b;
BigInteger A, B;

Initialization is as follows:

a = 54;
b = 23;
A = BigInteger.valueOf(54);
B = BigInteger.valueOf(37);

And for Integers available as strings you can initialize them as follows:

A = new BigInteger(“54”);
B = new BigInteger(“123456789123456789”);

Some constants are also defined in BigInteger class for ease of initialization as follows:

A = BigInteger.ONE;
// Other than this, available constant are BigInteger.ZERO
// and BigInteger.TEN

Mathematical operations are as follows:

int c = a + b;
BigInteger C = A.add(B);

Other similar functions are subtract(), multiply(), divide(), remainder(), but all these functions take
BigInteger as their argument so if we want this operation with integers or string convert them to
BigInteger before passing them to functions as shown below:
String str = “123456789”;
BigInteger C = A.add(new BigInteger(str));
int val = 123456789;
BigInteger C = A.add(BigInteger.valueOf(val));

Extraction of value from BigInteger is as follows:

int x = A.intValue(); // value should be in limit of int x


long y = A.longValue(); // value should be in limit of long y
String z = A.toString();

Comparison

if (a < b) {} // For primitive int


if (A.compareTo(B) < 0) {} // For BigInteger

Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values. For equality
we can also use:

if (A.equals(B)) {} // A is equal to B

Methods of BigInteger Class

Method Action Performed

add(BigInteger val) Returns a BigInteger whose value is (this + val).

Returns a BigInteger whose value is the absolute value of this


abs()
BigInteger.

and(BigInteger val) Returns a BigInteger whose value is (this & val).

andNot(BigInteger val) Returns a BigInteger whose value is (this & ~val).

Returns the number of bits in the two's complement


bitCount()
representation of this BigInteger that differ from its sign bit.
Method Action Performed

Returns the number of bits in the minimal two's-complement


bitLength()
representation of this BigInteger, excluding a sign bit.

Converts this BigInteger to a byte, checking for lost


byteValueExact()
information.

Returns a BigInteger whose value is equivalent to this


clearBit(int n)
BigInteger with the designated bit cleared.

compareTo(BigInteger val) Compares this BigInteger with the specified BigInteger.

divide(BigInteger val) Returns a BigInteger whose value is (this / val).

Returns an array of two BigIntegers containing (this / val)


divideAndRemainder(BigInteger val)
followed by (this % val).

doubleValue() Converts this BigInteger to a double.

Compares this BigInteger with the specified Object for


equals(Object x)
equality.

Returns a BigInteger whose value is equivalent to this


flipBit(int n)
BigInteger with the designated bit flipped.

floatValue() Converts this BigInteger to a float.


Method Action Performed

Returns a BigInteger whose value is the greatest common


gcd(BigInteger val)
divisor of abs(this) and abs(val).

Returns the index of the rightmost (lowest-order) one bit in


getLowestSetBit() this BigInteger (the number of zero bits to the right of the
rightmost one bit).

hashCode() Returns the hash code for this BigInteger.

intValue() Converts this BigInteger to an int.

Converts this BigInteger to an int, checking for lost


intValueExact()
information.

Returns true if this BigInteger is probably prime, false if it's


isProbablePrime(int certainty)
definitely composite.

longValue() Converts this BigInteger to a long.

Converts this BigInteger to a long, checking for lost


longValueExact()
information.

max(BigInteger val) Returns the maximum of this BigInteger and val.

min(BigInteger val) Returns the minimum of this BigInteger and val.


Method Action Performed

mod(BigInteger m Returns a BigInteger whose value is (this mod m).

modInverse(BigInteger m) Returns a BigInteger whose value is (this-1 mod m).

modPow(BigInteger exponent,
Returns a BigInteger whose value is (thisexponent mod m).
BigInteger m

multiply(BigInteger val) Returns a BigInteger whose value is (this * val).

negate() Returns a BigInteger whose value is (-this).

Returns the first integer greater than this BigInteger that is


nextProbablePrime()
probably prime.

not() Returns a BigInteger whose value is (~this).

or(BigInteger val) Returns a BigInteger whose value is (this | val).

pow(int exponent) Returns a BigInteger whose value is (thisexponent).

probablePrime(int bitLength, Returns a positive BigInteger that is probably prime, with the
Random rnd) specified bitLength.

remainder(BigInteger val) Returns a BigInteger whose value is (this % val).


Method Action Performed

Returns a BigInteger whose value is equivalent to this


setBit(int n)
BigInteger with the designated bit set.

shiftLeft(int n) Returns a BigInteger whose value is (this << n).

shiftRight(int n) Returns a BigInteger whose value is (this >> n).

Converts this BigInteger to a short, checking for lost


shortValueExact()
information.

signum() Returns the signum function of this BigInteger.

sqrt() Returns the integer square root of this BigInteger.

Returns an array of two BigIntegers containing the integer


sqrtAndRemainder()
square root s of this and its remainder this - s*s, respectively.

subtract(BigInteger val) Returns a BigInteger whose value is (this - val).

testBit(int n) Returns true if and only if the designated bit is set.

Returns a byte array containing the two's-complement


toByteArray()
representation of this BigInteger.

toString() Returns the decimal String representation of this BigInteger.


Method Action Performed

Returns the string representation of this BigInteger in the


toString(int radix)
given radix.

Returns a BigInteger whose value is equal to that of the


valueOf(long val)
specified long.

xor(BigInteger val) Returns a BigInteger whose value is (this ^ val).

Illustration:

Factorial of 100 contains 158 digits in it so we can’t store it in any primitive data type available. We can
store as large an Integer as we want in it. There is no theoretical limit on the upper bound of the range
because memory is allocated dynamically but practically as memory is limited you can store a number
that has Integer.MAX_VALUE number of bits in it which should be sufficient to store mostly all large
values.

Example:

Java
// Java program to find large factorials using BigInteger
import java.math.BigInteger;
import java.util.Scanner;

public class Example


{
// Returns Factorial of N
static BigInteger factorial(int N)
{
// Initialize result
BigInteger f = new BigInteger("1"); // Or BigInteger.ONE

// Multiply f with 2, 3, ...N


for (int i = 2; i <= N; i++)
f = f.multiply(BigInteger.valueOf(i));

return f;
}
// Driver method
public static void main(String args[]) throws Exception
{
int N = 20;
System.out.println(factorial(N));
}
}

Output:

2432902008176640000

Tip: If we have to write above program in C++, that would be too large and complex, we can
look at Factorial of Large Number.
So after the above knowledge of the function of BigInteger class, we can solve many complex problems
easily, but remember as BigInteger class internally uses an array of integers for processing, the
operation on an object of BigIntegers are not as fast as on primitives that are add function on BigIntgers
doesn’t take the constant time it takes time proportional to the length of BigInteger, so the complexity
of program will change accordingly.

BigInteger mod() Method in Java

The java.math.BigInteger.mod(BigInteger big) method returns a BigInteger whose value is equal to


(this BigInteger modfunction big(BigInteger passed as parameter)).In other words we can say that this
method returns the value after performing (this % big) step.The mod operation finds the remainder
after division of this BigInteger by another BigInteger passed as parameter.

java.math.BigInteger.mod(BigInteger big) and java.math.BigInteger.remainder(BigInteger val) both


function finds remainder but mod operation always returns a non-negative BigInteger.

Syntax:

public BigInteger mod(BigInteger big)

Parameter: The function accepts a single mandatory parameter big which specifies the BigInteger
Object by which we want to divide this bigInteger object.

Return Value: The method returns the BigInteger which is equal to this BigInteger mod big(BigInteger
passed as parameter).

Exception: The method throws ArithmeticException when big ≤ 0

Examples:

Input: BigInteger1=321456, BigInteger2=31711


Output: 4346
Explanation: BigInteger1.mod(BigInteger2)=4346. The divide operation between
321456 and 31711 returns 4346 as remainder.

Input: BigInteger1=59185482345, BigInteger2=59185482345


Output: 0
Explanation: BigInteger1.mod(BigInteger2)=0. The divide operation between
59185482345 and 59185482345 returns 0 as remainder.

Below programs illustrate mod() method of BigInteger class:

Example 1:

Java

// Java program to demonstrate mod() method of BigInteger

import java.math.BigInteger;

public class GFG {

public static void main(String[] args)


{

// Creating 2 BigInteger objects


BigInteger b1, b2;

b1 = new BigInteger("321456");
b2 = new BigInteger("31711");

// apply mod() method


BigInteger result = b1.mod(b2);

// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}

Output:
Result of mod operation between 321456 and 31711 equal to 4346

Example 2: When both are equal in value.


Java

// Java program to demonstrate mod() method of BigInteger

import java.math.BigInteger;

public class GFG {

public static void main(String[] args)


{

// Creating 2 BigInteger objects


BigInteger b1, b2;

b1 = new BigInteger("3515219485");
b2 = new BigInteger("3515219485");

// apply mod() method


BigInteger result = b1.mod(b2);

// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}

Output:

Result of mod operation between 3515219485 and 3515219485 equal to 0

Example 3: Program showing exception when BigInteger passed as a parameter is less than zero.

Java
// Java program to demonstrate mod() method of BigInteger

import java.math.BigInteger;

public class GFG {

public static void main(String[] args)


{

// Creating 2 BigInteger objects


BigInteger b1, b2;

b1 = new BigInteger("3515219485");
b2 = new BigInteger("-1711");

// apply mod() method


BigInteger result = b1.mod(b2);

// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
Output:

Exception in thread "main" java.lang.ArithmeticException: BigInteger: modulus not p


ositive
at java.math.BigInteger.mod(BigInteger.java:2458)
at GFG.main(GFG.java:17)

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#mod(java.math.
BigInteger)
Articles (6)

LinkedList in Java

Wrapper Classes in Java

Stack Class in Java

Queue Interface In Java

PriorityQueue in Java

ArrayList in Java

LinkedList in Java

Linked List is a part of the Collection framework present in java.util package. This class is an
implementation of the LinkedList data structure which is a linear data structure where the elements
are not stored in contiguous locations and every element is a separate object with a data part and
address part. The elements are linked using pointers and addresses. Each element is known as a node.
Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. It also
has a few disadvantages like the nodes cannot be accessed directly instead we need to start from the
head and follow through the link to reach a node we wish to access.

How Does LinkedList work Internally?

Since a LinkedList acts as a dynamic array and we do not have to specify the size while creating it, the
size of the list automatically increases when we dynamically add and remove items. And also, the
elements are not stored in a continuous fashion. Therefore, there is no need to increase the size.
Internally, the LinkedList is implemented using the doubly linked list data structure. The main
difference between a normal linked list and a doubly LinkedList is that a doubly linked list contains an
extra pointer, typically called the previous pointer, together with the next pointer and data which are
there in the singly linked list.

Constructors in the LinkedList


In order to create a LinkedList, we need to create an object of the LinkedList class. The LinkedList class
consists of various constructors that allow the possible creation of the list. The following are the
constructors available in this class:

1. LinkedList(): This constructor is used to create an empty linked list. If we wish to create an empty
LinkedList with the name ll, then, it can be created as:
LinkedList ll = new LinkedList();

2. LinkedList(Collection C): This constructor is used to create an ordered list that contains all the
elements of a specified collection, as returned by the collection's iterator. If we wish to create a
LinkedList with the name ll, then, it can be created as:

LinkedList ll = new LinkedList(C);

Methods for Java LinkedList

Method Description

This method Inserts the specified element at the specified position in this
add(int index, E element)
list.

add(E e) This method Appends the specified element to the end of this list.

addAll(int index, Collection<E> This method Inserts all of the elements in the specified collection into this
c) list, starting at the specified position.

This method Appends all of the elements in the specified collection to the
addAll(Collection<E> c) end of this list, in the order that they are returned by the specified
collection's iterator.

addFirst(E e) This method Inserts the specified element at the beginning of this list.

addLast(E e) This method Appends the specified element to the end of this list.

clear() This method removes all of the elements from this list.

clone() This method returns a shallow copy of this LinkedList.

contains(Object o) This method returns true if this list contains the specified element.
Method Description

This method returns an iterator over the elements in this deque in reverse
descendingIterator()
sequential order.

This method retrieves but does not remove, the head (first element) of this
element()
list.

get(int index) This method returns the element at the specified position in this list.

getFirst() This method returns the first element in this list.

getLast() This method returns the last element in this list.

This method returns the index of the first occurrence of the specified
indexOf(Object o)
element in this list, or -1 if this list does not contain the element.

This method returns the index of the last occurrence of the specified
lastIndexOf(Object o)
element in this list, or -1 if this list does not contain the element.

This method returns a list-iterator of the elements in this list (in proper
listIterator(int index)
sequence), starting at the specified position in the list.

This method Adds the specified element as the tail (last element) of this
offer(E e)
list.

offerFirst(E e) This method Inserts the specified element at the front of this list.
Method Description

offerLast(E e) This method Inserts the specified element at the end of this list.

This method retrieves but does not remove, the head (first element) of this
peek()
list.

This method retrieves, but does not remove, the first element of this list,
peekFirst()
or returns null if this list is empty.

This method retrieves, but does not remove, the last element of this list, or
peekLast()
returns null if this list is empty.

poll() This method retrieves and removes the head (first element) of this list.

This method retrieves and removes the first element of this list, or returns
pollFirst()
null if this list is empty.

This method retrieves and removes the last element of this list, or returns
pollLast()
null if this list is empty.

pop() This method Pops an element from the stack represented by this list.

push(E e) This method pushes an element onto the stack represented by this list.

remove() This method retrieves and removes the head (first element) of this list.
Method Description

remove(int index) This method removes the element at the specified position in this list.

This method removes the first occurrence of the specified element from
remove(Object o)
this list if it is present.

removeFirst() This method removes and returns the first element from this list.

removeFirstOccurrence(Object This method removes the first occurrence of the specified element in this
o) list (when traversing the list from head to tail).

removeLast() This method removes and returns the last element from this list.

removeLastOccurrence(Object This method removes the last occurrence of the specified element in this
o) list (when traversing the list from head to tail).

This method replaces the element at the specified position in this list with
set(int index, E element)
the specified element.

size() This method returns the number of elements in this list.

This method creates a late-binding and fail-fast Spliterator over the


spliterator()
elements in this list.

This method returns an array containing all of the elements in this list in
toArray()
proper sequence (from first to last element).
Method Description

This method returns an array containing all of the elements in this list in
toArray(T[] a) proper sequence (from first to last element); the runtime type of the
returned array is that of the specified array.

This method returns a string containing all of the elements in this list in
toString() proper sequence (from first to the last element), each element is
separated by commas and the String is enclosed in square brackets.

Example:

Java
// Java Program to Demonstrate
// Implementation of LinkedList
// class

// Importing required classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String args[])
{
// Creating object of the
// class linked list
LinkedList<String> ll = new LinkedList<String>();

// Adding elements to the linked list


ll.add("A");
ll.add("B");
ll.addLast("C");
ll.addFirst("D");
ll.add(2, "E");

System.out.println(ll);

ll.remove("B");
ll.remove(3);
ll.removeFirst();
ll.removeLast();

System.out.println(ll);
}
}

Output:

[D, A, E, B, C]
[A]

In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the
classes that implement the list interface. A separate functionality is implemented in each of the
mentioned classes. They are:
1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend
this AbstractList Class and implement only the get() and the size() methods.
2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList
in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.

Performing Various Operations on LinkedList

1. Adding elements
2. Updating elements
3. Removing elements
4. Iterating over elements

Let us see how to perform some basic operations on LinkedList to understand it better as follows:

Operation 1: Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to
perform multiple operations based on different parameters. They are:

 add(Object): This method is used to add an element at the end of the LinkedList.
 add(int index, Object): This method is used to add an element at a specific index in the LinkedList.

Example:

Java
// Java program to add elements
// to a LinkedList

import java.util.*;

public class GFG {

public static void main(String args[])


{
LinkedList<String> ll = new LinkedList<>();

ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "For");

System.out.println(ll);
}
}

Output:

[Geeks, For, Geeks]

Operation 2: Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since
a LinkedList is indexed, the element which we wish to change is referenced by the index of the element.
Therefore, this method takes an index and the updated element which needs to be inserted at that index.

Example:

Java
// Java program to change elements
// in a LinkedList

import java.util.*;

public class GFG {

public static void main(String args[])


{
LinkedList<String> ll = new LinkedList<>();

ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "Geeks");

System.out.println("Initial LinkedList " + ll);

ll.set(1, "For");

System.out.println("Updated LinkedList " + ll);


}
}
Output:

Initial LinkedList [Geeks, Geeks, Geeks]


Updated LinkedList [Geeks, For, Geeks]

Operation 3: Removing Elements

In order to remove an element from a LinkedList, we can use the remove() method. This method is
overloaded to perform multiple operations based on different parameters. They are:

 remove(Object): This method is used to simply remove an object from the LinkedList. If there are
multiple such objects, then the first occurrence of the object is removed.
 remove(int index): Since a LinkedList is indexed, this method takes an integer value which simply
removes the element present at that specific index in the LinkedList. After removing the element and the
indices of elements are updated so do the object of LinkedList is updated giving a new List after the
deletion of element/s.

Example:

Java
// Java program to remove elements
// in a LinkedList

import java.util.*;

public class GFG {

public static void main(String args[])


{
LinkedList<String> ll = new LinkedList<>();

ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "For");

System.out.println(
"Initial LinkedList " + ll);

ll.remove(1);

System.out.println(
"After the Index Removal " + ll);
ll.remove("Geeks");

System.out.println(
"After the Object Removal " + ll);
}
}

Output:

Initial LinkedList [Geeks, For, Geeks]


After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]

Operation 4: Iterating the LinkedList

There are multiple ways to iterate through LinkedList. The most famous ways are by using the basic for
loop in combination with a get() method to get the element at a specific index and the advanced for-
loop.

Example:

Java
// Java program to iterate the elements
// in an LinkedList

import java.util.*;

public class GFG {

public static void main(String args[])


{
LinkedList<String> ll
= new LinkedList<>();

ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "For");

// Using the Get method and the


// for loop
for (int i = 0; i < ll.size(); i++) {
System.out.print(ll.get(i) + " ");
}

System.out.println();

// Using the for each loop


for (String str : ll)
System.out.print(str + " ");
}
}

Output:

Geeks For Geeks


Geeks For Geeks

Wrapper Classes in Java

A Wrapper class is a class whose object wraps or contains primitive data types. When we create an
object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.

Need of Wrapper Classes

1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

Primitive Data types and their Corresponding Wrapper class


Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper
classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to
Double etc.
Example:

Java

// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object conversion


Character a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
Output:
25

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper
class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to
int, Long to long, Double to double, etc.

Java

// Java program to demonstrate Unboxing


import java.util.ArrayList;

class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive conversion


char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


arrayList.add(24);

// unboxing because get method returns an Integer object


int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}
Output:
24

Implementation

Java
// Java program to demonstrate Wrapping and UnWrapping
// in Java Classes
class WrappingUnwrapping
{
public static void main(String args[])
{
// byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);

// int data type


int b = 10;

//wrapping around Integer object


Integer intobj = new Integer(b);

// float data type


float c = 18.6f;

// wrapping around Float object


Float floatobj = new Float(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);

// char data type


char e='a';

// wrapping around Character object


Character charobj=e;

// printing the values from objects


System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object byteobj: " + byteobj);
System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);
System.out.println("Character object charobj: " + charobj);

// objects to data types (retrieving data types from objects)


// unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
System.out.println("char value, cv: " + cv);
}
}
Output:
Values of Wrapper objects (printing as objects)
Byte object byteobj: 1
Integer object intobj: 10
Float object floatobj: 18.6
Double object doubleobj: 250.5
Character object charobj: a
Unwrapped values (printing as data types)
byte value, bv: 1
int value, iv: 10
float value, fv: 18.6
double value, dv: 250.5
char value, cv: a

Stack Class in Java

Java Collection framework provides a Stack class that models and implements a Stack data structure.
The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop
operations, the class provides three more functions of empty, search, and peek. The class can also be
said to extend Vector and treats the class as a stack with the five mentioned functions. The class can
also be referred to as the subclass of Vector.

The below diagram shows the hierarchy of the Stack class:

The class supports one default constructor Stack() which is used to create an empty stack.

Declaration:
public class Stack<E> extends Vector<E>

All Implemented Interfaces:

 Serializable: It is a marker interface that classes must implement if they are to be serialized and
deserialized.
 Cloneable: This is an interface in Java which needs to be implemented by a class to allow its
objects to be cloned.
 Iterable<E>: This interface represents a collection of objects which is iterable — meaning which
can be iterated.
 Collection<E>: A Collection represents a group of objects known as its elements. The Collection
interface is used to pass around collections of objects where maximum generality is desired.
 List<E>: The List interface provides a way to store the ordered collection. It is a child interface
of Collection.
 RandomAccess: This is a marker interface used by List implementations to indicate that they
support fast (generally constant time) random access.

How to Create a Stack?

In order to create a stack, we must import java.util.stack package and use the Stack() constructor of
this class. The below example creates an empty Stack.
Stack<E> stack = new Stack<E>();
Here E is the type of Object.

Example:

Java
// Java code for stack implementation

import java.io.*;
import java.util.*;

class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}

// Popping element from the top of the stack


static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");

for(int i = 0; i < 5; i++)


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}

// Displaying element on the top of the stack


static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}

// Searching element in the stack


static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);

if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
}

public static void main (String[] args)


{
Stack<Integer> stack = new Stack<Integer>();

stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}

Output:

Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

Performing various operations on Stack class

1. Adding Elements: In order to add an element to the stack, we can use the push() method.
This push() operation place the element at the top of the stack.
Java
// Java program to add the
// elements in the stack
import java.io.*;
import java.util.*;

class StackDemo {

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

// Default initialization of Stack


Stack stack1 = new Stack();

// Initialization of Stack
// using Generics
Stack<String> stack2 = new Stack<String>();

// pushing the elements


stack1.push(4);
stack1.push("All");
stack1.push("Geeks");

stack2.push("Geeks");
stack2.push("For");
stack2.push("Geeks");

// Printing the Stack Elements


System.out.println(stack1);
System.out.println(stack2);
}
}

Output:
[4, All, Geeks]
[Geeks, For, Geeks]

2. Accessing the Element: To retrieve or fetch the first element of the Stack or the element present at
the top of the Stack, we can use peek() method. The element retrieved does not get deleted or removed
from the Stack.

Java
// Java program to demonstrate the accessing
// of the elements from the stack
import java.util.*;
import java.io.*;

public class StackDemo {

// Main Method
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();

// Use push() to add elements into the Stack


stack.push("Welcome");
stack.push("To");
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");

// Displaying the Stack


System.out.println("Initial Stack: " + stack);

// Fetching the element at the head of the Stack


System.out.println("The element at the top of the"
+ " stack is: " + stack.peek());

// Displaying the Stack after the Operation


System.out.println("Final Stack: " + stack);
}
}

Output:

Initial Stack: [Welcome, To, Geeks, For, Geeks]


The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

3. Removing Elements: To pop an element from the stack, we can use the pop() method. The element
is popped from the top of the stack and is removed from the same.

Java
// Java program to demonstrate the removing
// of the elements from the stack
import java.util.*;
import java.io.*;

public class StackDemo {


public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack = new Stack<Integer>();

// Use add() method to add elements


stack.push(10);
stack.push(15);
stack.push(30);
stack.push(20);
stack.push(5);

// Displaying the Stack


System.out.println("Initial Stack: " + stack);

// Removing elements using pop() method


System.out.println("Popped element: "
+ stack.pop());
System.out.println("Popped element: "
+ stack.pop());

// Displaying the Stack after pop operation


System.out.println("Stack after pop operation "
+ stack);
}
}

Output:

Initial Stack: [10, 15, 30, 20, 5]


Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

Methods in Stack Class

METHOD DESCRIPTION

empty() It returns true if nothing is on the top of the stack. Else, returns false.

peek() Returns the element on the top of the stack, but does not remove it.

Removes and returns the top element of the stack. An


pop() 'EmptyStackException'

An exception is thrown if we call pop() when the invoking stack is empty.

push(Object element) Pushes an element on the top of the stack.

It determines whether an object exists in the stack. If the element is found,


search(Object
element) It returns the position of the element from the top of the stack. Else, it
returns -1.

Methods inherited from class java.util.Vector

METHOD DESCRIPTION
add(Object obj) Appends the specified element to the end of this Vector.

add(int index, Object obj) Inserts the specified element at the specified position in this Vector.

Appends all of the elements in the specified Collection to the end of


this Vector,
addAll(Collection c)
in the order that they are returned by the specified Collection's
Iterator.

Inserts all the elements in the specified Collection into this Vector at
addAll(int index, Collection c)
the specified position.

Adds the specified component to the end of this vector, increasing


addElement(Object o)
its size by one.

capacity() Returns the current capacity of this vector.

clear() Removes all the elements from this Vector.

clone() Returns a clone of this vector.

contains(Object o) Returns true if this vector contains the specified element.


METHOD DESCRIPTION
Returns true if this Vector contains all the elements in the specified
containsAll(Collection c)
Collection.

copyInto(Object []array) Copies the components of this vector into the specified array.

elementAt(int index) Returns the component at the specified index.

elements() Returns an enumeration of the components of this vector.

Increases the capacity of this vector, if necessary, to ensure that it


ensureCapacity(int can hold
minCapacity)
at least the number of components specified by the minimum
capacity argument.

equals() Compares the specified Object with this Vector for equality.

firstElement() Returns the first component (the item at index 0) of this vector.

get(int index) Returns the element at the specified position in this Vector.

hashCode() Returns the hash code value for this Vector.

Returns the index of the first occurrence of the specified element in


indexOf(Object o) this vector, or -1

if this vector does not contain the element.

Returns the index of the first occurrence of the specified element in


indexOf(Object o, int index) this vector, searching forwards from the index, or returns -1 if the
element is not found.

insertElementAt(Object o, int Inserts the specified object as a component in this vector at the
index) specified index.

isEmpty() Tests if this vector has no components.

iterator() Returns an iterator over the elements in this list in proper sequence.

lastElement() Returns the last component of the vector.

Returns the index of the last occurrence of the specified element in


lastIndexOf(Object o) this vector, or -1

If this vector does not contain the element.


METHOD DESCRIPTION

Returns the index of the last occurrence of the specified element in


lastIndexOf(Object o, int this vector,
index)
searching backward from the index, or returns -1 if the element is
not found.

Returns a list iterator over the elements in this list (in proper
listIterator()
sequence).

Returns a list iterator over the elements in this list (in proper
listIterator(int index) sequence),

starting at the specified position in the list.

remove(int index) Removes the element at the specified position in this Vector.

Removes the first occurrence of the specified element in this Vector


remove(Object o)
If the Vector does not contain the element, it is unchanged.

Removes from this Vector all of its elements that are contained in
removeAll(Collection c)
the specified Collection.

removeAllElements() Removes all components from this vector and sets its size to zero.

Removes the first (lowest-indexed) occurrence of the argument from


removeElement(Object o)
this vector.

removeElementAt(int index) Deletes the component at the specified index.

removeRange(int fromIndex, Removes from this list all the elements whose index is between
int toIndex) fromIndex, inclusive, and toIndex, exclusive.

Retains only the elements in this Vector that are contained in the
retainAll(Collection c)
specified Collection.

Replaces the element at the specified position in this Vector with the
set(int index, Object o)
specified element.

setElementAt(Object o, int Sets the component at the specified index of this vector to be the
index) specified object.

setSize(int newSize) Sets the size of this vector.

size() Returns the number of components in this vector.

subList(int fromIndex, int Returns a view of the portion of this List between fromIndex,
toIndex) inclusive, and toIndex, exclusive.
METHOD DESCRIPTION
Returns an array containing all of the elements in this Vector in the
toArray()
correct order.

Returns an array containing all of the elements in this Vector in the


toArray(Object []array) correct order; the runtime

type of the returned array is that of the specified array.

Returns a string representation of this Vector, containing the String


toString()
representation of each element.

trimToSize() Trims the capacity of this vector to be the vector's current size.

Note: Please note that the Stack class in Java is a legacy class and inherits from Vector in Java. It is a
thread-safe class and hence involves overhead when we do not need thread safety. It is recommended
to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.

Java
// A Java Program to show implementation
// of Stack using ArrayDeque

import java.util.*;

class GFG {
public static void main (String[] args) {
Deque<Character> stack = new ArrayDeque<Character>();
stack.push('A');
stack.push('B');
System.out.println(stack.peek());
System.out.println(stack.pop());
}
}

Output:

B
B

Queue Interface In Java

The Queue interface is present in java.util package and extends the Collection interface is used to hold
the elements about to be processed in FIFO(First In First Out) order. It is an ordered list of objects with
its use limited to inserting elements at the end of the list and deleting elements from the start of the list,
(i.e.), it follows the FIFO or the First-In-First-Out principle.
Being an interface the queue needs a concrete class for the declaration and the most common classes
are the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-
safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is
needed.

Declaration: The Queue interface is declared as:


public interface Queue extends Collection

Creating Queue Objects: Since Queue is an interface, objects cannot be created of the type queue. We
always need a class which extends this list in order to create an object. And also, after the introduction
of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Queue. This
type-safe queue can be defined as:

// Obj is the type of the object to be stored in Queue


Queue<Obj> queue = new PriorityQueue<Obj> ();

Example: Queue

Java

// Java program to demonstrate a Queue

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

public static void main(String[] args)


{
Queue<Integer> q
= new LinkedList<>();

// Adds elements {0, 1, 2, 3, 4} to


// the queue
for (int i = 0; i < 5; i++)
q.add(i);

// Display contents of the queue.


System.out.println("Elements of queue "
+ q);

// To remove the head of queue.


int removedele = q.remove();
System.out.println("removed element-"
+ removedele);

System.out.println(q);

// To view the head of queue


int head = q.peek();
System.out.println("head of queue-"
+ head);

// Rest all methods of collection


// interface like size and contains
// can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-"
+ size);
}
}

Output:

Elements of queue [0, 1, 2, 3, 4]


removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4

Operations on Queue Interface

Let’s see how to perform a few frequently used operations on the queue using the Priority Queue class.
1. Adding Elements: In order to add an element in a queue, we can use the add() method. The insertion
order is not retained in the PriorityQueue. The elements are stored based on the priority order which
is ascending by default.

Example

Java

// Java program to add elements


// to a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

System.out.println(pq);
}
}

Output:

[For, Geeks, Geeks]


2. Removing Elements: In order to remove an element from a queue, we can use the remove()
method. If there are multiple such objects, then the first occurrence of the object is removed. Apart from
that, poll() method is also used to remove the head and return it.

Example

Java

// Java program to remove elements


// from a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

System.out.println("Initial Queue " + pq);

pq.remove("Geeks");

System.out.println("After Remove " + pq);

System.out.println("Poll Method " + pq.poll());

System.out.println("Final Queue " + pq);


}
}
Output:

Initial Queue [For, Geeks, Geeks]


After Remove [For, Geeks]
Poll Method For
Final Queue [Geeks]

3. Iterating the Queue: There are multiple ways to iterate through the Queue. The most famous way is
converting the queue to the array and traversing using the for loop. However, the queue also has an
inbuilt iterator which can be used to iterate through the queue.

Example

Java

// Java program to iterate elements


// to a Queue

import java.util.*;

public class GFG {

public static void main(String args[])


{
Queue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

Iterator iterator = pq.iterator();

while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}

Output:

For Geeks Geeks

Characteristics of a Queue: The following are the characteristics of the queue:

 The Queue is used to insert elements at the end of the queue and removes from the beginning of
the queue. It follows FIFO concept.
 The Java Queue supports all methods of Collection interface including insertion, deletion, etc.
 LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used
implementations.
 If any null operation is performed on BlockingQueues, NullPointerException is thrown.
 The Queues which are available in java.util package are Unbounded Queues.
 The Queues which are available in java.util.concurrent package are the Bounded Queues.
 All Queues except the Deques supports insertion and removal at the tail and head of the queue
respectively. The Deques support element insertion and removal at both ends.

Classes that implement the Queue Interface:

1. PriorityQueue: PriorityQueue class which is implemented in the collection framework provides us


a way to process the objects based on the priority. It is known that a queue follows the First-In-First-
Out algorithm, but sometimes the elements of the queue are needed to be processed according to the
priority, that’s when the PriorityQueue comes into play. Let’s see how to create a queue object using
this class.

Example

Java

// Java program to demonstrate the


// creation of queue object using the
// PriorityQueue class

import java.util.*;

class GfG {

public static void main(String args[])


{
// Creating empty priority queue
Queue<Integer> pQueue
= new PriorityQueue<Integer>();

// Adding items to the pQueue


// using add()
pQueue.add(10);
pQueue.add(20);
pQueue.add(15);

// Printing the top element of


// the PriorityQueue
System.out.println(pQueue.peek());

// Printing the top element and removing it


// from the PriorityQueue container
System.out.println(pQueue.poll());

// Printing the top element again


System.out.println(pQueue.peek());
}
}

Output:

10
10
15

2. LinkedList: LinkedList is a class which is implemented in the collection framework which inherently
implements the linked list data structure. It is a linear data structure where the elements are not stored
in contiguous locations and every element is a separate object with a data part and address part. The
elements are linked using pointers and addresses. Each element is known as a node. Due to the
dynamicity and ease of insertions and deletions, they are preferred over the arrays or queues. Let’s see
how to create a queue object using this class.

Example

Java

// Java program to demonstrate the


// creation of queue object using the
// LinkedList class

import java.util.*;

class GfG {

public static void main(String args[])


{
// Creating empty LinkedList
Queue<Integer> ll
= new LinkedList<Integer>();

// Adding items to the ll


// using add()
ll.add(10);
ll.add(20);
ll.add(15);

// Printing the top element of


// the LinkedList
System.out.println(ll.peek());

// Printing the top element and removing it


// from the LinkedList container
System.out.println(ll.poll());

// Printing the top element again


System.out.println(ll.peek());
}
}

Output:

10
10
20

3. PriorityBlockingQueue: It is to be noted that both the implementations, the PriorityQueue and


LinkedList are not thread-safe. PriorityBlockingQueue is one alternative implementation if thread-safe
implementation is needed. PriorityBlockingQueue is an unbounded blocking queue that uses the same
ordering rules as class PriorityQueue and supplies blocking retrieval operations.
Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting
in OutOfMemoryError. Let’s see how to create a queue object using this class.

Example
Java

// Java program to demonstrate the


// creation of queue object using the
// PriorityBlockingQueue class

import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;

class GfG {
public static void main(String args[])
{
// Creating empty priority
// blocking queue
Queue<Integer> pbq
= new PriorityBlockingQueue<Integer>();

// Adding items to the pbq


// using add()
pbq.add(10);
pbq.add(20);
pbq.add(15);

// Printing the top element of


// the PriorityBlockingQueue
System.out.println(pbq.peek());

// Printing the top element and


// removing it from the
// PriorityBlockingQueue
System.out.println(pbq.poll());

// Printing the top element again


System.out.println(pbq.peek());
}
}

Output:
10
10
15

Methods of Queue Interface

The queue interface inherits all the methods present in the collections interface while implementing
the following methods:

Method Description

This method is used to add an element at a particular index in the


add(int index, element) queue. When a single parameter is passed, it simply adds the element
at the end of the queue.

This method is used to add all the elements in the given collection to
addAll(int index,
the queue. When a single parameter is passed, it adds all the elements
Collection collection)
of the given collection at the end of the queue.

size() This method is used to return the size of the queue.

This method is used to remove all the elements in the queue. However,
clear()
the reference of the queue created is still stored.

This method removes an element from the specified index. It shifts


remove(int index)
subsequent elements(if any) to left and decreases their indexes by 1.

This method is used to remove and return the first occurrence of the
remove(element)
given element in the queue.

get(int index) This method returns elements at the specified index.

This method replaces elements at a given index with the new element.
set(int index, element) This function returns the element which was just replaced by a new
element.

This method returns the first occurrence of the given element or -1 if


indexOf(element)
the element is not present in the queue.

This method returns the last occurrence of the given element or -1 if


lastIndexOf(element)
the element is not present in the queue.
Method Description

This method is used to compare the equality of the given element with
equals(element)
the elements of the queue.

hashCode() This method is used to return the hashcode value of the given queue.

This method is used to check if the queue is empty or not. It returns


isEmpty()
true if the queue is empty, else false.

This method is used to check if the queue contains the given element
contains(element)
or not. It returns true if the queue contains the element.

containsAll(Collection This method is used to check if the queue contains all the collection of
collection) elements.

This method is used to sort the elements of the queue on the basis of
sort(Comparator comp)
the given comparator.

This method is used to insert the specified element into a queue and
boolean add(object)
return true upon success.

boolean offer(object) This method is used to insert the specified element into the queue.

This method is used to retrieve and removes the head of the queue, or
Object poll()
returns null if the queue is empty.

This method is used to retrieves, but does not remove, the head of
Object element()
queue.

This method is used to retrieves, but does not remove, the head of this
Object peek()
queue, or returns null if this queue is empty.

PriorityQueue in Java

A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is
known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue
are needed to be processed according to the priority, that's when the PriorityQueue comes into play.

The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered
according to the natural ordering, or by a Comparator provided at queue construction time, depending
on which constructor is used.
In the below priority queue, an element with a maximum ASCII value will have the highest priority.
Declaration:

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

where E is the type of elements held in this queue

The class implements Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces.

A few important points on Priority Queue are as follows:

 PriorityQueue doesn’t permit null.


 We can’t create a PriorityQueue of Objects that are non-comparable
 PriorityQueue are unbound queues.
 The head of this queue is the least element with respect to the specified ordering. If multiple
elements are tied for the least value, the head is one of those elements -- ties are broken
arbitrarily.
 Since PriorityQueue is not thread-safe, java provides PriorityBlockingQueue class that
implements the BlockingQueue interface to use in a java multithreading environment.
 The queue retrieval operations poll, remove, peek, and element access the element at the head
of the queue.
 It provides O(log(n)) time for add and poll methods.
 It inherits methods from AbstractQueue, AbstractCollection, Collection, and Object class.

Constructors:

1. PriorityQueue(): Creates a PriorityQueue with the default initial capacity (11) that orders its
elements according to their natural ordering.

PriorityQueue<E> pq = new PriorityQueue<E>();


2. PriorityQueue(Collection<E> c): Creates a PriorityQueue containing the elements in the specified
collection.

PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);


3. PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified initial capacity that
orders its elements according to their natural ordering.

PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);


4. PriorityQueue(int initialCapacity, Comparator<E> comparator): Creates a PriorityQueue with
the specified initial capacity that orders its elements according to the specified comparator.

PriorityQueue<E> pq = new PriorityQueue(int initialCapacity, Comparator<E> comparator);


5. PriorityQueue(PriorityQueue<E> c): Creates a PriorityQueue containing the elements in the
specified priority queue.

PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);


6. PriorityQueue(SortedSet<E> c): Creates a PriorityQueue containing the elements in the specified
sorted set.

PriorityQueue<E> pq = new PriorityQueue<E>(SortedSet<E> c);


Example:

The example below explains the following basic operations of the priority queue.

 boolean add(E element): This method inserts the specified element into this priority queue.
 public peek(): This method retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
 public poll(): This method retrieves and removes the head of this queue, or returns null if this
queue is empty.

Java
// Java program to demonstrate the
// working of PriorityQueue
import java.util.*;

class PriorityQueueDemo {
// Main Method
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

// Adding items to the pQueue using add()


pQueue.add(10);
pQueue.add(20);
pQueue.add(15);

// Printing the top element of PriorityQueue


System.out.println(pQueue.peek());

// Printing the top element and removing it


// from the PriorityQueue container
System.out.println(pQueue.poll());

// Printing the top element again


System.out.println(pQueue.peek());
}
}

Output
10
10
15

Operations on PriorityQueue

Let’s see how to perform a few frequently used operations on the Priority Queue class.

1. Adding Elements: In order to add an element in a priority queue, we can use the add() method. The
insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order
which is ascending by default.

Java
/*package whatever //do not write package name here */

import java.util.*;
import java.io.*;

public class PriorityQueueDemo {


public static void main(String args[])
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i=0;i<3;i++){
pq.add(i);
pq.add(1);
}
System.out.println(pq);
}
}

Output
[0, 1, 1, 1, 2, 1]

We will not get sorted elements by printing PriorityQueue.

Java
/*package whatever //do not write package name here */

import java.util.*;
import java.io.*;

public class PriorityQueueDemo {

public static void main(String args[])


{
PriorityQueue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

System.out.println(pq);
}
}
Output
[For, Geeks, Geeks]

2. Removing Elements: In order to remove an element from a priority queue, we can use
the remove() method. If there are multiple such objects, then the first occurrence of the object is
removed. Apart from that, the poll() method is also used to remove the head and return it.

Java
// Java program to remove elements
// from a PriorityQueue

import java.util.*;
import java.io.*;

public class PriorityQueueDemo {

public static void main(String args[])


{
PriorityQueue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

System.out.println("Initial PriorityQueue " + pq);

// using the method


pq.remove("Geeks");

System.out.println("After Remove - " + pq);

System.out.println("Poll Method - " + pq.poll());

System.out.println("Final PriorityQueue - " + pq);


}
}

Output
Initial PriorityQueue [For, Geeks, Geeks]
After Remove - [For, Geeks]
Poll Method - For
Final PriorityQueue - [Geeks]
3. Accessing the elements: Since Queue follows the First In First Out principle, we can access only the
head of the queue. To access elements from a priority queue, we can use the peek() method.

Java
// Java program to access elements
// from a PriorityQueue
import java.util.*;

class PriorityQueueDemo {

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

// Creating a priority queue


PriorityQueue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println("PriorityQueue: " + pq);

// Using the peek() method


String element = pq.peek();
System.out.println("Accessed Element: " + element);
}
}

Output
PriorityQueue: [For, Geeks, Geeks]
Accessed Element: For

4. Iterating the PriorityQueue: There are multiple ways to iterate through the PriorityQueue. The
most famous way is converting the queue to the array and traversing using the for loop. However, the
queue also has an inbuilt iterator which can be used to iterate through the queue.

Java
// Java program to iterate elements
// to a PriorityQueue

import java.util.*;

public class PriorityQueueDemo {


// Main Method
public static void main(String args[])
{
PriorityQueue<String> pq = new PriorityQueue<>();

pq.add("Geeks");
pq.add("For");
pq.add("Geeks");

Iterator iterator = pq.iterator();

while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}

Output
For Geeks Geeks

Methods in PriorityQueue class

METHOD DESCRIPTION

add(E e) Inserts the specified element into this priority queue.

clear() Removes all of the elements from this priority queue.

Returns the comparator used to order the elements in this queue, or null
comparator()
if this queue is sorted according to the natural ordering of its elements.

contains(Object o) Returns true if this queue contains the specified element.

forEach(Consumer<? Performs the given action for each element of the Iterable until all
super E> action) elements have been processed or the action throws an exception.
METHOD DESCRIPTION

iterator() Returns an iterator over the elements in this queue.

offer(E e) Inserts the specified element into this priority queue.

Removes a single instance of the specified element from this queue, if it


remove(Object o)
is present.

removeAll(Collection<?> Removes all of this collection's elements that are also contained in the
c) specified collection (optional operation).

removeIf(Predicate<? Removes all of the elements of this collection that satisfy the given
super E> filter) predicate.

retainAll(Collection<?> Retains only the elements in this collection that are contained in the
c) specified collection (optional operation).

Creates a late-binding and fail-fast Spliterator over the elements in this


spliterator()
queue.

toArray() Returns an array containing all of the elements in this queue.

Returns an array containing all of the elements in this queue; the runtime
toArray(T[] a)
type of the returned array is that of the specified array.

Methods Declared in class java.util.AbstractQueue


METHOD DESCRIPTION

addAll(Collection<? extends E> Adds all of the elements in the specified collection to this
c) queue.

element() Retrieves, but does not remove, the head of this queue.

remove() Retrieves and removes the head of this queue.

Methods Declared in class java.util.AbstractCollection

METHOD DESCRIPTION

containsAll(Collection<?> Returns true if this collection contains all of the elements in the
c) specified collection.

isEmpty() Returns true if this collection contains no elements.

toString() Returns a string representation of this collection.

Methods Declared in interface java.util.Collection

METHOD DESCRIPTION

Returns true if this collection contains all of the elements in the


containsAll(Collection<?> c)
specified collection.

equals(Object o) Compares the specified object with this collection for equality.
METHOD DESCRIPTION

hashCode() Returns the hash code value for this collection.

isEmpty() Returns true if this collection contains no elements.

parallelStream() Returns a possibly parallel Stream with this collection as its source.

size() Returns the number of elements in this collection.

stream() Returns a sequential Stream with this collection as its source.

toArray(IntFunction<T[]> Returns an array containing all of the elements in this collection,


generator) using the provided generator function to allocate the returned array.

Methods Declared in interface java.util.Queue

METHOD DESCRIPTION

Retrieves, but does not remove, the head of this queue, or returns null if this queue is
peek()
empty.

poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.

Applications:

 Implementing Dijkstra's and Prim's algorithms.


 Maximize array sum after K negations

ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us with
dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs
where lots of manipulation in the array is needed. This class is found in java.util package.

Illustration:

Example: The following implementation demonstrates how to create and use an ArrayList.

Java
// Java program to demonstrate the
// working of ArrayList in Java

import java.io.*;
import java.util.*;

class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;

// Declaring the ArrayList with


// initial size n
ArrayList<Integer> arrli
= new ArrayList<Integer>(n);

// Appending new elements at


// the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);

// Printing elements
System.out.println(arrli);

// Remove element at index 3


arrli.remove(3);

// Displaying the ArrayList


// after deletion
System.out.println(arrli);

// Printing elements one by one


for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of
the array automatically increases when we dynamically add and remove items. Though the actual
library implementation may be more complex, the following is a very basic idea explaining the working
of the array when the array becomes full and if we try to add an item:
 Creates a bigger-sized memory on heap memory (for example memory of double size).
 Copies the current memory elements to the new memory.
 New item is added now as there is bigger memory available now.
 Delete the old memory.

Important Features:

 ArrayList inherits AbstractList class and implements the List interface.


 ArrayList is initialized by the size. However, the size is increased automatically if the collection
grows or shrinks if the objects are removed from the collection.
 Java ArrayList allows us to randomly access the list.
 ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such
cases.
 ArrayList in Java can be seen as a vector in C++.
 ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Let's understand the Java ArrayList in depth. Look at the below image:
In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the
classes that implement the list interface. A separate functionality is implemented in each of the
mentioned classes. They are:

1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only
extend this AbstractList Class and implement only the get() and the size() methods.
2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version
of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a
fresh copy of the list.
3. AbstractSequentialList: This class implements the Collection interface and the
AbstractCollection class. This class is used to implement an unmodifiable list, for which one
needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in the ArrayList

In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class
consists of various constructors which allow the possible creation of the array list. The following are
the constructors available in this class:
1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty
ArrayList with the name arr, then, it can be created as:

ArrayList arr = new ArrayList();

2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements
from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present
in the collection c, then, it can be created as:

ArrayList arr = new ArrayList(c);

3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being
specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);


Methods in Java ArrayList

Method Description

This method is used to insert a specific element at a specific position


add(int index, Object element)
index in a list.

add(Object o) This method is used to append a specific element to the end of a list.

This method is used to append all the elements from a specific


addAll(Collection C) collection to the end of the mentioned list, in such an order that the
values are returned by the specified collection’s iterator.

addAll(int index, Collection Used to insert all of the elements starting at the specified position
C) from a specific collection into the mentioned list.

clear() This method is used to remove all the elements from any list.

clone() This method is used to return a shallow copy of an ArrayList.

contains?(Object o) Returns true if this list contains the specified element.

Increases the capacity of this ArrayList instance, if necessary, to


ensureCapacity?(int
ensure that it can hold at least the number of elements specified by
minCapacity)
the minimum capacity argument.

forEach?(Consumer<? super Performs the given action for each element of the Iterable until all
E> action) elements have been processed or the action throws an exception.
Method Description

get?(int index) Returns the element at the specified position in this list.

The index the first occurrence of a specific element is either


indexOf(Object O)
returned, or -1 in case the element is not in the list.

isEmpty?() Returns true if this list contains no elements.

The index of the last occurrence of a specific element is either


lastIndexOf(Object O)
returned or -1 in case the element is not in the list.

Returns a list iterator over the elements in this list (in proper
listIterator?()
sequence).

Returns a list iterator over the elements in this list (in proper
listIterator?(int index)
sequence), starting at the specified position in the list.

remove?(int index) Removes the element at the specified position in this list.

Removes the first occurrence of the specified element from this list,
remove?(Object o)
if it is present.

Removes from this list all of its elements that are contained in the
removeAll?(Collection c)
specified collection.

Removes all of the elements of this collection that satisfy the given
removeIf?(Predicate filter)
predicate.
Method Description

removeRange?(int fromIndex, Removes from this list all of the elements whose index is between
int toIndex) fromIndex, inclusive, and toIndex, exclusive.

Retains only the elements in this list that are contained in the
retainAll?(Collection<?> c)
specified collection.

Replaces the element at the specified position in this list with the
set?(int index, E element)
specified element.

size?() Returns the number of elements in this list.

Creates a late-binding and fail-fast Spliterator over the elements in


spliterator?()
this list.

subList?(int fromIndex, int Returns a view of the portion of this list between the specified
toIndex) fromIndex, inclusive, and toIndex, exclusive.

This method is used to return an array containing all of the elements


toArray()
in the list in the correct order.

It is also used to return an array containing all of the elements in this


toArray(Object[] O)
list in the correct order same as the previous method.

This method is used to trim the capacity of the instance of the


trimToSize()
ArrayList to the list's current size.

Note: You can also create a generic ArrayList:


// Creating generic integer ArrayList
ArrayList<Integer> arrli = new ArrayList<Integer>();

Let's see how to perform some basics operations on the ArrayList as listed which we are going to
discuss further alongside implementing every operation.

 Adding element to List


 Changing elements
 Removing elements
 Iterating elements

Operation 1: Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to
perform multiple operations based on different parameters. They are as follows:

 add(Object): This method is used to add an element at the end of the ArrayList.
 add(int index, Object): This method is used to add an element at a specific index in the ArrayList.

Example:

Java
// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Array of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to ArrayList


// Custom inputs
al.add("Geeks");
al.add("Geeks");

// Here we are mentioning the index


// at which it is to be added
al.add(1, "For");

// Printing all the elements in an ArrayList


System.out.println(al);
}
}

Output:

[Geeks, For, Geeks]

Operation 2: Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since
an ArrayList is indexed, the element which we wish to change is referenced by the index of the element.
Therefore, this method takes an index and the updated element which needs to be inserted at that
index.

Example

Java
// Java Program to Change elements in ArrayList

// Importing all utility classes


import java.util.*;

// main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Arraylist object of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to Arraylist


// Custom input elements
al.add("Geeks");
al.add("Geeks");

// Adding specifying the index to be added


al.add(1, "Geeks");

// Printing the Arraylist elements


System.out.println("Initial ArrayList " + al);

// Setting element at 1st index


al.set(1, "For");

// Printing the updated Arraylist


System.out.println("Updated ArrayList " + al);
}
}

Output:

Initial ArrayList [Geeks, Geeks, Geeks]


Updated ArrayList [Geeks, For, Geeks]

Operation 3: Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method. This method is
overloaded to perform multiple operations based on different parameters. They are as follows:

 remove(Object): This method is used to simply remove an object from the ArrayList. If there
are multiple such objects, then the first occurrence of the object is removed.
 remove(int index): Since an ArrayList is indexed, this method takes an integer value which
simply removes the element present at that specific index in the ArrayList. After removing the
element, all the elements are moved to the left to fill the space and the indices of the objects are
updated.

Example

Java
// Java program to Remove Elements in ArrayList

// Importing all utility classes


import java.util.*;

// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList<String> al = new ArrayList<>();

// Adding elements to ArrayList


// Custom addition
al.add("Geeks");
al.add("Geeks");
// Adding element at specific index
al.add(1, "For");

// Printing all elements of ArrayList


System.out.println("Initial ArrayList " + al);

// Removing element from above ArrayList


al.remove(1);

// Printing the updated Arraylist elements


System.out.println("After the Index Removal " + al);

// Removing this word element in ArrayList


al.remove("Geeks");

// Now printing updated ArrayList


System.out.println("After the Object Removal "
+ al);
}
}

Output:

Initial ArrayList [Geeks, For, Geeks]


After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
Operation 4: Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the
basic for loop in combination with a get() method to get the element at a specific index and
the advanced for loop.

Example

Java
// Java program to Iterate the elements
// in an ArrayList

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Arraylist of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to ArrayList


// using standard add() method
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");

// Using the Get method and the


// for loop
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}

System.out.println();

// Using the for each loop


for (String str : al)
System.out.print(str + " ");
}
}

Output:

Geeks For Geeks


Geeks For Geeks

Articles (7)

Set in Java

HashSet in Java

LinkedHashSet in Java with Examples

TreeSet in Java

Map Interface in Java

HashMap and TreeMap in Java

LinkedHashMap in Java

Set in Java

The set interface is present in java.util package and extends the Collection interface is an unordered
collection of objects in which duplicate values cannot be stored. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Collection interface and adds
a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the
set implementation namely SortedSet and NavigableSet.
In the above image, the navigable set extends the sorted set interface. Since a set doesn't retain the
insertion order, the navigable set interface provides the implementation to navigate through the Set.
The class which implements the navigable set is a TreeSet which is an implementation of a self-
balancing tree. Therefore, this interface provides us with a way to navigate through this tree.

Declaration: The Set interface is declared as:

public interface Set extends Collection

Creating Set Objects

Since Set is an interface, objects cannot be created of the typeset. We always need a class that extends
this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible
to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:

// Obj is the type of the object to be stored in Set


Set<Obj> set = new HashSet<Obj> ();

Let us discuss methods present in the Set interface provided below in a tabular format below as follows:
Method Description

This method is used to add a specific element to the set. The function adds the
add(element) element only if the specified element is not already present in the set else the
function returns False if the element is already present in the Set.

This method is used to append all of the elements from the mentioned collection to
addAll(collection) the existing set. The elements are added randomly without following any specific
order.

This method is used to remove all the elements from the set but not delete the set.
clear()
The reference for the set still exists.

contains(element) This method is used to check whether a specific element is present in the Set or not.

This method is used to check whether the set contains all the elements present in
containsAll(collection) the given collection or not. This method returns true if the set contains all the
elements and returns false if any of the elements are missing.

This method is used to get the hashCode value for this instance of the Set. It returns
hashCode()
an integer value which is the hashCode value for this instance of the Set.

isEmpty() This method is used to check whether the set is empty or not.

This method is used to return the iterator of the set. The elements from the set are
iterator()
returned in a random order.

This method is used to remove the given element from the set. This method returns
remove(element)
True if the specified element is present in the Set otherwise it returns False.
Method Description

This method is used to remove all the elements from the collection which are
removeAll(collection)
present in the set. This method returns true if this set changed as a result of the call.

This method is used to retain all the elements from the set which are mentioned in
retainAll(collection) the given collection. This method returns true if this set changed as a result of the
call.

This method is used to get the size of the set. This returns an integer value which
size()
signifies the number of elements.

toArray() This method is used to form an array of the same elements as that of the Set.

Illustration: Sample Program to Illustrate Set interface

Java
// Java program Illustrating Set Interface

// Importing utility classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Demonstrating Set using HashSet
// Declaring object of type String
Set<String> hash_Set = new HashSet<String>();

// Adding elements to the Set


// using add() method
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");

// Printing elements of HashSet object


System.out.println(hash_Set);
}
}

Output
[Set, Example, Geeks, For]

Operations on the Set Interface

The set interface allows the users to perform the basic mathematical operation on the set. Let's take
two arrays to understand these basic operations. Let set1 = [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0,
7, 5]. Then the possible operations on the sets are:

1. Intersection: This operation returns all the common elements from the given two sets. For the above
two sets, the intersection would be:

Intersection = [0, 1, 3, 4]

2. Union: This operation adds all the elements in one set with the other. For the above two sets, the
union would be:

Union = [0, 1, 2, 3, 4, 5, 7, 8, 9]

3. Difference: This operation removes all the values present in one set from the other set. For the above
two sets, the difference would be:
Difference = [2, 8, 9]

Now let us implement the following operations as defined above as follows:

Example:

div hideAd="auto">

Java
// Java Program Demonstrating Operations on the Set
// such as Union, Intersection and Difference operations

// Importing all utility classes


import java.util.*;

// Main class
public class SetExample {

// Main driver method


public static void main(String args[])
{
// Creating an object of Set class
// Declaring object of Integer type
Set<Integer> a = new HashSet<Integer>();

// Adding all elements to List


a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
// Again declaring object of Set class
// with reference to HashSet
Set<Integer> b = new HashSet<Integer>();

b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));

// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);

// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);

// To find the symmetric difference


Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}

Output
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection of the two Set[0, 1, 3, 4]
Difference of the two Set[2, 8, 9]

Performing Various Operations on SortedSet


After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored
in the Set. Since Set is an interface, it can be used only with a class that implements this interface.
HashSet is one of the widely used classes which implements the Set interface. Now, let’s see how to
perform a few frequently used operations on the HashSet. We are going to perform the following
operations as follows:
1. Adding elements
2. Accessing elements
3. Removing elements
4. Iterating elements
5. Iterating through Set

Now let us discuss these operations individually as follows:

Operations 1: Adding Elements

In order to add an element to the Set, we can use the add() method. However, the insertion order is not
retained in the Set. Internally, for every element, a hash is generated and the values are stored with
respect to the generated hash. the values are compared and sorted in ascending order. We need to keep
a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null
values are accepted by the Set.

Example

Java
// Java Program Demonstrating Working of Set by
// Adding elements using add() method

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an object of Set and
// declaring object of type String
Set<String> hs = new HashSet<String>();

// Adding elements to above object


// using add() method
hs.add("B");
hs.add("B");
hs.add("C");
hs.add("A");
// Printing the elements inside the Set object
System.out.println(hs);
}
}

Output
[A, B, C]

Operation 2: Accessing the Elements

After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains().

Example

Java
// Java code to demonstrate Working of Set by
// Accessing the Elements of the Set object

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an object of Set and
// declaring object of type String
Set<String> hs = new HashSet<String>();

// Elements are added using add() method


// Later onwards we will show accessing the same

// Custom input elements


hs.add("A");
hs.add("B");
hs.add("C");
hs.add("A");

// Print the Set object elements


System.out.println("Set is " + hs);

// Declaring a string
String check = "D";

// Check if the above string exists in


// the SortedSet or not
// using contains() method
System.out.println("Contains " + check + " "
+ hs.contains(check));
}
}

Output
Set is [A, B, C]
Contains D false

Operation 3: Removing the Values

The values can be removed from the Set using the remove() method.

Example

Java
// Java Program Demonstrating Working of Set by
// Removing Element/s from the Set

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring object of Set of type String
Set<String> hs = new HashSet<String>();

// Elements are added


// using add() method

// Custom input elements


hs.add("A");
hs.add("B");
hs.add("C");
hs.add("B");
hs.add("D");
hs.add("E");

// Printing initial Set elements


System.out.println("Initial HashSet " + hs);

// Removing custom element


// using remove() method
hs.remove("B");

// Printing Set elements after removing an element


// and printing updated Set elements
System.out.println("After removing element " + hs);
}
}

Output
Initial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]

Operation 4: Iterating through the Set

There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop.

Example

Java
// Java Program to Demonstrate Working of Set by
// Iterating through the Elements

// Importing utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating object of Set and declaring String type
Set<String> hs = new HashSet<String>();
// Adding elements to Set
// using add() method

// Custom input elements


hs.add("A");
hs.add("B");
hs.add("C");
hs.add("B");
hs.add("D");
hs.add("E");

// Iterating through the Set


// via for-each loop
for (String value : hs)

// Printing all the values inside the object


System.out.print(value + ", ");

System.out.println();
}
}

Output
A, B, C, D, E,

Classes that implement the Set interface in Java Collections can be easily perceived from the
image below as follows and are listed as follows:

 HashSet
 EnumSet
 LinkedHashSet
 TreeSet
Class 1: HashSet

HashSet class which is implemented in the collection framework is an inherent implementation of


the hash table data structure. The objects that we insert into the HashSet do not guarantee to be
inserted in the same order. The objects are inserted based on their hashcode. This class also allows the
insertion of NULL elements. Let’s see how to create a set object using this class.

Example

Java
// Java program Demonstrating Creation of Set object
// Using the Hashset class

// Importing utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating object of Set of type String
Set<String> h = new HashSet<String>();

// Adding elements into the HashSet


// using add() method
// Custom input elements
h.add("India");
h.add("Australia");
h.add("South Africa");

// Adding the duplicate element


h.add("India");

// Displaying the HashSet


System.out.println(h);

// Removing items from HashSet


// using remove() method
h.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + h);

// Iterating over hash set items


System.out.println("Iterating over set:");

// Iterating through iterators


Iterator<String> i = h.iterator();

// It holds true till there is a single element


// remaining in the object
while (i.hasNext())

System.out.println(i.next());
}
}

Output
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India

Class 2: EnumSet

EnumSet class which is implemented in the collections framework is one of the specialized
implementations of the Set interface for use with the enumeration type. It is a high-performance set
implementation, much faster than HashSet. All of the elements in an enum set must come from a single
enumeration type that is specified when the set is created either explicitly or implicitly. Let's see how
to create a set object using this class.

Example

Java
// Java program to demonstrate the
// creation of the set object
// using the EnumSet class
import java.util.*;

enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }


;

public class GFG {

public static void main(String[] args)


{
// Creating a set
Set<Gfg> set1;

// Adding the elements


set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.LEARN, Gfg.CODE);

System.out.println("Set 1: " + set1);


}
}

Output
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]

Class 3: LinkedHashSet

LinkedHashSet class which is implemented in the collections framework is an ordered version of


HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to
be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a
LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let's see
how to create a set object using this class.

Example

Java
// Java program to demonstrate the
// creation of Set object using
// the LinkedHashset class
import java.util.*;

class GFG {

public static void main(String[] args)


{
Set<String> lh = new LinkedHashSet<String>();

// Adding elements into the LinkedHashSet


// using add()
lh.add("India");
lh.add("Australia");
lh.add("South Africa");

// Adding the duplicate


// element
lh.add("India");

// Displaying the LinkedHashSet


System.out.println(lh);

// Removing items from LinkedHashSet


// using remove()
lh.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + lh);

// Iterating over linked hash set items


System.out.println("Iterating over set:");
Iterator<String> i = lh.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}

Output
[India, Australia, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

Class 4: TreeSet

TreeSet class which is implemented in the collections framework and implementation of the SortedSet
Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it
stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in
sorted, ascending order. But we can iterate in descending order using the method
TreeSet.descendingIterator(). Let's see how to create a set object using this class.

Example

Java
// Java Program Demonstrating Creation of Set object
// Using the TreeSet class

// Importing utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating a Set object and declaring it of String
// type
// with reference to TreeSet
Set<String> ts = new TreeSet<String>();

// Adding elements into the TreeSet


// using add()
ts.add("India");
ts.add("Australia");
ts.add("South Africa");

// Adding the duplicate


// element
ts.add("India");

// Displaying the TreeSet


System.out.println(ts);

// Removing items from TreeSet


// using remove()
ts.remove("Australia");
System.out.println("Set after removing "
+ "Australia:" + ts);

// Iterating over Tree set items


System.out.println("Iterating over set:");
Iterator<String> i = ts.iterator();

while (i.hasNext())
System.out.println(i.next());
}
}

Output
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

HashSet in Java

The HashSet class implements the Set interface, backed by a hash table which is actually
a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class
does not guarantee the constant order of elements over time. This class permits the null element. The
class also offers constant time performance for the basic operations like add, remove, contains, and size
assuming the hash function disperses the elements properly among the buckets, which we shall see
further in the article.

A few important features of HashSet are:

 Implements Set Interface.


 The underlying data structure for HashSet is Hashtable.
 As it implements the Set Interface, duplicate values are not allowed.
 Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects
are inserted based on their hash code.
 NULL elements are allowed in HashSet.
 HashSet also implements Serializable and Cloneable interfaces.

The Hierarchy of HashSet is as follows:

HashSet extends Abstract Set<E> class and implements Set<E>, Cloneable, and Serializable interfaces
where E is the type of elements maintained by this set. The directly known subclass of HashSet
is LinkedHashSet.

Now for the maintenance of constant time performance, iterating over HashSet requires time
proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of
the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial
capacity too high (or the load factor too low) if iteration performance is important.

 Initial Capacity: The initial capacity means the number of buckets when hashtable (HashSet
internally uses hashtable data structure) is created. The number of buckets will be automatically
increased if the current size gets full.

 Load Factor: The load factor is a measure of how full the HashSet is allowed to get before its
capacity is automatically increased. When the number of entries in the hash table exceeds the
product of the load factor and the current capacity, the hash table is rehashed (that is, internal
data structures are rebuilt) so that the hash table has approximately twice the number of
buckets.

Number of stored elements in the table


Load Factor = -----------------------------------------
Size of the hash table

Example: If internal capacity is 16 and the load factor is 0.75 then the number of buckets will
automatically get increased when the table has 12 elements in it.
Effect on performance: Load factor and initial capacity are two main factors that affect the
performance of HashSet operations. A load factor of 0.75 provides very effective performance with
respect to time and space complexity. If we increase the load factor value more than that then memory
overhead will be reduced (because it will decrease internal rebuilding operation) but, it will affect the
add and search operation in the hashtable. To reduce the rehashing operation we should choose initial
capacity wisely. If the initial capacity is greater than the maximum number of entries divided by the
load factor, no rehash operation will ever occur.

Note: The implementation in a HashSet is not synchronized, in the sense that if multiple threads
access a hash set concurrently, and at least one of the threads modifies the set, it must be
synchronized externally. This is typically accomplished by synchronizing on some object that
naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the
Collections.synchronizedSet method. This is best done at creation time, to prevent accidental
unsynchronized access to the set as shown below:
Set s = Collections.synchronizedSet(new HashSet(...));

Syntax: Declaration of HashSet

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serial


izable

where E is the type of elements stored in a HashSet.

Internal working of a HashSet: All the classes of Set interface are internally backed up by Map.
HashSet uses HashMap for storing its object internally. You must be wondering that to enter a value in
HashMap we need a key-value pair, but in HashSet, we are passing only one value.

Storage in HashMap: Actually the value we insert in HashSet acts as a key to the map Object and for its
value, java uses a constant variable. So in the key-value pair, all the values will be the same.

Implementation of HashSet in Java doc

private transient HashMap map;

// Constructor - 1
// All the constructors are internally creating HashMap Object.
public HashSet()
{
// Creating internally backing HashMap object
map = new HashMap();
}

// Constructor - 2
public HashSet(int initialCapacity)
{
// Creating internally backing HashMap object
map = new HashMap(initialCapacity);
}

// Dummy value to associate with an Object in Map


private static final Object PRESENT = new Object();

If we look at the add() method of HashSet class:

public boolean add(E e)


{
return map.put(e, PRESENT) == null;
}

We can notice that, add() method of HashSet class internally calls the put() method of backing the
HashMap object by passing the element you have specified as a key and constant “PRESENT” as
its value. remove() method also works in the same manner. It internally calls the remove method of the
Map interface.

public boolean remove(Object o)


{
return map.remove(o) == PRESENT;
}

HashSet not only stores unique Objects but also a unique Collection of
Objects like ArrayList<E>, LinkedList<E>, Vector<E>,..etc.

Implementation:

Java
// Java program to illustrate the concept
// of Collection objects storage in a HashSet
import java.io.*;
import java.util.*;

class CollectionObjectStorage {

public static void main(String[] args)


{
// Instantiate an object of HashSet
HashSet<ArrayList> set = new HashSet<>();

// create ArrayList list1


ArrayList<Integer> list1 = new ArrayList<>();

// create ArrayList list2


ArrayList<Integer> list2 = new ArrayList<>();
// Add elements using add method
list1.add(1);
list1.add(2);
list2.add(1);
list2.add(2);
set.add(list1);
set.add(list2);

// print the set size to understand the


// internal storage of ArrayList in Set
System.out.println(set.size());
}
}

Output:
1

Before storing an Object, HashSet checks whether there is an existing entry using hashCode() and
equals() methods. In the above example, two lists are considered equal if they have the same elements
in the same order. When you invoke the hashCode() method on the two lists, they both would give the
same hash since they are equal.

HashSet does not store duplicate items, if you give two Objects that are equal then it stores only the
first one, here it is list1.

Constructors of HashSet class

In order to create a HashSet, we need to create an object of the HashSet class. The HashSet class consists
of various constructors that allow the possible creation of the HashSet. The following are the
constructors available in this class.

1. HashSet(): This constructor is used to build an empty HashSet object in which the default initial
capacity is 16 and the default load factor is 0.75. If we wish to create an empty HashSet with the name
hs, then, it can be created as:

HashSet<E> hs = new HashSet<E>();

2. HashSet(int initialCapacity): This constructor is used to build an empty HashSet object in which
the initialCapacity is specified at the time of object creation. Here, the default loadFactor remains 0.75.

HashSet<E> hs = new HashSet<E>(int initialCapacity);

3. HashSet(int initialCapacity, float loadFactor): This constructor is used to build an empty HashSet
object in which the initialCapacity and loadFactor are specified at the time of object creation.

HashSet<E> hs = new HashSet<E>(int initialCapacity, float loadFactor);


4. HashSet(Collection): This constructor is used to build a HashSet object containing all the elements
from the given collection. In short, this constructor is used when any conversion is needed from any
Collection object to the HashSet object. If we wish to create a HashSet with the name hs, it can be created
as:

HashSet<E> hs = new HashSet<E>(Collection C);

Implementation:

Java
// Java program to Demonstrate Working of HashSet Class

// Importing required classes


import java.util.*;

// Main class
// HashSetDemo
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty HashSet


HashSet<String> h = new HashSet<String>();

// Adding elements into HashSet


// using add() method
h.add("India");
h.add("Australia");
h.add("South Africa");

// Adding duplicate elements


h.add("India");

// Displaying the HashSet


System.out.println(h);
System.out.println("List contains India or not:"
+ h.contains("India"));

// Removing items from HashSet


// using remove() method
h.remove("Australia");
System.out.println("List after removing Australia:"
+ h);

// Display message
System.out.println("Iterating over list:");

// Iterating over hashSet items


Iterator<String> i = h.iterator();

// Holds true till there is single element remaining


while (i.hasNext())

// Iterating over elements


// using next() method
System.out.println(i.next());
}
}

Output:
[South Africa, Australia, India]
List contains India or not:true
List after removing Australia:[South Africa, India]
Iterating over list:
South Africa
India

Performing Various Operations on HashSet

Let’s see how to perform a few frequently used operations on the HashSet.

Operation 1: Adding Elements

In order to add an element to the HashSet, we can use the add() method. However, the insertion order
is not retained in the HashSet. We need to keep a note that duplicate elements are not allowed and all
the duplicate elements are ignored.

Example
Java
// Java program to Adding Elements to HashSet

// Importing required classes


import java.io.*;
import java.util.*;

// Main class
// AddingElementsToHashSet
class GFG {

// Method 1
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashSet of string entities
HashSet<String> hs = new HashSet<String>();

// Adding elements using add() method


hs.add("Geek");
hs.add("For");
hs.add("Geeks");

// Printing all string el=ntries inside the Set


System.out.println("HashSet elements : " + hs);
}
}

Output:
HashSet elements : [Geek, For, Geeks]

Operation 2: Removing Elements

The values can be removed from the HashSet using the remove() method.

Example

Java
// Java program Illustrating Removal Of Elements of HashSet

// Importing required classes


import java.io.*;
import java.util.*;
// Main class
// RemoveElementsOfHashSet
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an
HashSet<String> hs = new HashSet<String>();

// Adding elements to above Set


// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");

// Printing the elements of HashSet elements


System.out.println("Initial HashSet " + hs);

// Removing the element B


hs.remove("B");

// Printing the updated HashSet elements


System.out.println("After removing element " + hs);

// Returns false if the element is not present


System.out.println("Element AC exists in the Set : "
+ hs.remove("AC"));
}
}

Output:
Initial HashSet [A, B, Geek, For, Geeks, Z]
After removing element [A, Geek, For, Geeks, Z]
Element AC exists in the Set : false

Operation 3: Iterating through the HashSet

Iterate through the elements of HashSet using the iterator() method. Also, the most famous one is to
use the enhanced for loop.
Example

Java
// Java Program to Illustrate Iteration Over HashSet

// Importing required classes


import java.io.*;
import java.util.*;

// Main class
// IterateTheHashSet
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty HashSet of string entries


HashSet<String> hs = new HashSet<String>();

// Adding elements to above Set


// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");

// Iterating though the HashSet using iterators


Iterator itr = hs.iterator();

// Holds true till there is single element


// remaining in Set
while (itr.hasNext())

// Traversing elements and printing them


System.out.print(itr.next() + ", ");
System.out.println();

// Using enhanced for loop for traversal


for (String s : hs)
// Traversing elements and printing them
System.out.print(s + ", ");
System.out.println();
}
}

Output
A, B, Geek, For, Geeks, Z,
A, B, Geek, For, Geeks, Z,

Time Complexity of HashSet Operations: The underlying data structure for HashSet is
hashtable. So amortize (average or usual case) time complexity for add, remove and look-up
(contains method) operation of HashSet takes O(1) time.

Methods in HashSet

METHOD DESCRIPTION
Used to add the specified element if it is not present, if it is present then return
add(E e)
false.

clear() Used to remove all the elements from set.

contains(Object
Used to return true if an element is present in set.
o)

remove(Object
Used to remove the element if it is present in set.
o)

iterator() Used to return an iterator over the element in the set.

Used to check whether the set is empty or not. Returns true for empty and false
isEmpty()
for a non-empty condition for set.

size() Used to return the size of the set.

clone() Used to create a shallow copy of the set.

Methods inherited from class java.util.AbstractSet

METHOD DESCRIPTION
Used to verify the equality of an Object with a HashSet and compare them.
equals() The list returns true only if both HashSet contains same elements,
irrespective of order.

hashcode() Returns the hash code value for this set.


METHOD DESCRIPTION

This method is used to remove all the elements from the collection which are
removeAll(collection) present in the set.

This method returns true if this set changed as a result of the call.

Methods inherited from class java.util.AbstractCollection

METHOD DESCRIPTION

This method is used to append all of the elements from the mentioned
addAll(collection) collection to the existing set.

The elements are added randomly without following any specific order.

This method is used to check whether the set contains all the elements
present in the given collection or not.
containsAll(collection)
This method returns true if the set contains all the elements and returns
false if any of the elements are missing.

This method is used to retain all the elements from the set which are
retainAll(collection) mentioned in the given collection.

This method returns true if this set changed as a result of the call.

This method is used to form an array of the same elements as that of the
toArray()
Set.

The toString() method of Java HashSet is used to return a string


toString()
representation of the elements of the HashSet Collection.

Methods declared in interface java.util.Collection

METHOD DESCRIPTION
parallelStream() Returns a possibly parallel Stream with this collection as its source.

removeIf(Predicate<? Removes all of the elements of this collection that satisfy the given
super E> filter) predicate.

stream() Returns a sequential Stream with this collection as its source.

toArray(IntFunction<T[]> Returns an array containing all of the elements in this collection, using
generator) the provided generator function to allocate the returned array.

Methods declared in interface java.lang.Iterable


METHOD DESCRIPTION
forEach(Consumer<? Performs the given action for each element of the Iterable until all
super T> action) elements have been processed or the action throws an exception.

Methods declared in interface java.util.Set

METHOD DESCRIPTION
addAll(Collection<? Adds all of the elements in the specified collection to this set if they're
extends E> c) not already present (optional operation).

containsAll Returns true if this set contains all of the elements of the specified
(Collection<?> c) collection.

equals(Object o) Compares the specified object with this set for equality.

hashCode() Returns the hash code value for this set.

removeAll Removes from this set all of its elements that are contained in the
(Collection<?> c) specified collection (optional operation).

retainAll(Collection<?> Retains only the elements in this set that are contained in the specified
c) collection (optional operation).

toArray() Returns an array containing all of the elements in this set.

Returns an array containing all of the elements in this set; the runtime
toArray(T[] a)
type of the returned array is that of the specified array.

HashSet vs HashMap

BASIS HashSet HashMap


HashMap implements Map
Implementation HashSet implements Set interface.
interface.

HashMap store key, value pairs


and it does not allow duplicate
Duplicates HashSet doesn't allow duplicate values. keys. If key is duplicate then
the old key is replaced with the
new value.

Number of objects HashMap requires two objects


HashSet requires only one object
during storing put(K key, V Value) to add an
add(Object o).
objects element to the HashMap object.

HashSet internally uses HashMap to add


elements. In HashSet, the argument passed
HashMap does not have any
Dummy value in add(Object) method serves as key K. Java
concept of dummy value.
internally associates dummy value for each
value passed in add(Object) method.
BASIS HashSet HashMap
Storing or Adding HashSet internally uses the HashMap object HashMap internally uses
mechanism to store or add the objects. hashing to store or add objects

HashMap is faster than


Faster HashSet is slower than HashMap.
HashSet.

HashSet uses the add() method for add or HashMap uses the put() method
Insertion
storing data. for storing data.

HashMap is a key -> value


Example HashSet is a set, e.g. {1, 2, 3, 4, 5, 6, 7}. pair(key to value) map, e.g. {a -
> 1, b -> 2, c -> 2, d -> 1}.

HashSet vs TreeSet

BASIS HashSet TreeSet


For operations like TreeSet takes O(Log n) for search, insert and delete
search, insert and delete. which is higher than HashSet. But TreeSet keeps
It takes constant time for sorted data. Also, it supports operations like higher()
Speed and
these operations on (Returns least higher element), floor(), ceiling(), etc.
internal
average. HashSet is These operations are also O(Log n) in TreeSet and
implementation
faster than TreeSet. not supported in HashSet. TreeSet is implemented
HashSet is Implemented using a Self Balancing Binary Search Tree (Red-
using a hash table. Black Tree). TreeSet is backed by TreeMap in Java.

TreeSet maintains objects in Sorted order defined by


either Comparable or Comparator method in Java.
Elements in HashSet are
Ordering TreeSet elements are sorted in ascending order by
not ordered.
default. It offers several methods to deal with the
ordered set like first(), last(), headSet(), tailSet(), etc.

TreeSet doesn’t allow null Object and throw


NullPointerException, Why, because TreeSet uses
HashSet allows the null
Null Object compareTo() method to compare keys and
object.
compareTo() will throw
java.lang.NullPointerException.

TreeSet uses compareTo() method for same purpose.


HashSet uses equals() If equals() and compareTo() are not consistent, i.e. for
method to compare two two equal object equals should return true while
Comparison
objects in Set and for compareTo() should return zero, then it will break the
detecting duplicates. contract of the Set interface and will allow duplicates
in Set implementations like TreeSet

LinkedHashSet in Java with Examples

The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all
elements. When the iteration order is needed to be maintained this class is used. When iterating through
a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the
order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements
will be returned in the order in which they were inserted.

The Hierarchy of LinkedHashSet is as follows:

Parameters: The type of elements maintained by this set

All Implemented Interfaces are as listed below:


Serializable
Cloneable,
Iterable<E>
Collection<E>
Set<E>

Syntax: Declaration

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Seri


alizable

 Contains unique elements only like HashSet. It extends the HashSet class and implements the Set
interface.
 Maintains insertion order.

Constructors of LinkedHashSet Class

1. LinkedHashSet(): This constructor is used to create a default HashSet

LinkedHashSet<E> hs = new LinkedHashSet<E>();

2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C.

LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);


3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer
mentioned in the parameter.

LinkedHashSet<E> hs = new LinkedHashSet<E>(int size);

4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill
ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the
parameter. When the number of elements exceeds the capacity of the hash set is multiplied with the fill
ratio thus expanding the capacity of the LinkedHashSet.

LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity, int fillRatio);

Example:

Java
// Java Program to Illustrate LinkedHashSet

// Importing required classes


import java.util.LinkedHashSet;

// Main class
// LinkedHashSetExample
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty LinkedHashSet of string type


LinkedHashSet<String> linkedset
= new LinkedHashSet<String>();

// Adding element to LinkedHashSet


// using add() method
linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");

// Note: This will not add new element


// as A already exists
linkedset.add("A");
linkedset.add("E");

// Getting size of LinkedHashSet


// using size() method
System.out.println("Size of LinkedHashSet = "
+ linkedset.size());

System.out.println("Original LinkedHashSet:"
+ linkedset);

// Removing existing entry from above Set


// using remove() method
System.out.println("Removing D from LinkedHashSet: "
+ linkedset.remove("D"));

// Removing existing entry from above Set


// that does not exist in Set
System.out.println(
"Trying to Remove Z which is not "
+ "present: " + linkedset.remove("Z"));

// Checking for element whether it is present inside


// Set or not using contains() method
System.out.println("Checking if A is present="
+ linkedset.contains("A"));

// Noew lastly printing the updated LinkedHashMap


System.out.println("Updated LinkedHashSet: "
+ linkedset);
}
}

Output
Size of LinkedHashSet = 5
Original LinkedHashSet:[A, B, C, D, E]
Removing D from LinkedHashSet: true
Trying to Remove Z which is not present: false
Checking if A is present=true
Updated LinkedHashSet: [A, B, C, E]

Performing Various Operations on the LinkedHashSet Class

Let’s see how to perform a few frequently used operations on the LinkedHashSet.

Operation 1: Adding Elements


In order to add an element to the LinkedHashSet, we can use the add() method. This is different from
HashSet because in HashSet, the insertion order is not retained but is retained in the LinkedHashSet.

Example:

Java
// Java Program to Add Elements to LinkedHashSet

// Importing required classes


import java.io.*;
import java.util.*;

// Main class
// AddingElementsToLinkedHashSet
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty LinkedHashSet


LinkedHashSet<String> hs = new LinkedHashSet<String>();

// Adding elements to above Set


// using add() method

// Note: Insertion order is maintained


hs.add("Geek");
hs.add("For");
hs.add("Geeks");

// Printing elements of Set


System.out.println("LinkedHashSet : " + hs);
}
}

Output:
LinkedHashSet : [Geek, For, Geeks]

Operation 2: Removing Elements

The values can be removed from the LinkedHashSet using the remove() method.

Example:
Java
// Java program to Remove Elements from LinkedHashSet

// Importing required classes


import java.io.*;
import java.util.*;

// Main class
// RemoveElementsFromLinkedHashSet
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty LinekdhashSet of string type


LinkedHashSet<String> hs
= new LinkedHashSet<String>();

// Adding elements to above Set


// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");

// Printing all above elements to the console


System.out.println("Initial HashSet " + hs);

// Removing the element from above Set


hs.remove("B");

// Again removing the element


System.out.println("After removing element " + hs);

// Returning false if the element is not present


System.out.println(hs.remove("AC"));
}
}
Output:
Initial HashSet [Geek, For, Geeks, A, B, Z]
After removing element [Geek, For, Geeks, A, Z]
false

Operation 3: Iterating through LinkedHashSet

Iterate through the elements of LinkedHashSet using the iterator() method. The most famous one is to
use the enhanced for loop.

Example:

Java
// Java Program to Illustrate Iterating over LinkedHashSet

// Importing required classes


import java.io.*;
import java.util.*;

// Main class
// IteratingLinkedHashSet
class GFG {

// Main driver method


public static void main(String[] args)
{

// Instantiate an object of Set


// Since LinkedHashSet implements Set
// Set points to LinkedHashSet
Set<String> hs = new LinkedHashSet<String>();

// Adding elements to above Set


// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");

// Iterating though the LinkedHashSet


// using iterators
Iterator itr = hs.iterator();

while (itr.hasNext())
System.out.print(itr.next() + ", ");

// New line
System.out.println();

// Using enhanced for loop for iteration


for (String s : hs)
System.out.print(s + ", ");
System.out.println();
}
}

Output:
Geek, For, Geeks, A, B, Z,
Geek, For, Geeks, A, B, Z,

Methods of LinkedHashSet

Here, E is the type of element stored.

METHOD DESCRIPTION
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set.

Methods Declared in class java.util.AbstractSet

METHOD DESCRIPTION
equals(Object o) Compares the specified object with this set for equality.

hashCode() Returns the hash code value for this set.

removeAll(Collection Removes from this set all of its elements that are contained in the specified
c) collection (optional operation).

Methods declared in class java.util.AbstractCollection

METHOD DESCRIPTION
addAll(Collection<? Adds all of the elements in the specified collection to this collection
extends E> c) (optional operation).

containsAll Returns true if this collection contains all of the elements in the specified
(Collection<?> c) collection.
METHOD DESCRIPTION
retainAll(Collection<?> Retains only the elements in this collection that are contained in the
c) specified collection (optional operation).

toArray() Returns an array containing all of the elements in this collection.

Returns an array containing all of the elements in this collection; the


toArray(T[] a)
runtime type of the returned array is that of the specified array.

toString() Returns a string representation of this collection.

Methods declared in interface java.util.Collection

METHOD DESCRIPTION
parallelStream() Returns a possibly parallel Stream with this collection as its source.

removeIf(Predicate<?
super Removes all of the elements of this collection that satisfy the given
predicate.
E> filter)

stream() Returns a sequential Stream with this collection as its source.

Methods declared in class java.util.HashSet

METHOD DESCRIPTION
add(E e) Adds the specified element to this set if it is not already present.

clear() Removes all of the elements from this set.

Returns a shallow copy of this HashSet instance: the elements themselves are not
clone()
cloned.

contains(Object
Returns true if this set contains the specified element.
o)

isEmpty() Returns true if this set contains no elements.

iterator() Returns an iterator over the elements in this set.

remove(Object o) Removes the specified element from this set if it is present.

size() Returns the number of elements in this set (its cardinality).

Methods declared in interface java.lang.Iterable


METHOD DESCRIPTION

forEach(Consumer<?
super Performs the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.
T> action)

Methods declared in interface java.util.Set

METHOD DESCRIPTION

This method is used to add a specific element to the set. The function adds
add(element) the element only if the specified element is not already present in the set
else the function returns False if the element is already present in the Set.

This method is used to append all of the elements from the mentioned
addAll(Collection c) collection to the existing set. The elements are added randomly without
following any specific order.

This method is used to remove all the elements from the set but not delete
clear()
the set. The reference for the set still exists.

This method is used to check whether a specific element is present in the


contains(element)
Set or not.

This method is used to check whether the set contains all the elements
containsAll(Collection present in the given collection or not. This method returns true if the set
c) contains all the elements and returns false if any of the elements are
missing.

This method is used to get the hashCode value for this instance of the Set.
hashCode() It returns an integer value which is the hashCode value for this instance of
the Set.

isEmpty() This method is used to check whether the set is empty or not.
METHOD DESCRIPTION

This method is used to return the iterator of the set. The elements from the
iterator()
set are returned in random order.

This method is used to remove the given element from the set. This method
remove(element) returns True if the specified element is present in the Set otherwise it
returns False.

This method is used to remove all the elements from the collection which
removeAll(collection) are present in the set. This method returns true if this set changed as a result
of the call.

This method is used to retain all the elements from the set which are
retainAll(collection) mentioned in the given collection. This method returns true if this set
changed as a result of the call.

This method is used to get the size of the set. This returns an integer value
size()
which signifies the number of elements.

This method is used to form an array of the same elements as that of the
toArray()
Set.

Returns an array containing all of the elements in this set; the runtime type
toArray(T[] a)
of the returned array is that of the specified array.

Following is the difference between LinkedHashMap and LinkedHashSet:

Categories LinkedHashMap LinkedHashSet

Operation Usd to store key-value pairs. Used to store collection of things


Categories LinkedHashMap LinkedHashSet

Take unique an no duplicate keys but can


Duplicates Stores no duplicate element
takeduplicate values

Implements HashMap HashSet

Map<String, Integer> lhm = new Set<String> lhs = new


Example
LinkedHashMap<String, Integer>(); LinkedhashSet<String>();

Note: Keeping the insertion order in both LinkedHashmap and LinkedHashset have additional
associated costs, both in terms of spending additional CPU cycles and needing more memory. If
you do not need the insertion order maintained, it is recommended to use the lighter-
weight HashSet and HashMap instead.
Map Interface in Java

The map interface is present in java.util package represents a mapping between a key and a value. The
Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the
rest of the collection types. A map contains unique keys.

Geeks, the brainstormer should have been why and when to use Maps?
Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to
perform lookups by keys or when someone wants to retrieve and update elements by keys. Some
common scenarios are as follows:

 A map of error codes and their descriptions.


 A map of zip codes and cities.
 A map of managers and employees. Each manager (key) is associated with a list of employees (value) he
manages.
 A map of classes and students. Each class (key) is associated with a list of students (value).

Creating Map Objects

Since Map is an interface, objects cannot be created of the type map. We always need a class that extends
this map in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible
to restrict the type of object that can be stored in the Map.

Syntax: Defining Type-safe Map

Map hm = new HashMap();


// Obj is the type of the object to be stored in Map

Characteristics of a Map Interface

1. A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations
allow null key and null values like the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders, while HashMap does not.
3. There are two interfaces for implementing Map in java. They are Map and SortedMap, and three classes:
HashMap, TreeMap, and LinkedHashMap.

Methods in Map Interface


Method Action Performed

This method is used to clear and remove all of the elements or


clear()
mappings from a specified Map collection.

This method is used to check whether a particular key is being


containsKey(Object) mapped into the Map or not. It takes the key element as a
parameter and returns True if that element is mapped in the map.

This method is used to check whether a particular value is being


mapped by a single or more than one key in the Map. It takes the
containsValue(Object)
value as a parameter and returns True if that value is mapped by
any of the key in the map.

This method is used to create a set out of the same elements


entrySet() contained in the map. It basically returns a set view of the map or
we can create a new set and store the map elements into them.

This method is used to check for equality between two maps. It


equals(Object) verifies whether the elements of one map passed as a parameter is
equal to the elements of this map or not.

This method is used to retrieve or fetch the value mapped by a


get(Object) particular key mentioned in the parameter. It returns NULL when
the map contains no such mapping for the key.

This method is used to generate a hashCode for the given map


hashCode()
containing keys and values.

This method is used to check if a map is having any entry for key
isEmpty()
and value pairs. If no mapping exists, then this returns true.
Method Action Performed

This method is used to return a Set view of the keys contained in


keySet() this map. The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa.

This method is used to associate the specified value with the


put(Object, Object)
specified key in this map.

This method is used to copy all of the mappings from the specified
putAll(Map)
map to this map.

This method is used to remove the mapping for a key from this map
remove(Object)
if it is present in the map.

This method is used to return the number of key/value pairs


size()
available in the map.

This method is used to create a collection out of the values of the


values() map. It basically returns a Collection view of the values in the
HashMap.

getOrDefault(Object key, V Returns the value to which the specified key is mapped, or
defaultValue) defaultValue if this map contains no mapping for the key.

merge(K key, V value, BiFunction<?


If the specified key is not already associated with a value or is
super V,? super V,? extends V>
associated with null, associates it with the given non-null value.
remappingFunction)
Method Action Performed

If the specified key is not already associated with a value (or is


putIfAbsent(K key, V value) mapped to null) associates it with the given value and returns null,
else returns the curassociaterent value.

Example:

Java
// Java Program to Demonstrate
// Working of Map interface

// Importing required classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hm
= new HashMap<String, Integer>();

// Inserting pairs in above Map


// using put() method
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));

// Traversing through Map using for-each loop


for (Map.Entry<String, Integer> me :
hm.entrySet()) {

// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}

Output:

a:100
b:200
c:300
d:400

Classes that implement the Map interface are depicted in the below media and described later as
follows:

Class 1: HashMap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map
interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. This
class uses a technique called Hashing. Hashing is a technique of converting a large String to a small
String that represents the same String. A shorter value helps in indexing and faster searches. Let's see
how to create a map object using this class.

Example

Java
// Java Program to illustrate the Hashmap Class

// Importing required classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty HashMap


Map<String, Integer> map = new HashMap<>();

// Inserting entries in the Map


// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);

// Iterating over Map


for (Map.Entry<String, Integer> e : map.entrySet())

// Printing key-value pairs


System.out.println(e.getKey() + " "
+ e.getValue());
}
}

Output
vaibhav 20
vishal 10
sachin 30

Class 2: LinkedHashMap
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements
inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never
maintained the track and order of insertion which the LinkedHashMap provides where the elements
can be accessed in their insertion order. Let's see how to create a map object using this class.

Example
Java
// Java Program to Illustrate the LinkedHashmap Class

// Importing required classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty LinkedHashMap


Map<String, Integer> map = new LinkedHashMap<>();

// Inserting pair entries in above Map


// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);

// Iterating over Map


for (Map.Entry<String, Integer> e : map.entrySet())

// Printing key-value pairs


System.out.println(e.getKey() + " "
+ e.getValue());
}
}

Output:

vishal 10
sachin 30
vaibhav 20

Class 3: TreeMap
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the Abstract
Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at
map creation time, depending on which constructor is used. This proves to be an efficient way of sorting
and storing the key-value pairs. The storing order maintained by the treemap must be consistent with
equals just like any other sorted map, irrespective of the explicit comparators. Let's see how to create a
map object using this class.

Example

Java
// Java Program to Illustrate TreeMap Class

// Importing required classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty TreeMap


Map<String, Integer> map = new TreeMap<>();

// Inserting custom elements in the Map


// using put() method
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);

// Iterating over Map using for each loop


for (Map.Entry<String, Integer> e : map.entrySet())

// Printing key-value pairs


System.out.println(e.getKey() + " "
+ e.getValue());
}
}

Output:

sachin 30
vaibhav 20
vishal 10

Performing Various Operations using Map Interface and HashMap Class

Since Map is an interface, it can be used only with a class that implements this interface. Now, let’s see
how to perform a few frequently used operations on a Map using the widely used HashMap class. And
also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be
stored in the map.

Operation 1: Adding Elements

In order to add an element to the map, we can use the put() method. However, the insertion order is not
retained in the hashmap. Internally, for every element, a separate hash is generated and the elements
are indexed based on this hash to make it more efficient.

Example

Java

// Java program to demonstrate


// the working of Map interface

import java.util.*;
class GFG {
public static void main(String args[])
{
// Default Initialization of a
// Map
Map<Integer, String> hm1 = new HashMap<>();

// Initialization of a Map
// using Generics
Map<Integer, String> hm2
= new HashMap<Integer, String>();

// Inserting the Elements


hm1.put(1, "Geeks");
hm1.put(2, "For");
hm1.put(3, "Geeks");

hm2.put(new Integer(1), "Geeks");


hm2.put(new Integer(2), "For");
hm2.put(new Integer(3), "Geeks");

System.out.println(hm1);
System.out.println(hm2);
}
}

Output:

{1=Geeks, 2=For, 3=Geeks}


{1=Geeks, 2=For, 3=Geeks}

Operation 2: Changing Element

After adding the elements if we wish to change the element, it can be done by again adding the element
with the put() method. Since the elements in the map are indexed using the keys, the value of the key
can be changed by simply inserting the updated value for the key for which we wish to change.

Example

Java

// Java program to demonstrate


// the working of Map interface

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

// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();

// Inserting the Elements


hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "Geeks");
hm1.put(new Integer(3), "Geeks");

System.out.println("Initial Map " + hm1);


hm1.put(new Integer(2), "For");

System.out.println("Updated Map " + hm1);


}
}

Output:

Initial Map {1=Geeks, 2=Geeks, 3=Geeks}


Updated Map {1=Geeks, 2=For, 3=Geeks}

Operation 3: Removing Elements

In order to remove an element from the Map, we can use the remove() method. This method takes the
key value and removes the mapping for a key from this map if it is present in the map.

Example

Java

// Java program to demonstrate


// the working of Map interface

import java.util.*;
class GFG {

public static void main(String args[])


{

// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();

// Inserting the Elements


hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");
hm1.put(new Integer(4), "For");

// Initial Map
System.out.println(hm1);
hm1.remove(new Integer(4));

// Final Map
System.out.println(hm1);
}
}

Output:

{1=Geeks, 2=For, 3=Geeks, 4=For}


{1=Geeks, 2=For, 3=Geeks}

Operation 4: Iterating through the Map

There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and
get the keys. The value of the key is found by using the getValue() method.

Example

Java

// Java program to demonstrate


// the working of Map interface

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

// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();

// Inserting the Elements


hm1.put(new Integer(1), "Geeks");
hm1.put(new Integer(2), "For");
hm1.put(new Integer(3), "Geeks");

for (Map.Entry mapElement : hm1.entrySet()) {


int key
= (int)mapElement.getKey();

// Finding the value


String value
= (String)mapElement.getValue();

System.out.println(key + " : "


+ value);
}
}
}

Output:

1 : Geeks
2 : For
3 : Geeks

HashMap and TreeMap in Java

HashMap and TreeMap are part of collection framework.

HashMap

java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value
pair<Key, Value>.

HashMap<K, V> hmap = new HashMap<K, V>();

Let us consider below example where we have to count occurrences of each integer in given array of
integers.

Input: arr[] = {10, 3, 5, 10, 3, 5, 10};


Output: Frequency of 10 is 3
Frequency of 3 is 2
Frequency of 5 is 2

Java
/* Java program to print frequencies of all elements using
HashMap */
import java.util.*;

class Main
{
// This function prints frequencies of all elements
static void printFreq(int arr[])
{
// Creates an empty HashMap
HashMap<Integer, Integer> hmap =
new HashMap<Integer, Integer>();

// Traverse through the given array


for (int i = 0; i < arr.length; i++)
{
Integer c = hmap.get(arr[i]);

// If this is first occurrence of element


if (hmap.get(arr[i]) == null)
hmap.put(arr[i], 1);

// If elements already exists in hash map


else
hmap.put(arr[i], ++c);
}

// Print result
for (Map.Entry m:hmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}

// Driver method to test above method


public static void main (String[] args)
{
int arr[] = {10, 34, 5, 10, 3, 5, 10};
printFreq(arr);
}
}
Output:
Frequency of 34 is 1
Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3

Key Points

 HashMap does not maintain any order neither based on key nor on basis of value, If we want the
keys to be maintained in a sorted order, we need to use TreeMap.
 Complexity: get/put/containsKey() operations are O(1) in average case but we can’t guarantee
that since it all depends on how much time does it take to compute the hash.

Application:
HashMap is basically an implementation of hashing. So wherever we need hashing with key value pairs,
we can use HashMap. For example, in Web Applications username is stored as a key and user data is
stored as a value in the HashMap, for faster retrieval of user data corresponding to a username.

TreeMap

TreeMap can be a bit handy when we only need to store unique elements in a sorted order.
Java.util.TreeMap uses a red-black tree in the background which makes sure that there are no
duplicates; additionally it also maintains the elements in a sorted order.

TreeMap<K, V> hmap = new TreeMap<K, V>();

Below is TreeMap based implementation of same problem. This solution has more time complexity
O(nLogn) compared to previous one which has O(n). The advantage of this method is, we get elements
in sorted order.

Java

/* Java program to print frequencies of all elements using


TreeMap */
import java.util.*;
class Main
{
// This function prints frequencies of all elements
static void printFreq(int arr[])
{
// Creates an empty TreeMap
TreeMap<Integer, Integer> tmap =
new TreeMap<Integer, Integer>();

// Traverse through the given array


for (int i = 0; i < arr.length; i++)
{
Integer c = tmap.get(arr[i]);

// If this is first occurrence of element


if (tmap.get(arr[i]) == null)
tmap.put(arr[i], 1);

// If elements already exists in hash map


else
tmap.put(arr[i], ++c);
}

// Print result
for (Map.Entry m:tmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}

// Driver method to test above method


public static void main (String[] args)
{
int arr[] = {10, 34, 5, 10, 3, 5, 10};
printFreq(arr);
}
}
Output:
Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3
Frequency of 34 is 1
Key Points

 For operations like add, remove, containsKey, time complexity is O(log n where n is number of
elements present in TreeMap.

 TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a
HashMap have no order. TreeMap also provides some cool methods for first, last, floor and
ceiling of keys.

Overview:

1. HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted
Map interface is a child of Map.
2. HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing
Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search
Tree apply here.
3. Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet
implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly
used to see presence/absence in a set. For above problem, we can't use HashSet (or TreeSet) as
we can't store counts. An example problem where we would prefer HashSet (or TreeSet) over
HashMap (or TreeMap) is to print all distinct elements in an array.
LinkedHashMap in Java

The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but
it never maintained the track and order of insertion, which the LinkedHashMap provides where the
elements can be accessed in their insertion order.

Important Features of a LinkedHashMap are listed as follows:

 A LinkedHashMap contains values based on the key. It implements the Map interface and
extends the HashMap class.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It is non-synchronized.
 It is the same as HashMap with an additional feature that it maintains insertion order. For
example, when we run the code with a HashMap, we get a different order of elements.

Declaration:

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

Here, K is the key Object type and V is the value Object type

 K – The type of the keys in the map.


 V – The type of values mapped in the map.

It implements Map<K, V> interface, and extends HashMap<K, V> class. Though the Hierarchy of
LinkedHashMap is as depicted in below media as follows:
How LinkedHashMap Work Internally?

A LinkedHashMap is an extension of the HashMap class and it implements the Map interface.
Therefore, the class is declared as:
public class LinkedHashMap
extends HashMap
implements Map

In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap is very
similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is represented as:

 Hash: All the input keys are converted into a hash which is a shorter form of the key so that the
search and insertion are faster.
 Key: Since this class extends HashMap, the data is stored in the form of a key-value pair.
Therefore, this parameter is the key to the data.
 Value: For every key, there is a value associated with it. This parameter stores the value of the
keys. Due to generics, this value can be of any form.
 Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next
node of the LinkedHashMap.
 Previous: This parameter contains the address to the previous node of the LinkedHashMap.

Synchronized LinkedHashMap

The implementation of LinkedHashMap is not synchronized. If multiple threads access a linked hash
map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized
externally. This is typically accomplished by synchronizing on some object that naturally encapsulates
the map. If no such object exists, the map should be "wrapped" using
the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental
unsynchronized access to the map:

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

Constructors of LinkedHashMap Class

In order to create a LinkedHashMap, we need to create an object of the LinkedHashMap class. The
LinkedHashMap class consists of various constructors that allow the possible creation of the ArrayList.
The following are the constructors available in this class:

1. LinkedHashMap(): This is used to construct a default LinkedHashMap constructor.


LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>();

2. LinkedHashMap(int capacity): It is used to initialize a particular LinkedHashMap with a specified


capacity.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity);

3. LinkedHashMap(Map<? extends K,? extends V> map): It is used to initialize a particular


LinkedHashMap with the elements of the specified map.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(Map<? extends K,? extends V> map)
;

4. LinkedHashMap(int capacity, float fillRatio): It is used to initialize both the capacity and fill ratio
for a LinkedHashMap. A fillRatio also called as loadFactor is a metric that determines when to increase
the size of the LinkedHashMap automatically. By default, this value is 0.75 which means that the size of
the map is increased when the map is 75% full.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity, float fillRatio);

5. LinkedHashMap(int capacity, float fillRatio, boolean Order): This constructor is also used to
initialize both the capacity and fill ratio for a LinkedHashMap along with whether to follow the insertion
order or not.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity, float fillRatio, bo


olean Order);

Here, For the Order attribute, true is passed for the last access order and false is passed for the
insertion order.

Methods of LinkedHashMap

METHOD DESCRIPTION
Returns true if this map maps one or more keys to the specified
containsValue(Object value)
value.

entrySet() Returns a Set view of the mappings contained in this map.

Returns the value to which the specified key is mapped, or null if


get(Object key)
this map contains no mapping for the key.

keySet() Returns a Set view of the keys contained in this map.

removeEldestEntry
Returns true if this map should remove its eldest entry.
(Map.Entry<K,V> eldest)

values() Returns a Collection view of the values contained in this map.

Application: Since the LinkedHashMap makes use of Doubly LinkedList to maintain the
insertion order, we can implement LRU Cache functionality by overriding
the removeEldestEntry() method to impose a policy for automatically removing stale when
new mappings are added to the map. This lets you expire data using some criteria that you
define.
Example:

Java
// Java Program to Demonstrate Working of LinkedHashMap

// Importing required classes


import java.util.*;

// LinkedHashMapExample
public class GFG {

// Main driver method


public static void main(String a[])
{

// Creating an empty LinkedHashMap


LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();

// Adding entries in Map


// using put() method
lhm.put("one", "practice.geeksforgeeks.org");
lhm.put("two", "code.geeksforgeeks.org");
lhm.put("four", "quiz.geeksforgeeks.org");

// Printing all entries inside Map


System.out.println(lhm);

// Note: It prints the elements in same order


// as they were inserted

// Getting and printing value for a specific key


System.out.println("Getting value for key 'one': "
+ lhm.get("one"));

// Getting size of Map using size() method


System.out.println("Size of the map: "
+ lhm.size());

// Checking whether Map is empty or not


System.out.println("Is map empty? "
+ lhm.isEmpty());
// Using containsKey() method to check for a key
System.out.println("Contains key 'two'? "
+ lhm.containsKey("two"));

// Using containsKey() method to check for a value


System.out.println(
"Contains value 'practice.geeks"
+ "forgeeks.org'? "
+ lhm.containsValue("practice"
+ ".geeksforgeeks.org"));

// Removing entry using remove() method


System.out.println("delete element 'one': "
+ lhm.remove("one"));

// Printing mappings to the console


System.out.println("Mappings of LinkedHashMap : "
+ lhm);
}
}

Output
{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeek
s.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
Mappings of LinkedHashMap : {two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.or
g}

Various operations on the LinkedHashMap class

Let’s see how to perform a few frequently used operations on the LinkedHashMap class instance.

Operation 1: Adding Elements

In order to add an element to the LinkedHashMap, we can use the put() method. This is different from
HashMap because in HashMap, the insertion order is not retained but it is retained in the
LinkedHashMap.
Example

Java
// Java Program to Demonstrate Adding
// Elements to a LinkedHashMap

// Importing required classes


import java.util.*;

// Main class
// AddElementsToLinkedHashMap
class GFG {

// Main driver method


public static void main(String args[])
{

// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm1
= new LinkedHashMap<Integer, String>();

// Add mappings to Map


// using put() method
hm1.put(3, "Geeks");
hm1.put(2, "For");
hm1.put(1, "Geeks");

// Printing mappings to the console


System.out.println("Mappings of LinkedHashMap : "
+ hm1);
}
}

Output
Mappings of LinkedHashMap : {3=Geeks, 2=For, 1=Geeks}

Operation 2: Changing/Updating Elements

After adding elements if we wish to change the element, it can be done by again adding the element
using the put() method. Since the elements in the LinkedHashMap are indexed using the keys, the value
of the key can be changed by simply re-inserting the updated value for the key for which we wish to
change.
Example

Java
// Java Program to Demonstrate Updation of Elements
// of LinkedHashMap

import java.util.*;

// Main class
// UpdatingLinkedHashMap
class GFG {

// Main driver method


public static void main(String args[])
{

// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();

// Inserting mappings into Map


// using put() method
hm.put(3, "Geeks");
hm.put(2, "Geeks");
hm.put(1, "Geeks");

// Printing mappings to the console


System.out.println("Initial map : " + hm);

// Updating the value with key 2


hm.put(2, "For");

// Printing the updated Map


System.out.println("Updated Map : " + hm);
}
}

Output
Initial map : {3=Geeks, 2=Geeks, 1=Geeks}
Updated Map : {3=Geeks, 2=For, 1=Geeks}

Operation 3: Removing Element


In order to remove an element from the LinkedHashMap, we can use the remove() method. This method
takes the value of key as input, searches for existence of such key and then removes the mapping for
the key from this LinkedHashMap if it is present in the map. Apart from that, we can also remove the
first entered element from the map if the maximum size is defined.

Example

Java
// Java program to Demonstrate Removal of Elements
// from LinkedHashMap

// Importing utility classes


import java.util.*;

// Main class
// RemovingMappingsFromLinkedHashMap
class GFG {

// Main driver method


public static void main(String args[])
{
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();

// Inserting the Elements


// using put() method
hm.put(3, "Geeks");
hm.put(2, "Geeks");
hm.put(1, "Geeks");
hm.put(4, "For");

// Printing the mappings to the console


System.out.println("Initial Map : " + hm);

// Removing the mapping with Key 4


hm.remove(4);

// Printing the updated map


System.out.println("Updated Map : " + hm);
}
}

Output
Initial Map : {3=Geeks, 2=Geeks, 1=Geeks, 4=For}
Updated Map : {3=Geeks, 2=Geeks, 1=Geeks}

Operation 4: Iterating through the LinkedHashMap

There are multiple ways to iterate through the LinkedHashMap. The most famous way is to use a for-
each loop over the set view of the map (fetched using map.entrySet() instance method). Then for each
entry (set element) the values of key and value can be fetched usingthe getKey() and
the getValue() method.

Example

Java
// Java program to demonstrate
// Iterating over LinkedHashMap

// Importing required classes


import java.util.*;

// Main class
// IteratingOverLinkedHashMap
class GFG {

// Main driver method


public static void main(String args[])
{

// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();

// Inserting elements into Map


// using put() method
hm.put(3, "Geeks");
hm.put(2, "For");
hm.put(1, "Geeks");

// For-each loop for traversal over Map


for (Map.Entry<Integer, String> mapElement :
hm.entrySet()) {
Integer key = mapElement.getKey();

// Finding the value


// using getValue() method
String value = mapElement.getValue();

// Printing the key-value pairs


System.out.println(key + " : " + value);
}
}
}

Output
3 : Geeks
2 : For
1 : Geeks

Articles (4)

Java.util.Dictionary Class in Java

Calendar Class in Java with examples

Java.util.GregorianCalendar Class in Java

Date class in Java (With Examples)

Java.util.Dictionary Class in Java

util.Dictionary is an abstract class, representing a key-value relation and works similar to a map.
Given a key you can store values and when needed can retrieve the value back using its key. Thus, it is
a list of key-value pair.

Declaration

public abstract class Dictionary extends Object

Constructors:
Dictionary() Sole constructor.

Methods of util.Dictionary Class :


1. put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair to the dictionary.

Syntax :

public abstract V put(K key, V value)


Parameters :
-> key
-> value
Return :
key-value pair mapped in the dictionary

2. elements() : java.util.Dictionary.elements() returns value representation in dictionary.

Syntax :

public abstract Enumeration elements()


Parameters :
--------
Return :
value enumeration in dictionary

3. get(Object key) : java.util.Dictionary.get(Object key) returns the value that is mapped with the
argumented key in the dictionary.

Syntax :

public abstract V get(Object key)


Parameters :
key - key whose mapped value we want
Return :
value mapped with the argumented key

4. isEmpty() : java.util.Dictionary.isEmpty() checks whether the dictionary is empty or not.

Syntax :

public abstract boolean isEmpty()


Parameters :
------
Return :
true, if there is no key-value relation in the dictionary; else false

5. keys() : java.util.Dictionary.keys() returns key representation in dictionary.

Syntax :

public abstract Enumeration keys()


Parameters :
--------
Return :
key enumeration in dictionary

6. remove(Object key) : java.util.Dictionary.remove(Object key) removes the key-value pair


mapped with the argumented key.

Syntax :

public abstract V remove(Object key)


Parameters :
key : key to be removed
Return :
value mapped with the key

7. size() : java.util.Dictionary.size() returns the no. of key-value pairs in the Dictionary.

Syntax :

public abstract int size()


Parameters :
-------
Return :
returns the no. of key-value pairs in the Dictionary

Java

// Java Program explaining util.Dictionary class Methods


// put(), elements(), get(), isEmpty(), keys()
// remove(), size()

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

// Initializing a Dictionary
Dictionary geek = new Hashtable();

// put() method
geek.put("123", "Code");
geek.put("456", "Program");
// elements() method :
for (Enumeration i = geek.elements(); i.hasMoreElements();)
{
System.out.println("Value in Dictionary : " + i.nextElement());
}

// get() method :
System.out.println("\nValue at key = 6 : " + geek.get("6"));
System.out.println("Value at key = 456 : " + geek.get("123"));

// isEmpty() method :
System.out.println("\nThere is no key-value pair : " + geek.isEmpty() +
"\n");

// keys() method :
for (Enumeration k = geek.keys(); k.hasMoreElements();)
{
System.out.println("Keys in Dictionary : " + k.nextElement());
}

// remove() method :
System.out.println("\nRemove : " + geek.remove("123"));
System.out.println("Check the value of removed key : " +
geek.get("123"));

System.out.println("\nSize of Dictionary : " + geek.size());

}
}

Output:

Value in Dictionary : Code


Value in Dictionary : Program

Value at key = 6 : null


Value at key = 456 : Code

There is no key-value pair : false

Keys in Dictionary : 123


Keys in Dictionary : 456
Remove : Code
Check the value of removed key : null

Size of Dictionary : 1

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.

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)

Java program to demonstrate getInstance() method:


Java

// Date getTime(): It is used to return a


// Date object representing this
// Calendar's time value.

import java.util.*;
public class Calendar1 {
public static void main(String args[])
{
Calendar c = Calendar.getInstance();
System.out.println("The Current Date is:" + c.getTime());
}
}

Output:

The Current Date is:Tue Aug 28 11:10:40 UTC 2018


Important Methods and their usage

METHOD DESCRIPTION

abstract void add(int field, int It is used to add or subtract the specified amount of time to the given
amount) calendar field, based on the calendar's rules.

int get(int field) It is used to return the value of the given calendar field.

abstract int getMaximum(int It is used to return the maximum value for the given calendar field of
field) this Calendar instance.
METHOD DESCRIPTION

abstract int getMinimum(int It is used to return the minimum value for the given calendar field of this
field) Calendar instance.

It is used to return a Date object representing this Calendar's time


Date getTime()
value.</td

Below programs illustrate the above methods:

Program 1: Java program to demonstrate get() method.

Java

// Program to demonstrate get() method


// of Calendar class

import java.util.*;
public class Calendar2 {
public static void main(String[] args)
{
// creating Calendar object
Calendar calendar = Calendar.getInstance();

// Demonstrate Calendar's get()method


System.out.println("Current Calendar's Year: " +
calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " +
calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
}
}

Output:

Current Calendar's Year: 2018


Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
Program 2: Java program to demonstrate getMaximum() method.
Java

// Program to demonstrate getMaximum() method


// of Calendar class

import java.util.*;
public class Calendar3 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();

int max = calendar.getMaximum(Calendar.DAY_OF_WEEK);


System.out.println("Maximum number of days in a week: " + max);

max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in a year: " + max);
}
}

Output:

Maximum number of days in a week: 7


Maximum number of weeks in a year: 53

Program 3: Java program to demonstrate the getMinimum() method.


Java

// Program to demonstrate getMinimum() method


// of Calendar class

import java.util.*;
public class Calendar4 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();

int min = calendar.getMinimum(Calendar.DAY_OF_WEEK);


System.out.println("Minimum number of days in week: " + min);

min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + min);
}
}

Output:

Minimum number of days in week: 1


Minimum number of weeks in year: 1

Program 4: Java program to demonstrate add() method.


Java

// Program to demonstrate add() method


// of Calendar class

import java.util.*;
public class Calendar5 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}

Output:

15 days ago: Mon Aug 13 11:10:57 UTC 2018


4 months later: Thu Dec 13 11:10:57 UTC 2018
2 years later: Sun Dec 13 11:10:57 UTC 2020

Java.util.GregorianCalendar Class in Java

Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()


GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited
members either from interface or abstract class) of a Calendar that implements the most widely used
Gregorian Calendar with which we are familiar.

java.util.GregorianCalendar vs java.util.Calendar

The major difference between GregorianCalendar and Calendar classes are that the Calendar Class
being an abstract class cannot be instantiated. So an object of the Calendar Class is initialized as:

Calendar cal = Calendar.getInstance();

Here, an object named cal of Calendar Class is initialized with the current date and time in the default
locale and timezone. Whereas, GregorianCalendar Class being a concrete class, can be instantiated. So
an object of the GregorianCalendar Class is initialized as:

GregorianCalendar gcal = new GregorianCalendar();

Here, an object named gcal of GregorianCalendar Class is initialized with the current date and time in
the default locale and timezone.
Fields defined :

GregorianCalendar Class defines two fields:


AD : referring to the common era(anno Domini)
BC : referring to before common era(Before Christ)

Constructors : There are several constructors for GregorianCalendar objects. Broadly classifying,
constructors for GregorianCalendar either initialize the object with the user specified date and/or
time in the default locale and time zone, or initialize the object with default date and time in the
user specified locale and/or time zone. These are as follows:

Constructor Signature Description

initializes the object with the current


GregorianCalendar() date and time in the default locale and
time zone
Constructor Signature Description

initializes the object with the date-set


GregorianCalendar(int year, int month,
passed as parameters in the default
int dayOfMonth)
locale and time zone

initializes the object with the date and


GregorianCalendar(int year, int month,
time-set passed as parameters in the
int dayOfMonth, int hours, int minutes)
default locale and time zone

initializes the object with the date and


GregorianCalendar(int year, int month, more specific time-set passed as
int dayOfMonth, int hours, int minutes, int seconds) parameters in the default locale and time
zone

initializes the object with the current


GregorianCalendar(Locale locale) date and time in the default time zone
and the locale passed as parameters

initializes the object with the current


GregorianCalendar(TimeZone timeZone) date and time in the default locale and
the time zone passed as parameters

initializes the object with the current


GregorianCalendar(TimeZone timeZone,
date and time in the locale and the time
Locale locale)
zone passed as parameters

Methods from(), toZonedDateTime(), getCalendarType() were introduced in JDK 8.

Java

// Java Program to show that Calendar class with


// default instantiation and GregorianCalendar class
// with default constructor is basically the same as both
// return the Gregorian Calendar for the default
// date, time, time zone and locale
import java.util.Calendar;
import java.util.GregorianCalendar;

class CalendarGFG {
public static void main(String[] args)
{
// Creating an object of Calendar Class
Calendar cal = Calendar.getInstance();

/* Creating an object of
GregorianCalendar Class */
GregorianCalendar gcal = new GregorianCalendar();

/* Displaying Current Date using


Calendar Class */
System.out.println("Calendar date: "
+ cal.getTime());

/* Displaying Current Date using


GregorianCalendar Class */
System.out.print("Gregorian date: "
+ gcal.getTime());
} // end of main function
} // end of class

Output:

Calendar date: Sat Apr 28 13:36:37 UTC 2018


Gregorian date: Sat Apr 28 13:36:37 UTC 2018

Example to demonstrate the usage of various constructors:


1. Using default constructor

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class GregorianCalendarGFG {
public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of GregorianCalendar class


using default constructor*/
GregorianCalendar gcal = new GregorianCalendar();

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: " + gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: "
+ Locale.getDefault().getDisplayName());
} // end of main function
} // end of class

Output:

Date: Apr 30, 2018


Time: 10:21:51 PM
Time Zone: Coordinated Universal Time
Locale: English (United States)

2. By passing year, month, dayOfMonth as parameters:

Java
// Java program to demonstrate simple GregorianCalendar
// operations
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarGFG {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of GregorianCalendar class


by specifying year, month and dayOfMonth */
GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30);

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: " + gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: "
+ Locale.getDefault().getDisplayName());
} // end of main function
} // end of class

Output:

Date: Apr 30, 2018


Time: 0:0:0 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)

3. By passing year, month, dayOfMonth, hourOfDay, minute:

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarGFG {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of GregorianCalendar class


by specifying year, month, dayOfMonth,
hourOfDay and minute */
GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21);

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: " + gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: "
+ Locale.getDefault().getDisplayName());
} // end of main function
} // end of class

Output:

Date: Apr 30, 2018


Time: 10:21:0 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)

4. By passing year, month, dayOfMonth, hourOfDay, minute, second:

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarGFG {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of GregorianCalendar class


by specifying year, month, dayOfMonth,
hourOfDay, minute and second */
GregorianCalendar gcal = new GregorianCalendar(2018, 3, 30, 10, 21,
51);
// displaying the date, time, time zone and locale
System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: " + gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: "
+ Locale.getDefault().getDisplayName());
} // end of main function
} // end of class

Output:

Date: Apr 30, 2018


Time: 10:21:51 AM
Time Zone: Coordinated Universal Time
Locale: English (United States)

5. By passing timeZone as parameter:

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.TimeZone;
import java.util.Locale;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarTest {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };
// declaring an array to store AM or PM
String amPm[] = { "AM", "PM" };

/* Creating an object of TimeZone class to create


an object of GregorianCalendar class to assign
an user defined time zone (GMT + 5:30)*/
TimeZone tz = TimeZone.getTimeZone("GMT+5:30");
GregorianCalendar gcal = new GregorianCalendar(tz);

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: " + gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: " +
Locale.getDefault().getDisplayCountry());
} // end of main function
} // end of class

Output:

Date: May 1, 2018


Time: 4:24:7 AM
Time Zone: GMT+05:30
Locale: United States

6. By passing the locale as a parameter:

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.TimeZone;
import java.util.Locale;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarTest {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of Locale class to create


an object of GregorianCalendar class to assign
an user defined locale (India)*/
Locale l = new Locale("en", "IN");
GregorianCalendar gcal = new GregorianCalendar(l);

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: "
+ gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: " + l.getDisplayCountry());
} // end of main function
} // end of class

Output:

Date: Apr 30, 2018


Time: 10:58:30 PM
Time Zone: Coordinated Universal Time
Locale: India
7. By passing timeZone and locale as parameters:

Java

// Java program to demonstrate simple GregorianCalendar


// operations
import java.util.TimeZone;
import java.util.Locale;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class GregorianCalendarTest {


public static void main(String args[])
{
// declaring an array to store month abbreviations
String month[] = { "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };

// declaring an array to store AM or PM


String amPm[] = { "AM", "PM" };

/* Creating an object of TimeZone class and Locale


class to create an object of GregorianCalendar
class to assign an user defined time zone
(GMT + 5:30) and locale (India)*/
TimeZone tz = TimeZone.getTimeZone("GMT+5:30");
Locale l = new Locale("en", "IN");
GregorianCalendar gcal = new GregorianCalendar(tz, l);

// displaying the date, time, time zone and locale


System.out.print("Date: "
+ month[gcal.get(Calendar.MONTH)] + " "
+ gcal.get(Calendar.DATE) + ", "
+ gcal.get(Calendar.YEAR) + "\n"
+ "Time: "
+ gcal.get(Calendar.HOUR) + ":"
+ gcal.get(Calendar.MINUTE) + ":"
+ gcal.get(Calendar.SECOND) + " "
+ amPm[gcal.get(Calendar.AM_PM)] + "\n"
+ "Time Zone: "
+ gcal.getTimeZone().getDisplayName()
+ "\n"
+ "Locale: " + l.getDisplayCountry());
} // end of main function
} // end of class

Output:

Date: May 1, 2018


Time: 4:34:59 AM
Time Zone: GMT+05:30
Locale: India

Date class in Java (With Examples)

The class Date represents a specific instant in time, with millisecond precision. The Date class of java.util
package implements Serializable, Cloneable and Comparable interface. It provides constructors and
methods to deal with date and time with java.

Constructors

 Date() : Creates date object representing current date and time.


 Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970,
00:00:00 GMT.
 Date(int year, int month, int date)
 Date(int year, int month, int date, int hrs, int min)
 Date(int year, int month, int date, int hrs, int min, int sec)
 Date(String s)

Note : The last 4 constructors of the Date class are Deprecated.Java

// Java program to demonstrate constuctors of Date


import java.util.*;

public class Main


{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2 );
}
}
Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970

Important Methods

o boolean after(Date date) : Tests if current date is after the given date.
o boolean before(Date date) : Tests if current date is before the given date.
o int compareTo(Date date) : Compares current date with given date. Returns 0 if the
argument Date is equal to the Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after the Date argument.
o long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00
GMT represented by this Date object.
o void setTime(long time) : Changes the current date and time to given time.

Java

// Program to demonstrate methods of Date class


import java.util.*;

public class Main


{
public static void main(String[] args)
{
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);

boolean a = d3.after(d1);
System.out.println("Date d3 comes after " +
"date d2: " + a);

boolean b = d3.before(d2);
System.out.println("Date d3 comes before "+
"date d2: " + b);

int c = d1.compareTo(d2);
System.out.println(c);

System.out.println("Miliseconds from Jan 1 "+


"1970 to date d1 is " + d1.getTime());

System.out.println("Before setting "+d2);


d2.setTime(204587433443L);
System.out.println("After setting "+d2);
}
}
Output:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976

You might also like