Professional Documents
Culture Documents
Java PDF
Java PDF
48 Articles
13 Problems
15 MCQ's
Learn
12 Articles
11 Problems
10 MCQ's
Learn
12 Articles
5 Problems
10 MCQ's
Learn
6 Articles
5 Problems
10 MCQ's
Learn
7 Articles
7 Problems
10 MCQ's
Learn
Module 6 (Misc) - Java
4 Articles
3 Problems
10 MCQ's
Articles (48)
Does JVM create object of Main class (the class with main())?
Java Identifiers
enum in Java
Variables in Java
Scope of Variables In Java
Operators in Java
Loops in Java
Comments in 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 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++).
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
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:
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
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).
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
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.
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.
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.
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.
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.
Type 3: Variables
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.
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:
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.
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:
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.
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
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
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.
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
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.
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.
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.
Loading
Linking
Initialization
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.
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.
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;
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.
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());
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.
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.
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())?
class Main {
public static void main(String args[])
{
System.out.println("Hello");
}
}
Output:
Hello
Java
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.
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.
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
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 :
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.
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :
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 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.
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.
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;
Example:
Java
// Java Program to Demonstrate Boolean Primitive DataType
// Class
class GFG {
//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;
Default Value: 0
Example:
Java
// Java Program to demonstrate Byte Data Type
// Class
class GFG {
byte a = 126;
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;
Type 4: int
Syntax:
int intVar;
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;
Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775, 807} (inclusive)
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;
Java
// Java Program to Illustrate Float Primitive Data Type
// Class
class GFG {
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;
Note:
Type 8: char
Syntax:
char charVar;
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[])
{
short s = 56;
//need to hold big range of numbers then we need this data type
long l = 12121;
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
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.
Example:
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.
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
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
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
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.
Example 2:
Java
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
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;
}
Output
RED
Java
// enum declaration inside a class.
// 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
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;
}
// Constructor
public Test(Day day) { this.day = day; }
// 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
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.
Java
// Java program to demonstrate working of values(),
// ordinal() and valueOf()
enum Color {
RED,
GREEN,
BLUE;
}
Output
RED at index 0
GREEN at index 1
BLUE at index 2
RED
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.
Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.
Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color
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
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
// getter method
public String getAction()
{
return this.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();
Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
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.
Syntax:
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 {
Output:
Example 2:
Java
// Java Program to Illustrate appendCodePoint() Method
// of StringBuffer class
Output:
Example 3:
Java
// Java program to illustrate appendCodePoint() Method
// of StringBuffer class
// Main class
public class GFG {
Output:
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.
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
Illustrations:
float simpleInterest;
// Declaring float variable
int time = 10, speed = 20;
// Declaring and initializing integer variable
char var = 'h';
// Declaring and initializing character variable
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
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 GFG()
{ // Default Constructor
// 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
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 {
Output
Geek Name is : Shubham Jain
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.
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
Must Read:
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 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.
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:
Default (no
modifier) Yes No No
private No No No
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;
}
}
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.
Java
Output:
Test.x: 22
t.x: 22
t.y: 33
y: 44
Java
// System.out.println(x);
}
}
Output:
10
Java
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}
Output:
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.
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
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
A final variable in Java can be assigned a value only once, we can assign a value either in declaration or
later.
A blank final variable in Java is a final variable that is not initialized during declaration. Below is a
simple example of blank final.
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);
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()
{
// Calling Test(int val)
this(10);
}
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
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.
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
private T objRef;
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");
}
}
}
}
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
private T objRef;
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");
}
}
Output :
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;
interface B
{
public void displayClass();
}
class A implements B
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}
}
}
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
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.
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.
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,
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
&&, 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 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;
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-
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-
Java
// Java program to illustrate
// instance of operator
class operators {
public static void main(String[] args)
{
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 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;
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.
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 :
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.
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
// 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;
}
Output :
0.0
0.0
20.0
20.0
Explanation :
First let us understand what the following fragment does in above program.
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.
Here, b1 has been set to null, but b2 still points to the original object.
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.
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.
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:
Example:
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:
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:
~ 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
// 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);
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"
};
// 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
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:
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.
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 {
int x = -4;
System.out.println(x >> 1);
int y = 4;
System.out.println(y >> 1);
}
}
Output
-2
2
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 {
Output
7
3
1
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
// Main class
class GFG {
public static void main(String[] args)
{
Output
true
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 {
// 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");
Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object
Java
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:
Java
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:
Java
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
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;
}
// Driver class
class Test
{
public static void main(String[] args)
{
Parent cobj = new Child();
Parent par = cobj;
Output:
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.
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
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
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;
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.
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 {
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");
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.
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.
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:
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
// Main class
class GFG {
// Expression 1 (using ?: )
// Automatic promotion in conditional expression
Object o1 = true ? new Integer(4) : new Float(2.0);
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 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
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
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
Input:
101
223
238
892
99
500
728
Output:
Mean: 397
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 {
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)
{
// Print statements
System.out.println("The command line"
+ " arguments are:");
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.
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.
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
// Main class
public class GFG {
int temp;
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
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}
Output:
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)
Return Value: The function returns an object-valued Stream consisting of the results of applying the
given function.
Example 1 :
Java
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);
}
}
Output:
39.303999999999995
91.125
300.76300000000003
704.969
Example 2 :
Java
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);
Output:
13.4
14.5
16.7
18.9
Related Articles :
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
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
System.out.println("Enter an integer");
System.out.println("Enter a String");
Output:
Let us try the same using Buffer class and same Input below as follows:
Example 2:
Java
// Java Program to Illustrate BufferedReader Class
// Main class
class GFG {
System.out.println("Enter an integer");
System.out.println("Enter a String");
String b = br.readLine();
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
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)
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);
float n = 5.2f;
n = 2324435.3f;
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
Java
// Java program to demonstrate working of DecimalFormat
import java.text.DecimalFormat;
class JavaFormatter2 {
public static void main(String args[])
{
double num = 123.4567;
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
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);
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);
}
}
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;
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);
}
}
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 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();
}
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;
}
}
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 Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
if (neg)
return -ret;
return ret;
}
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;
}
In Java, there are four different ways for reading input from the user in the command line
environment(console).
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));
Input:
Geek
Output:
Geek
Note:
To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple
values, we use split().
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
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:
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:
Input:
GeeksforGeeks
Output:
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:");
javac GFG1.java
java Main Hello World
Output:
Loops in Java
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 :
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:
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
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
Output:
It's commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:
is equivalent to:
Java
Output:
1. For-each loops are not appropriate when you want to modify the array:
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
}
}
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");
}
}
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.
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;
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
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
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
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.
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;
Output
1 3 5 7 9
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;
Output
Before the return.
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.
case value2 :
// Statements
break; // break is optional
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 {
// 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
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 {
// 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";
}
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 {
// Switch case
switch (year) {
// Case
case 1:
System.out.println(
"elective courses : Advance english, Algebra");
// Case
case 2:
// 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 }
// Switch case
switch (Now) {
// Case 1
case Sun:
System.out.println("Sunday");
// 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
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:
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 {
// Case 1
case "one":
// Case 2
case "two":
// Case 4
// Default case
default:
Output
two
Example 2:
Java
// Java Program to Demonstrate use of String to
// Control a Switch Statement
// Main class
public class GFG {
// Case 1
case "one":
// Print statement corresponding case
System.out.println("one");
// Case 2
case "two":
// Case 3
case "three":
// Case 4
// Default case
default:
Output
no match
Java
// filename: Test2.java
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.
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
Datatype Bits Acquired In Memory
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
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 {
Output
Int value 100
Long value 100
Float value 100.0
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)
{
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.
Java
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG {
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Print statements
System.out.println("Double value " + d);
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 {
// 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
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 {
// The Expression
double result = (f * b) + (i / c) - (d * s);
Output
result = 626.7784146484375
Example:
Java
// Java program to Illustrate Type Casting
// in Integer to Byte
// Main class
class GFG {
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.
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 {
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 {
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.
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:
Illustration:
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
We can also accomplish single line comments by using the above syntax as shown below:
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*/
Inherits a comment from the nearest inheritable Inherits a comment from the
{@inheritDoc}
class or implementable interface. immediate surperclass.
{@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
@return Adds a "Returns" section with the description text. @return description
@serialField field-name
@serialField Documents an ObjectStreamField component.
field-type field-description
@throws class-name
@throws The @throws and @exception tags are synonyms.
description
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);
Output:
Average of 10, 20 and 30 is :20
For the above code documentation can be generated by using the tool 'javadoc':
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
Find the element that appears once in an array where every other element appears twice
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.
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.
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:
arr[ 2 ] = 10;
Time Complexity:
Accessing array elements become extremely important, in order to perform operations on arrays.
Pseudo Code:
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.
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 :
To learn about the differences between One-dimensional and Multidimensional arrays, click here.
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.
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.
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 -
Applications on Array
To learn more about the advantage, disadvantages, and applications of arrays, click here.
Indexed arrays
Multidimensional arrays
Associative arrays
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
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
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}
};
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][];
// 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++;
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;
// 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++;
Output
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
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:
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:
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 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.
Declaration - Syntax:
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)
{
data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
Example:
Java
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
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 } };
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 } };
System.out.println();
}
}
}
Output:
1 2
3 4
Declaration - Syntax:
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)
{
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 } } };
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:
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 } } };
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 } } };
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;
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
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:
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
// sum of a combination
int sum = 0;
// 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);
Output:
YES
Note: This program would not run for the large size of the array.
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
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
C++CJavaPython3C#PHPJavascript
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
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
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)
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).
C++CJavaPython3C#PHPJavascript
return f[n];
}
Output
34
C++CJavaPython3C#PHPJavascript
Output
34
Time Complexity:O(n)
Extra Space: O(1)
[1101]n=[Fn+1FnFnFn+1]
C++CJavaPython3C#PHPJavascript
class fibonacci
{
return F[0][0];
}
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}};
Output
34
C++CJavaPython3C#Javascript
return F[0][0];
}
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);
}
Output
34
Putting m = n in equation(1).
F2n-1 = Fn2 + Fn-12
Putting m = n in equation(2)
C++JavaPython3C#PHPJavascript
class GFG {
if (n == 1 || n == 2)
return (f[n] = 1);
int k = (n & 1) == 1? (n + 1) / 2
: n / 2;
return f[n];
}
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
class GFG {
// 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
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];
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));
}
}
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) )
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;
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 :
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).
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.
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.
res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
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
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)
As we know that set does not contain any duplicate element we will be using the set here.
C++JavaPython3C#Javascript
class GFG
{
// 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));
Output
2
89
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.
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{
// 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));
}
}
Output
2
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
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));
}
}
Output :
Recursive Approach:
C++CJavaPython3C#PHPJavascript
class GFG {
// base case
if (n == 0)
return 0;
else
// Driver code
public static void main(String[] args)
{
// function calling
System.out.println(countSetBits(n));
}
}
Output :
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
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));
}
}
Output :
n = 9 (1001)
count = 0
Recursive Approach:
C++JavaPython3C#PHPJavascript
class GFG {
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// Driver function
public static void main(String[] args)
{
// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributed by sunnysingh
Output :
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
// Lookup table
static int[] BitsSetTable256 = new int[256];
// Driver code
public static void main(String[] args)
{
Output:
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
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));
}
}
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
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 };
// Driver code
public static void main(String[] args)
{
int num = 31;
System.out.println(countSetBitsRec(num));
}
}
// this code is contributed by mits
Output :
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
{
// Driver code
public static void main(String[] args)
{
int N = 15;
System.out.println(countSetBits(N));
}
}
Output
4
Count set bits in an integer Using Lookup Table
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
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
class GFG{
return bitCount;
}
// Driver program
public static void main(String[] args)
{
int n = 4;
System.out.print("Total set bit count is ");
System.out.print(countSetBits(n));
}
}
Output
Total set bit count is 5
C++JavaPython3C#PHPJavascript
if (k == true)
ans += 1;
else
ans += 0;
if (change == 1) {
return ans;
}
// Driver program
public static void main(String[] args)
{
int n = 17;
System.out.println(countSetBits(n));
}
}
Output
35
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
class GFG
{
// Driver code
public static void main (String[] args)
{
int n = 17;
System.out.println ("Total set bit count is " + countSetBits(n));
}
}
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;
}
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.....
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
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;
}
Output
35
Please write comments if you find anything incorrect, or you want to share more information about the
topic discussed above
Method 5(Iterative)
Example:
Input: N = 4
Output: 5
Input: N = 17
Output: 35
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.
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
mod = 17%2 = 1
mod = 17%4 = 1
totalSetBitCount = 9 + 4*(2) + 0 = 9 + 8 = 17
mod = 17%8 = 1
mod = 17%16 = 1
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
lastPow = pow(2, 4) = 16
mod = 17%16 = 1
totalSetBit = 33 + (mod+1) = 33 + 1 + 1 = 35
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;
}
return totalSetBitCount;
}
Output :
35
75
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.
Implementation:
C++CJavaPython3C#PHPJavascript
class GFG {
return result;
}
// Driver program
public static void main(String[] args)
{
int res = swapBits(28, 0, 3, 2);
System.out.println("Result = " + res);
}
}
Output
Result = 7
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));
}
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) -
Example:
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)
{
// Driver code
public static void main(String[] args)
{
int res = swapBits(28, 0, 3, 2);
System.out.println("Result = " + res);
}
}
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.
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
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
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.
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.
import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
//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());
// 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
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
Java
class Test
{
public static int i = 0;
class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();
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
class Addition{
class GFG {
public static void main (String[] args) {
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
class Addition
{
// adding two integer value.
public int add(int a, int b)
{
class GFG
{
public static void main (String[] args)
{
Addition ob = new Addition();
}
}
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 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
:
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
// 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());
}
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:
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 clone() method: clone() method is present in Object class. It creates and returns a copy
of the object.
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 {}
Anonymous objects
Anonymous objects are objects that are instantiated but are not stored in a reference variable.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
Consider the following Java program that passes a primitive type to function.
Java
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.
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
class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);
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
class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);
Output:
10
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);
}
}
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
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
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
g.x();
}
}
Output:
GeeksforGeeks
GeeksforGeeks
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:
Output:
GeeksforGeeks
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
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).
1. By string literal
2. By new keyword
i) By string literal:
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.
For example:
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");
}
}
// Driver Code
public static void main(String[] args)
{
Test t;
Output:
java
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
Output
Test::show() called
Java
// 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
Java
//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");
}
Output:
Java
//Default constructor
Test()
{
a = 10;
b = 20;
}
Output:
a = 10 b = 20
Java
// Default constructor
Test()
{
a = 10;
b = 20;
}
Output:
a = 10 b = 20
Java
void display()
{
// calling function show()
this.show();
void show() {
System.out.println("Inside show function");
}
Output:
Java
class B
{
int x = 5;
Output:
Value of x in Class B : 5
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:
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.
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;
}
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:
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.
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:
Example 1:
Java
// Java Program to demonstrate
// Reference of Final Variable
// Main class
class GFG {
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 {
Output:
Example:
Java
// Java program to demonstrate
// local final variable
// Main class
class GFG {
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 {
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.
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
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
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.
Syntax:
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:
Syntax:
Java
import java.lang.*;
public class NewClass
{
public static void main(String[] args)
{
// Declaring the variables
int Vali = -1;
float Valf = .5f;
}
}
Output :
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:
5. cbrt() : java.lang.Math.cbrt() method returns the cube root of the passed argument.
Special Point :
Syntax:
Java
import java.lang.*;
public class NewClass
{
}
}
Output :
asin value of Asini : NaN
asin value of Asinj : 0.054858647341251204
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
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 :
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
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
import java.lang.*;
public class NewClass
{
f2 =Math.floor(f2);
System.out.println("Floor value of f2 : "+f2);
System.out.println("");
}
}
Output :
Hypotenuse : 13.0
Remainder : 1.0
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.
Syntax:
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:
12. copySign() : java.lang.Math.copySign() method returns first floating-point argument but having
the sign of second argument.
Syntax:
Java
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;
}
}
Output :
copySign1 : 15.34
copySign2 : -15.34
Read
Discuss
Courses
Practice
Video
import java.math.*;
double value = 2;
System.out.println("");
// Use of decrementExact() method
System.out.println("");
Output:
Using addExact() : 9
import java.lang.*;
f1 =Math.incrementExact(f1);
f2 =Math.incrementExact(f2);
System.out.println("");
System.out.println("");
double b = 10, e = 2;
Output :
Incremented value of f1 : 31
Incremented value of f2 : -55
import java.lang.*;
signm = Math.signum(y);
System.out.println("");
double r1 = Math.round(x);
double r2 = Math.round(y);
System.out.println("");
Output:
Signum of 10.45 = 1.0
Signum of -23.34 = -1.0
// ulp(), log1p()
import java.lang.*;
double u = Math.ulp(x);
u = Math.ulp(y);
System.out.println("");
double l = 99;
double l1 = Math.log1p(l);
l1 = Math.log(100);
Output:
ulp of 34.652 : 7.105427357601002E-15
ulp of -23.34789 : 3.552713678800501E-15
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:
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
NaN
1.0
5.0
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
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));
Comparison
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
modPow(BigInteger exponent,
Returns a BigInteger whose value is (thisexponent mod m).
BigInteger m
probablePrime(int bitLength, Returns a positive BigInteger that is probably prime, with the
Random rnd) specified bitLength.
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;
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.
Syntax:
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).
Examples:
Example 1:
Java
import java.math.BigInteger;
b1 = new BigInteger("321456");
b2 = new BigInteger("31711");
// 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
import java.math.BigInteger;
b1 = new BigInteger("3515219485");
b2 = new BigInteger("3515219485");
// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
Output:
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;
b1 = new BigInteger("3515219485");
b2 = new BigInteger("-1711");
// print result
System.out.println("Result of mod
operation between " + b1
+ " and " + b2 +
" equal to " + result);
}
}
Output:
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#mod(java.math.
BigInteger)
Articles (6)
LinkedList 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.
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.
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:
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.
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.
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.
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
// Main class
public class GFG {
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.
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:
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.*;
ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "For");
System.out.println(ll);
}
}
Output:
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.*;
ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "Geeks");
ll.set(1, "For");
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.*;
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:
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.*;
ll.add("Geeks");
ll.add("Geeks");
ll.add(1, "For");
System.out.println();
Output:
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.
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.
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
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
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
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
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;
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 class supports one default constructor Stack() which is used to create an empty stack.
Declaration:
public class Stack<E> extends Vector<E>
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.
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);
}
}
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
}
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
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)
{
// Initialization of Stack
// using Generics
Stack<String> stack2 = new Stack<String>();
stack2.push("Geeks");
stack2.push("For");
stack2.push("Geeks");
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.*;
// Main Method
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
Output:
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.*;
Output:
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.
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.
Inserts all the elements in the specified Collection into this Vector at
addAll(int index, Collection c)
the specified position.
copyInto(Object []array) Copies the components of this vector into the specified array.
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.
insertElementAt(Object o, int Inserts the specified object as a component in this vector at the
index) specified index.
iterator() Returns an iterator over the elements in this list in proper sequence.
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),
remove(int index) Removes the element at the specified position in this Vector.
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.
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.
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.
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
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.
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:
Example: Queue
Java
import java.util.LinkedList;
import java.util.Queue;
System.out.println(q);
Output:
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
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println(pq);
}
}
Output:
Example
Java
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
pq.remove("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
import java.util.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
Output:
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.
Example
Java
import java.util.*;
class GfG {
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
import java.util.*;
class GfG {
Output:
10
10
20
Example
Java
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>();
Output:
10
10
15
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 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.
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 is used to remove and return the first occurrence of the
remove(element)
given element in the queue.
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 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 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:
Constructors:
1. PriorityQueue(): Creates a PriorityQueue with the default initial capacity (11) that orders its
elements according to their natural ordering.
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>();
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.*;
Output
[0, 1, 1, 1, 2, 1]
Java
/*package whatever //do not write package name here */
import java.util.*;
import java.io.*;
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.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
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)
{
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.*;
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
Output
For Geeks Geeks
METHOD DESCRIPTION
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.
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
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).
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.
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.
METHOD DESCRIPTION
containsAll(Collection<?> Returns true if this collection contains all of the elements in the
c) specified collection.
METHOD DESCRIPTION
equals(Object o) Compares the specified object with this collection for equality.
METHOD DESCRIPTION
parallelStream() Returns a possibly parallel Stream with this collection as its source.
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:
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;
// Printing elements
System.out.println(arrli);
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:
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.
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:
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:
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:
Method Description
add(Object o) This method is used to append a specific element to the end of a list.
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.
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.
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.
subList?(int fromIndex, int Returns a view of the portion of this list between the specified
toIndex) fromIndex, inclusive, and toIndex, exclusive.
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.
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 {
Output:
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
// main class
class GFG {
Output:
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
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList<String> al = new ArrayList<>();
Output:
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
// Main class
class GFG {
System.out.println();
Output:
Articles (7)
Set in Java
HashSet in Java
TreeSet 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.
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:
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.
Java
// Java program Illustrating Set Interface
// Main class
public class GFG {
Output
[Set, Example, Geeks, For]
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]
Example:
div hideAd="auto">
Java
// Java Program Demonstrating Operations on the Set
// such as Union, Intersection and Difference operations
// Main class
public class SetExample {
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);
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]
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
// Main class
class GFG {
Output
[A, B, C]
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
// Main class
class GFG {
// Declaring a string
String check = "D";
Output
Set is [A, B, C]
Contains D false
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
// Main class
class GFG {
Output
Initial HashSet [A, B, C, D, E]
After removing element [A, C, D, E]
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
// Main class
class GFG {
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
Example
Java
// Java program Demonstrating Creation of Set object
// Using the Hashset class
// Main class
class GFG {
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.*;
Output
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Class 3: LinkedHashSet
Example
Java
// Java program to demonstrate the
// creation of Set object using
// the LinkedHashset class
import java.util.*;
class GFG {
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
// Main class
class GFG {
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.
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.
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(...));
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.
// 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);
}
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.
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 {
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.
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:
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.
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.
Implementation:
Java
// Java program to Demonstrate Working of HashSet Class
// Main class
// HashSetDemo
class GFG {
// Display message
System.out.println("Iterating over list:");
Output:
[South Africa, Australia, India]
List contains India or not:true
List after removing Australia:[South Africa, India]
Iterating over list:
South Africa
India
Let’s see how to perform a few frequently used operations on the HashSet.
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
// 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>();
Output:
HashSet elements : [Geek, For, Geeks]
The values can be removed from the HashSet using the remove() method.
Example
Java
// Java program Illustrating Removal Of Elements of HashSet
Output:
Initial HashSet [A, B, Geek, For, Geeks, Z]
After removing element [A, Geek, For, Geeks, Z]
Element AC exists in the Set : false
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
// Main class
// IterateTheHashSet
class GFG {
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.
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)
Used to check whether the set is empty or not. Returns true for empty and false
isEmpty()
for a non-empty condition for set.
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.
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.
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.
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.
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.
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.
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).
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
HashSet uses the add() method for add or HashMap uses the put() method
Insertion
storing data. for storing data.
HashSet vs TreeSet
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.
Syntax: Declaration
Contains unique elements only like HashSet. It extends the HashSet class and implements the Set
interface.
Maintains insertion order.
2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C.
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.
Example:
Java
// Java Program to Illustrate LinkedHashSet
// Main class
// LinkedHashSetExample
public class GFG {
System.out.println("Original 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]
Let’s see how to perform a few frequently used operations on the LinkedHashSet.
Example:
Java
// Java Program to Add Elements to LinkedHashSet
// Main class
// AddingElementsToLinkedHashSet
class GFG {
Output:
LinkedHashSet : [Geek, For, Geeks]
The values can be removed from the LinkedHashSet using the remove() method.
Example:
Java
// Java program to Remove Elements from LinkedHashSet
// Main class
// RemoveElementsFromLinkedHashSet
class GFG {
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
// Main class
// IteratingLinkedHashSet
class GFG {
while (itr.hasNext())
System.out.print(itr.next() + ", ");
// New line
System.out.println();
Output:
Geek, For, Geeks, A, B, Z,
Geek, For, Geeks, A, B, Z,
Methods of LinkedHashSet
METHOD DESCRIPTION
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set.
METHOD DESCRIPTION
equals(Object o) Compares the specified object with this set for equality.
removeAll(Collection Removes from this set all of its elements that are contained in the specified
c) collection (optional operation).
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).
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)
METHOD DESCRIPTION
add(E e) Adds the specified element to this set if it is not already present.
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)
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)
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 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.
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:
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.
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.
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 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.
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.
Example:
Java
// Java Program to Demonstrate
// Working of Map interface
// Main class
class GFG {
// 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
// Main class
public class GFG {
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
// Main class
public class GFG {
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
// Main class
public class GFG {
Output:
sachin 30
vaibhav 20
vishal 10
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.
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
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>();
System.out.println(hm1);
System.out.println(hm2);
}
}
Output:
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
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>();
Output:
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
import java.util.*;
class GFG {
// Initialization of a Map
// using Generics
Map<Integer, String> hm1
= new HashMap<Integer, String>();
// Initial Map
System.out.println(hm1);
hm1.remove(new Integer(4));
// Final Map
System.out.println(hm1);
}
}
Output:
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
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>();
Output:
1 : Geeks
2 : For
3 : Geeks
HashMap
java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value
pair<Key, Value>.
Let us consider below example where we have to count occurrences of each integer in given array of
integers.
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>();
// Print result
for (Map.Entry m:hmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}
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.
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
// Print result
for (Map.Entry m:tmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}
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.
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:
Here, K is the key Object type and V is the value Object type
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:
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:
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.
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.
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.
removeEldestEntry
Returns true if this map should remove its eldest entry.
(Map.Entry<K,V> eldest)
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
// LinkedHashMapExample
public class GFG {
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}
Let’s see how to perform a few frequently used operations on the LinkedHashMap class instance.
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
// Main class
// AddElementsToLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm1
= new LinkedHashMap<Integer, String>();
Output
Mappings of LinkedHashMap : {3=Geeks, 2=For, 1=Geeks}
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 {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();
Output
Initial map : {3=Geeks, 2=Geeks, 1=Geeks}
Updated Map : {3=Geeks, 2=For, 1=Geeks}
Example
Java
// Java program to Demonstrate Removal of Elements
// from LinkedHashMap
// Main class
// RemovingMappingsFromLinkedHashMap
class GFG {
Output
Initial Map : {3=Geeks, 2=Geeks, 1=Geeks, 4=For}
Updated Map : {3=Geeks, 2=Geeks, 1=Geeks}
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
// Main class
// IteratingOverLinkedHashMap
class GFG {
// Initialization of a LinkedHashMap
// using Generics
LinkedHashMap<Integer, String> hm
= new LinkedHashMap<Integer, String>();
Output
3 : Geeks
2 : For
1 : Geeks
Articles (4)
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
Constructors:
Dictionary() Sole constructor.
Syntax :
Syntax :
3. get(Object key) : java.util.Dictionary.get(Object key) returns the value that is mapped with the
argumented key in the dictionary.
Syntax :
Syntax :
Syntax :
Syntax :
Syntax :
Java
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"));
}
}
Output:
Size of Dictionary : 1
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)
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:
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.
Java
import java.util.*;
public class Calendar2 {
public static void main(String[] args)
{
// creating Calendar object
Calendar calendar = Calendar.getInstance();
Output:
import java.util.*;
public class Calendar3 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in a year: " + max);
}
}
Output:
import java.util.*;
public class Calendar4 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + min);
}
}
Output:
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:
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:
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:
Here, an object named gcal of GregorianCalendar Class is initialized with the current date and time in
the default locale and timezone.
Fields defined :
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:
Java
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();
Output:
Java
Output:
Java
// Java program to demonstrate simple GregorianCalendar
// operations
import java.util.Locale;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;
Output:
Java
Output:
Java
Output:
Java
Output:
Java
Output:
Java
Output:
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
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
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);