- Tech Partner
- Enterprise Software Development Article Challenge
- Learn Delphi
- DelphiFeeds
- Delphi 25th Anniversary
Null Pointer Assignment Errors Explained
Author: Embarcadero USA
Article originally contributed by Borland Staff
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed .
Join Our Global Developer Community
Join our email list and receive the latest case studies, event updates, product news, and much more.
- Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder. Design. Code. Compile. Deploy. Start Free Trial Upgrade Today Free Delphi Community Edition Free C++Builder Community Edition
Something Fresh
How to live track the iss international space station, read the webinar: why you should leave delphi 7 once and for all, upgrading c++builder 12.2: tip #7, bcc64x tips, popular posts, rad studio 12.2 athens inline patch 1 available.
Announcing the Availability of RAD Studio 12.2 Athens
Delphi 12 and c++builder 12 community editions released, interbase odbc driver on github, embarcadero partners with raize software for ksvc maintenance.
- Toggle Reader Mode
Unknown Feed
Embarcadero’s users understand the scalability and stability of C++ and Delphi programming, and depend on the decades of innovation those languages bring to development. Ninety of the Fortune 100 and an active community of more than three million users worldwide have relied on Embarcadero’s award-winning products over the past 30 years. Icons by Icons8.com .
© 2024 EMBARCADERO INC. ALL RIGHTS RESERVED
Useful Links
Section 1. Null Pointers
1.1: what is this infamous null pointer, anyway, 1.2: how do i "get" a null pointer in my programs, 1.3: what is null and how is it #defined, 1.4: how should null be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer, 1.5: if null were defined as follows:, wouldn't that make function calls which pass an uncast null work, 1.6: i use the preprocessor macro, to help me build null pointers of the correct type., 1.7: is the abbreviated pointer comparison " if(p) " to test for non- null pointers valid what if the internal representation for null pointers is nonzero, 1.8: if " null " and "0" are equivalent, which should i use, 1.9: but wouldn't it be better to use null (rather than 0) in case the value of null changes, perhaps on a machine with nonzero null pointers, 1.10: i'm confused. null is guaranteed to be 0, but the null pointer is not, 1.11: why is there so much confusion surrounding null pointers why do these questions come up so often, 1.12: i'm still confused. i just can't understand all this null pointer stuff., 1.13: given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes, 1.14: seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types, 1.15: what does a run-time "null pointer assignment" error mean how do i track it down.
12.8 — Null pointers
In the previous lesson ( 12.7 -- Introduction to pointers ), we covered the basics of pointers, which are objects that hold the address of another object. This address can be dereferenced using the dereference operator (*) to get the object at that address:
The above example prints:
In the prior lesson, we also noted that pointers do not need to point to anything. In this lesson, we’ll explore such pointers (and the various implications of pointing to nothing) further.
Null pointers
Besides a memory address, there is one additional value that a pointer can hold: a null value. A null value (often shortened to null ) is a special value that means something has no value. When a pointer is holding a null value, it means the pointer is not pointing at anything. Such a pointer is called a null pointer .
The easiest way to create a null pointer is to use value initialization:
Best practice
Value initialize your pointers (to be null pointers) if you are not initializing them with the address of a valid object.
Because we can use assignment to change what a pointer is pointing at, a pointer that is initially set to null can later be changed to point at a valid object:
The nullptr keyword
Much like the keywords true and false represent Boolean literal values, the nullptr keyword represents a null pointer literal. We can use nullptr to explicitly initialize or assign a pointer a null value.
In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer.
Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.
Dereferencing a null pointer results in undefined behavior
Much like dereferencing a dangling (or wild) pointer leads to undefined behavior, dereferencing a null pointer also leads to undefined behavior. In most cases, it will crash your application.
The following program illustrates this, and will probably crash or terminate your application abnormally when you run it (go ahead, try it, you won’t harm your machine):
Conceptually, this makes sense. Dereferencing a pointer means “go to the address the pointer is pointing at and access the value there”. A null pointer holds a null value, which semantically means the pointer is not pointing at anything. So what value would it access?
Accidentally dereferencing null and dangling pointers is one of the most common mistakes C++ programmers make, and is probably the most common reason that C++ programs crash in practice.
Whenever you are using pointers, you’ll need to be extra careful that your code isn’t dereferencing null or dangling pointers, as this will cause undefined behavior (probably an application crash).
Checking for null pointers
Much like we can use a conditional to test Boolean values for true or false , we can use a conditional to test whether a pointer has value nullptr or not:
The above program prints:
In lesson 4.9 -- Boolean values , we noted that integral values will implicitly convert into Boolean values: an integral value of 0 converts to Boolean value false , and any other integral value converts to Boolean value true .
Similarly, pointers will also implicitly convert to Boolean values: a null pointer converts to Boolean value false , and a non-null pointer converts to Boolean value true . This allows us to skip explicitly testing for nullptr and just use the implicit conversion to Boolean to test whether a pointer is a null pointer. The following program is equivalent to the prior one:
Conditionals can only be used to differentiate null pointers from non-null pointers. There is no convenient way to determine whether a non-null pointer is pointing to a valid object or dangling (pointing to an invalid object).
Use nullptr to avoid dangling pointers
Above, we mentioned that dereferencing a pointer that is either null or dangling will result in undefined behavior. Therefore, we need to ensure our code does not do either of these things.
We can easily avoid dereferencing a null pointer by using a conditional to ensure a pointer is non-null before trying to dereference it:
But what about dangling pointers? Because there is no way to detect whether a pointer is dangling, we need to avoid having any dangling pointers in our program in the first place. We do that by ensuring that any pointer that is not pointing at a valid object is set to nullptr .
That way, before dereferencing a pointer, we only need to test whether it is null -- if it is non-null, we assume the pointer is not dangling.
A pointer should either hold the address of a valid object, or be set to nullptr. That way we only need to test pointers for null, and can assume any non-null pointer is valid.
Unfortunately, avoiding dangling pointers isn’t always easy: when an object is destroyed, any pointers to that object will be left dangling. Such pointers are not nulled automatically! It is the programmer’s responsibility to ensure that all pointers to an object that has just been destroyed are properly set to nullptr .
When an object is destroyed, any pointers to the destroyed object will be left dangling (they will not be automatically set to nullptr ). It is your responsibility to detect these cases and ensure those pointers are subsequently set to nullptr .
Legacy null pointer literals: 0 and NULL
In older code, you may see two other literal values used instead of nullptr .
The first is the literal 0 . In the context of a pointer, the literal 0 is specially defined to mean a null value, and is the only time you can assign an integral literal to a pointer.
As an aside…
On modern architectures, the address 0 is typically used to represent a null pointer. However, this value is not guaranteed by the C++ standard, and some architectures use other values. The literal 0 , when used in the context of a null pointer, will be translated into whatever address the architecture uses to represent a null pointer.
Additionally, there is a preprocessor macro named NULL (defined in the <cstddef> header). This macro is inherited from C, where it is commonly used to indicate a null pointer.
Both 0 and NULL should be avoided in modern C++ (use nullptr instead). We discuss why in lesson 12.11 -- Pass by address (part 2) .
Favor references over pointers whenever possible
Pointers and references both give us the ability to access some other object indirectly.
Pointers have the additional abilities of being able to change what they are pointing at, and to be pointed at null. However, these pointer abilities are also inherently dangerous: A null pointer runs the risk of being dereferenced, and the ability to change what a pointer is pointing at can make creating dangling pointers easier:
Since references can’t be bound to null, we don’t have to worry about null references. And because references must be bound to a valid object upon creation and then can not be reseated, dangling references are harder to create.
Because they are safer, references should be favored over pointers, unless the additional capabilities provided by pointers are required.
Favor references over pointers unless the additional capabilities provided by pointers are needed.
Did you hear the joke about the null pointer?
That’s okay, you wouldn’t get dereference.
Question #1
1a) Can we determine whether a pointer is a null pointer or not? If so, how?
Show Solution
Yes, we can use a conditional (if statement or conditional operator) on the pointer. A pointer will convert to Boolean false if it is a null pointer, and true otherwise.
1b) Can we determine whether a non-null pointer is valid or dangling? If so, how?
There is no easy way to determine this.
Question #2
For each subitem, answer whether the action described will result in behavior that is: predictable, undefined, or possibly undefined. If the answer is “possibly undefined”, clarify when.
2a) Assigning a new address to a non-const pointer
Predictable.
2b) Assigning nullptr to a pointer
2c) Dereferencing a pointer to a valid object
2d) Dereferencing a dangling pointer
2e) Dereferencing a null pointer
2f) Dereferencing a non-null pointer
Possibly undefined, if the pointer is dangling.
Question #3
Why should we set pointers that aren’t pointing to a valid object to ‘nullptr’?
We can not determine whether a non-null pointer is valid or dangling, and accessing a dangling pointer will result in undefined behavior. Therefore, we need to ensure that we do not have any dangling pointers in our program.
If we ensure all pointers are either pointing to valid objects or set to nullptr , then we can use a conditional to test for null to ensure we don’t dereference a null pointer, and assume all non-null pointers are pointing to valid objects.
5.1 What is this infamous null pointer, anyway?
5.2 How do I get a null pointer in my programs?
5.3 Is the abbreviated pointer comparison `` if(p) '' to test for non-null pointers valid? What if the internal representation for null pointers is nonzero?
5.4 What is NULL and how is it defined?
5.5 How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer?
5.6 If NULL were defined as follows: #define NULL ((char *)0) wouldn't that make function calls which pass an uncast NULL work?
5.7 My vendor provides header files that #define NULL as 0L . Why?
5.8 Is NULL valid for pointers to functions?
5.9 If NULL and 0 are equivalent as null pointer constants, which should I use?
5.10 But wouldn't it be better to use NULL (rather than 0 ), in case the value of NULL changes, perhaps on a machine with nonzero internal null pointers?
5.11 I once used a compiler that wouldn't work unless NULL was used.
5.12 I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type.
5.13 This is strange. NULL is guaranteed to be 0 , but the null pointer is not?
5.14 Why is there so much confusion surrounding null pointers? Why do these questions come up so often?
5.15 I'm confused. I just can't understand all this null pointer stuff.
5.16 Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes?
5.17 Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types?
5.18 Is a run-time integral value of 0, cast to a pointer, guaranteed to be a null pointer?
5.19 How can I access an interrupt vector located at the machine's location 0? If I set a pointer to 0 , the compiler might translate it to some nonzero internal null pointer value.
5.20 What does a run-time ``null pointer assignment'' error mean? How can I track it down?
Java Arrays
Java strings.
- Java Collection
- Java 8 Tutorial
Java Multithreading
Java exception handling.
- Java Programs
- Java Project
- Java Collections Interview
Java Interview Questions
- Spring Boot
Null Pointer Exception in Java
A NullPointerException in Java is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.
Explanation: In the above example, the string reference “s” is null. When the program tries to call the length() method, it throws a NullPointerException because there is no actual object.
Reasons for Null Pointer Exception
A NullPointerException occurs due to below reasons:
- Invoking a method from a null object.
- Accessing or modifying a null object’s field.
- Taking the length of null, as if it were an array.
- Accessing or modifying the slots of null objects, as if it were an array.
- Throwing null, as if it were a Throwable value.
- When you try to synchronize over a null object.
Need of Null Value
The null value serves as a placeholder and it indicates that no value is assigned to a reference variable. Common applications include:
- Linked Data Structures : It represents the end of a list or tree branch.
- Design Patterns : This is used in patterns like the Null Object Pattern or Singleton Pattern .
How to Avoid the NullPointerException?
To avoid the NullPointerException , we must ensure that all the objects are initialized properly, before we use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
1. String Comparison with Literals
A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum . Instead of invoking the method from the null object, consider invoking it from the literal.
We can avoid NullPointerException by calling equals on literal rather than object.
Note : Always invoke equals on the literal to avoid calling a method on a null reference.
2. Checking Method Arguments
Before executing the body of the new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments.
3. Use the Ternary Operator
The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers.
Explanation : The ternary operator helps check for null and avoid operations on null references.
FAQs – Java Null Pointer Exception
What is nullpointerexception in java.
NullPointerException in Java is a type RuntimeException.
Why Null Pointer Exception Occurs?
NullPointerException occurs when one tries to access or manipulate object reference that has a Null value stored in it.
How to handle a Null Pointer Exception in Java?
There are certain methods to handle Null Pointer Exception in Java are mentioned below: String comparison with literals Keeping a Check on the arguments of a method Use of Ternary Operator
Reason for Null Pointer Exception.
NullPointerException is thrown when a program attempts to use an object reference that has the null value.
Similar Reads
- Java Tutorial Java is one of the most popular and widely used programming languages which is used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level systems. Java was invented by James Gosling and Oracle currently owns it. JDK 23 is the latest version of Java. Popular platfor 4 min read
Java Overview
- Introduction to Java Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the 10 min read
- The Complete History of Java Programming Language Java is an Object-Oriented programming language developed by James Gosling in the early 1990s. The team initiated this project to develop a language for digital devices such as set-top boxes, television, etc. Originally C++ was considered to be used in the project but the idea was rejected for sever 5 min read
- How to Download and Install Java for 64 bit machine? Java is one of the most popular and widely used programming languages. It is a simple, portable, platform-independent language. It has been one of the most popular programming languages for many years. In this article, We will see How to download and install Java for Windows 64-bit. We'll also be an 4 min read
- Setting up the environment in Java Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 22. Below are the environ 6 min read
- How JVM Works - JVM Architecture JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that 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 s 7 min read
- JDK in Java The Java Development Kit (JDK) is a cross-platformed software development environment that offers a collection of tools and libraries necessary for developing Java-based software applications and applets. It is a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java 5 min read
- Differences between JDK, JRE and JVM Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java 5 min read
Java Basics
- Java Syntax Java is an object-oriented programming language which is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++ which makes it easier to understand. Let's understand the Syntax and Structure of Java Programs with a basic 5 min read
- Java Hello World Program Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn h 5 min read
- Java Identifiers An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names and every Java Variables must be identified with unique names. Example: public class Test{ public static void main(String[] args) { int a = 20; }}In the above Java code, we h 2 min read
- Java Keywords In Java, Keywords are the Reserved words in a programming language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Example : [GFGTABS] Java // Java Program to demonstrate Keywords class GFG { pub 5 min read
- Java Data Types 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 11 min read
- Java Variables Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val 8 min read
- Scope of Variables In Java Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of function call stack. Java programs are organized in the form of cla 5 min read
- Java Operators Java operators are special symbols that perform operations on variables or values. They can be classified into several categories based on their functionality. These operators play a crucial role in performing arithmetic, logical, relational, and bitwise operations etc. Example: Here, we are using + 14 min read
- How to Take Input From User in Java? Java brings various Streams with its I/O package that helps the user perform all the Java input-output operations. These streams support all types of objects, data types, characters, files, etc. to fully execute the I/O operations. Input in Java can be with certain methods mentioned below in the art 5 min read
Java Flow Control
- Java if statement The Java 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 statements is executed otherwise not. Example: [GFGTABS] Java // Java program to ill 5 min read
- Java if-else Statement The if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples. Example: [GF 4 min read
- Java if-else-if ladder with Examples The Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback. Example: The 3 min read
- Java For Loop Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections. Example: [GFGTABS] Java class Geeks { pu 4 min read
- For-each loop in Java The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required. Example: Below is a basic e 6 min read
- Java while Loop Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGT 3 min read
- Java Do While Loop Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // 4 min read
- Java Break Statement The Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example: [GFGTABS] 3 min read
- Java Continue Statement In Java, continue statement is used inside the loops such as for, while and do-while to skip the curren iteration and move directly to the next iteration of the loop. Example: [GFGTABS] Java // Java Program to illustrate the use of continue statement public class GFG { public static void main(String 4 min read
- return keyword in Java In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows: Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrat 6 min read
Java Methods
- Java Methods The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every metho 10 min read
- How to Call a Method in Java? Calling a method allows to reuse code and organize our program effectively. Java Methods are the collection of statements used for performing certain tasks and for returning the result to the user. In this article, we will learn how to call different types of methods in Java with simple examples. Ex 3 min read
- Static methods vs Instance methods in Java In this article, we are going to learn about Static Methods and Instance Methods in Java. Java Instance MethodsInstance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the m 5 min read
- Access Modifiers in Java In Java, Access modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc. to the user depending upon the access modifier used with the element. In this article, let us learn about Java Access Modifiers, their types, and 6 min read
- Command Line Arguments in Java Java command-line argument is an argument i.e. passed at the time of running the Java program. In Java, the command line 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-li 3 min read
- Variable Arguments (Varargs) in Java Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments. Need of Java VarargsUntil JDK 4, we cant declare a method with variable no. of arguments. If the 4 min read
- Arrays in Java Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with e 15+ min read
- How to Initialize an Array in Java? An array in Java is a data structure used to store multiple values of the same data type. Each element in an array has a unique index value. It makes it easy to access individual elements. In an array, we have to declare its size first because the size of the array is fixed. In an array, we can stor 6 min read
- Java Multi-Dimensional Arrays A multidimensional array can be defined as an array of arrays. Data in multidimensional arrays are stored in tabular form (row-major order). Example: [GFGTABS] Java // Java Program to Demonstrate // Multi Dimensional Array import java.io.*; public class Main { public static void main(String[] args) 9 min read
- Jagged Array in Java In Java, 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. Example: arr [][]= { {1,2}, {3,4,5,6},{7,8,9}}; So, here you can check that the number of columns in row1!=row2!=row3. Tha 5 min read
- Arrays class in Java The Arrays class in java.util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. The c 13 min read
- Final Arrays in Java As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another 4 min read
- Java Strings In Java, String is the type of objects that can store the sequence of characters enclosed by double quotes and every character is stored in 16 bits i.e using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowing 9 min read
- Why Java Strings are Immutable? In Java, strings are immutable means their values cannot be changed once they are created. This feature enhances performance, security, and thread safety. In this article, we will explain why strings are immutable in Java and how this benefits Java applications. What Does Immutable Mean?An immutable 3 min read
- Java String concat() Method with Examples The string concat() method concatenates (appends) a string to the end of another string. It returns the combined string. It is used for string concatenation in Java. It returns NullPointerException if any one of the strings is Null. In this article, we will learn how to concatenate two strings in Ja 4 min read
- String class in Java String is a sequence of characters. In Java, objects of the String class are immutable which means they cannot be changed once created. In this article, we will learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import java.io.*; 7 min read
- StringBuffer class in Java StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time. Features of StringBuffer ClassHere are some important features and met 12 min read
- StringBuilder Class in Java with Examples StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much s 6 min read
- String vs StringBuilder vs StringBuffer in Java A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. Initializing a String is one of the important pillars required as a pre-requisite with deeper understanding. Comparison between String, StringBuilder, and StringB 7 min read
Java OOPs Concepts
- Object Oriented Programming (OOPs) Concept in Java As the name suggests, Object-Oriented Programming or Java OOPs concept refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks you assign. Object-oriented programmin 12 min read
- Classes and Objects in Java In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named 11 min read
- Java Constructors Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attrib 9 min read
- Object Class in Java Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob 8 min read
- Abstraction in Java Abstraction in Java is the process in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. In this article, we will learn about abstraction and what abstraction means. Simple Example to understand Abstraction:Televisi 11 min read
- Encapsulation in Java Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. Java Encapsulation is a way of hiding the implementation details of a class from outsid 8 min read
- Inheritance in Java Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from ano 13 min read
- Polymorphism in Java The word 'polymorphism' means 'having many forms'. In simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type. Real-life Illustration of Polymorphism in Java: A person can have d 6 min read
- Method Overloading in Java In Java, Method Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static Polym 9 min read
- Overriding in Java In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or 13 min read
- Packages In Java Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.EmployeeMaking searching/locatin 8 min read
Java Interfaces
- Interfaces in Java An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to ac 11 min read
- Interfaces and Inheritance in Java A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This mean 7 min read
- Java Class vs Interfaces In Java, the difference between a class and an interface is syntactically similar, both contain methods and variables, but they are different in many aspects. The main difference is, A class defines the state of behavior of objects.An interface defines the methods that a class must implement.Class v 5 min read
- Java Functional Interfaces A functional interface in Java is an interface that contains only one abstract method. Functional interface can have multiple default or static methods, but only one abstract method. Runnable, ActionListener, and Comparable are common examples of Java functional interfaces. From Java 8 onwards, lamb 7 min read
- Nested Interface in Java We can declare interfaces as members of a class or another interface. Such an interface is called a member interface or nested interface. Interfaces declared outside any class can have only public and default (package-private) access specifiers. In Java, nested interfaces (interfaces declared inside 5 min read
- Marker interface in Java It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. public interface Serializable { // nothing here } Examples of Marker Interface which are used in real-time applications : Cloneabl 3 min read
- Comparator Interface in Java with Examples A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):Suppose we have an Array/ArrayList of our own class 6 min read
Java Collections
- Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac 15+ min read
- Collections Class in Java Collections class in Java is one of the utility classes in Java Collections Framework. The java.util package contains the Collections class in Java. Java Collections class is used with the static methods that operate on the collections or return the collection. All the methods of this class throw th 13 min read
- Collection Interface in Java The Collection interface in Java is a core member of the Java Collections Framework located in the java.util package. It is one of the root interfaces of the Java Collection Hierarchy. The Collection interface is not directly implemented by any class. Instead, it is implemented indirectly through it 6 min read
- Java List Interface The List Interface in Java extends the Collection Interface and is a part of java.util package. It is used to store the ordered collections of elements. So in a Java List, you can organize and manage the data sequentially. Maintained the order of elements in which they are added.Allows the duplicate 15+ min read
- ArrayList in Java Java ArrayList is a part of collections framework and it is a class of 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 array is required. The main advantage of ArrayList is, unli 10 min read
- Vector Class in Java The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface. Thread-Safe: All methods are synchronized, making it suitable for multi-threaded environments. 13 min read
- 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 addr 13 min read
- Stack Class in Java Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of LIFO(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 Stack cl 11 min read
- Set in Java The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of the dupl 14 min read
- Java HashSet HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon 12 min read
- TreeSet in Java TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ 13 min read
- Java LinkedHashSet LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el 8 min read
- Queue Interface In Java The Queue Interface is present in java.util package and extends the Collection interface. It stores and processes the data in FIFO(First In First Out) order. It is an ordered list of objects limited to inserting elements at the end of the list and deleting elements from the start of the list. No Nul 13 min read
- PriorityQueue in Java The PriorityQueue class in Java is part of the java.util package. It is known that a Queue follows the FIFO(First-In-First-Out) Algorithm, but 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 11 min read
- Deque Interface in Java Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/ 10 min read
- Map Interface in Java In Java, Map Interface is present in java.util package represents a mapping between a key and a value. Java Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. No Duplicates in Keys: Ensures that keys are unique. H 12 min read
- HashMap in Java In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding 15+ min read
- Java LinkedHashMap LinkedHashMap in Java implements the Map interface of the Collections Framework. It stores key-value pairs while maintaining the insertion order of the entries. It maintains the order in which elements are added. Stores unique key-value pairs.Maintains insertion order.Allows one null key and multipl 7 min read
- Hashtable in Java The Hashtable class, introduced as part of the original Java Collections framework, implements a hash table that maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashC 13 min read
- Java Dictionary Class Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and used to access the values. It was part of the Java Collections Framework and it was introduced in Java 1.0 but has been largely replaced by the Map interface since Java 1.2. Store 5 min read
- SortedSet Interface in Java with Examples The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this 8 min read
- Java Comparable Interface The Comparable interface in Java is used to define the natural ordering of objects for a user-defined class. It is part of the java.lang package and it provides a compareTo() method to compare instances of the class. A class has to implement a Comparable interface to define its natural ordering. Exa 4 min read
- Java Comparable vs Comparator In Java, both Comparable and Comparator are used for sorting objects. The main difference between Comparable and Comparator is: Comparable: It is used to define the natural ordering of the objects within the class.Comparator: It is used to define custom sorting logic externally.Difference Between Co 5 min read
- Java Iterator An Iterator in Java is an interface used to traverse elements in a Collection sequentially. It provides methods like hasNext(), next(), and remove() to loop through collections and perform manipulation. An Iterator is a part of the Java Collection Framework, and we can use it with collections like A 7 min read
- Exceptions in Java Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. What are Ja 10 min read
- Checked vs Unchecked Exceptions in Java In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked exceptionsUnchecked exceptions Understanding the difference betwee 5 min read
- Java Try Catch Block In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, 4 min read
- final, finally and finalize in Java This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different 13 min read
- throw and throws in Java In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as NullPointerException, ArrayIndexOutOfBoundsException, etc. In this article, we will 4 min read
- User-defined Custom Exception in Java An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which ar 3 min read
- Chained Exceptions in Java Chained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero, but the root cause of the error was an I/O 3 min read
- Null Pointer Exception in Java A NullPointerException in Java is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Example: [GFGTABS] Java // Demonstration of NullPointerException in J 5 min read
- Exception Handling with Method Overriding in Java An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-orient 6 min read
- Java Multithreading Tutorial Threads are the backbone of multithreading. We are living in a real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking ef 15+ min read
- Java Threads Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time). For example, in MS Word. one thread automatically formats 9 min read
- Java.lang.Thread Class in Java Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of 8 min read
- Runnable interface in Java java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread - Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run( 3 min read
- Lifecycle and States of a Thread in Java A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any inst 6 min read
- Main thread in Java Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i 4 min read
- Java Thread Priority in Multithreading As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be give 5 min read
- Naming a thread and fetching name of current thread in Java Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a 5 min read
- Difference between Thread.start() and Thread.run() in Java In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. 3 min read
- Thread.sleep() Method in Java With Examples Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. T 4 min read
- Daemon Thread in Java In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual M 4 min read
- Thread Safety and how to achieve it in Java As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already wor 5 min read
- Thread Pools in Java Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service 9 min read
Java File Handling
- File Handling in Java In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file. Why File Handling is Required? File Handling is an integral part of any programming lan 7 min read
- Java.io.File Class in Java Java File class is Java's representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, 6 min read
- Java Program to Create a New File A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is created. The file is one way, in which data will be stored as per requirement. Steps to Create a N 8 min read
- Java Program to Write into a File In this article, we will see different ways of writing into a File using Java Programming language. Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java. There are many ways to 7 min read
- Delete a File Using Java Java provides methods to delete files using java programs. On contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin. Methods used to delete a file in Java: 1. Using java.io.File.de 2 min read
- Java IO FileReader Class FileReader in Java is a class in the java.io package which can be used to read a stream of characters from the files. Java IO FileReader class uses either specified charset or the platform's default charset for decoding from bytes to characters. 1. Charset: The Charset class is used to define method 3 min read
- FileWriter Class in Java Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java. This class inherits from OutputStreamWriter class which in turn 7 min read
- Java.io.FilePermission Class in Java java.io.FilePermission class is used to represent access to a file or a directory. These accesses are in the form of a path name and a set of actions associated to the path name(specifies which file to be open along with the extension and the path). For Example, in FilePermission("GEEKS.txt", "read" 5 min read
- Java.io.FileDescriptor in Java java.io.FileDescriptor works for opening a file having a specific name. If there is any content present in that file it will first erase all that content and put "Beginning of Process" as the first line. Instances of the file descriptor class serve as an opaque handle to the underlying machine-speci 4 min read
Java Streams and Lambda Expressions
- Lambda Expression in Java Lambda expressions in Java, introduced in Java SE 8, represent instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Functionalities of Lambda Expression in JavaLambda Expressi 5 min read
- Method References in Java with examples Functional Interfaces in Java and Lambda Function are prerequisites required in order to grasp grip over method references in Java. As we all know that a method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task 9 min read
- Java 8 Stream Tutorial Java 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme 15+ min read
- Java 8 Features - Complete Tutorial Java 8 is the most awaited release of Java programming language development because, in the entire history of Java, it never released that many major features. It consists of major features of Java. It is a new version of Java and was released by Oracle on 18 March 2014. Java provided support for fu 9 min read
- Java IO : Input-output in Java with Examples Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 sta 6 min read
- Java.io.Reader class in Java Java Reader class is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or 5 min read
- Java.io.Writer Class in Java java.io.Writer class is an abstract class. It is used to write to character streams. Declaration of Writer Class in Javapublic abstract class Writer extends Object implements Appendable, Closeable, FlushableConstructors of Java Writer Classprotected Writer(): Creates a new character stream that can 6 min read
- Java.io.FileInputStream Class in Java FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Constructors of FileInputStream Class 1. FileInputStream(File file): 3 min read
- FileOutputStream in Java FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a file, we use FileOutputStream class. For writing byte-oriented and character-oriented data, we can use FileOutpu 5 min read
- Ways to read input from console in Java In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassThis is the Java classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamRe 5 min read
- Java.io.BufferedOutputStream class in Java Java.io.BufferedInputStream class in Java Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. Fie 2 min read
- Difference Between Scanner and BufferedReader Class in Java In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner class is a simple text scanner that can parse primitive types and strings. It internally uses regular expressions to read different types while on the other hand BufferedReader class reads text from a 3 min read
- 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 31 7 min read
Java Synchronization
- Synchronization in Java Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. Why use Java Synchronization?Java Synchronization is used to make sure by some synchronization method that only one thread can access th 5 min read
- Importance of Thread Synchronization in Java Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes 10 min read
- Method and Block Synchronization in Java Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent the 7 min read
- Difference Between Atomic, Volatile and Synchronized in Java Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes. There may be a chance of data inconsistency problem to overcome this problem we should go for a synchronized keyword when multiple threads are trying to operate simultaneously on the same j 5 min read
- Lock framework vs Thread synchronization in Java Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. T 5 min read
- Deadlock in Java Multithreading synchronized keyword is used to make the class or method thread-safe which means only one thread can have the lock of the synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock. It is important to use if our program is running in a mul 7 min read
- Deadlock Prevention And Avoidance When two or more processes try to access the critical section at the same time and they fail to access simultaneously or stuck while accessing the critical section then this condition is known as Deadlock. Deadlock prevention and avoidance are strategies used in computer systems to ensure that diffe 6 min read
- Difference Between Lock and Monitor in Java Concurrency Java Concurrency basically deals with concepts like multithreading and other concurrent operations. This is done to ensure maximum and efficient utilization of CPU performance thereby reducing its idle time in general. Locks have been in existence to implement multithreading much before the monitors 5 min read
- Reentrant Lock in Java Background The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don't offer any 9 min read
- Regular Expressions in Java In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi 8 min read
- Pattern pattern() method in Java with Examples The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not 2 min read
- Matcher pattern() method in Java with Examples The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax: public Pattern pattern() Parameters: This method do not accepts any parameter. Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher. Below examples illust 2 min read
- java.lang.Character class methods | Set 1 [caption id="attachment_151090" align="aligncenter" width="787"] lang.Character class wraps the value of a primitive data type - char to an object of datatype char and this object contains a single field having the data type - char. This class provides no. of methods regarding character manipulation 7 min read
- Quantifiers in Java Prerequisite: Regular Expressions in Java Quantifiers in Java allow users to specify the number of occurrences to match against. Below are some commonly used quantifiers in Java. X* Zero or more occurrences of X X? Zero or One occurrences of X X+ One or More occurrences of X X{n} Exactly n occurrenc 4 min read
Java Networking
- Java Networking When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is 15+ min read
- TCP/IP Model The TCP/IP model is a fundamental framework for computer networking. It stands for Transmission Control Protocol/Internet Protocol, which are the core protocols of the Internet. This model defines how data is transmitted over networks, ensuring reliable communication between devices. It consists of 14 min read
- User Datagram Protocol (UDP) User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection before data transfer. The UDP helps to establish low-late 10 min read
- Difference Between IPv4 and IPv6 In the digital world, where billions of devices connect and communicate, Internet Protocol (IP) Addresses play a crucial role. These addresses are what allow devices to identify and locate each other on a network. To know all about IP Addresses - refer to What is an IP Address? Currently, there are 10 min read
- Difference Between Connection-oriented and Connection-less Services In computer networks, communication between devices occurs using two types of services: connection-oriented and connectionless. These services define how data is transferred between a source and a destination. Connection-oriented services establish a dedicated connection before data transfer, ensuri 5 min read
- Socket Programming in Java This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection. There's a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) 5 min read
- java.net.ServerSocket Class in Java ServerSocket Class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). It is widely used so the ap 4 min read
- URL Class in Java with Examples URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it. Components of a URL A URL can have many forms. The most general however follows a th 4 min read
- Introduction to JDBC (Java Database Connectivity) JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language w 6 min read
- JDBC Drivers Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access any kind of tabular data, especially a relational database. JDBC Drivers uses JDBC APIs which was developed by Sun Microsystem, but now this is a p 4 min read
- Establishing JDBC Connection in Java Before Establishing JDBC Connection in Java (the front end i.e your Java Program and the back end i.e the database) we should learn what precisely a JDBC is and why it came into existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to ge 6 min read
- Types of Statements in JDBC The Statement interface in JDBC is used to create SQL statements in Java and execute queries with the database. There are different types of statements used in JDBC: Create StatementPrepared StatementCallable Statement1. Create a Statement: A Statement object is used for general-purpose access to d 6 min read
Java Memory Allocation
- Java Memory Management This article will focus on Java memory management, how the heap works, reference types, garbage collection, and also related concepts. Why Learn Java Memory Management? We all know that Java itself manages the memory and needs no explicit intervention of the programmer. Garbage collector itself ensu 6 min read
- How are Java objects stored in memory? In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only de 3 min read
- Stack vs Heap Memory Allocation Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program. Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of m 7 min read
- 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 b 4 min read
- How many types of memory areas are allocated by JVM? JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actuall 3 min read
- Garbage Collection in Java Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedica 9 min read
- Types of JVM Garbage Collectors in Java with implementation details prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To 5 min read
- Memory leaks in Java In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C, Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there 1 min read
- Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per 15+ min read
- Java Multiple Choice Questions Java is a widely used high-level, general-purpose, object-oriented programming language and platform that was developed by James Gosling in 1982. Java Supports WORA(Write Once, Run Anywhere) also, it defined as 7th most popular programming language in the world. Java language is a high-level, multi- 3 min read
Java Practice Problems
- Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs. Java is one of the most popular programming languages today because of it 9 min read
- Java Exercises - Basic to Advanced Java Practice Programs with Solutions Looking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers 8 min read
- Java Quiz | Level Up Your Java Skills The best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi 4 min read
Java Projects
- Top 50 Java Project Ideas For Beginners and Advanced [Update 2025] Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce. Building Java projects is an exce 15+ min read
- Number guessing game in Java The task is to write a Java program in which a user will get K trials to guess a randomly generated number. Below are the rules of the game: If the guessed number is bigger than the actual number, the program will respond with the message that the guessed number is higher than the actual number.If t 3 min read
- Mini Banking Application in Java In any Bank Transaction, there are several parties involved to process transaction like a merchant, bank, receiver, etc. so there are several numbers reasons that transaction may get failed, declined, so to handle a transaction in Java, there is a JDBC (Java Database Connectivity) which provides us 7 min read
- Java program to convert Currency using AWT Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. 4 min read
- Tic-Tac-Toe Game in Java In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For 6 min read
- Design Snake Game Let us see how to design a basic Snake Game that provides the following functionalities: Snake can move in a given direction and when it eats the food, the length of snake increases. When the snake crosses itself, the game will be over. Food will be generated at a given interval.Asked In: Amazon, Mi 9 min read
- Memory Game in Java The Memory Game is a game where the player has to flip over pairs of cards with the same symbol. We create two arrays to represent the game board: board and flipped. The board is an array of strings that represents the state of the game board at any given time.When a player flips a card, we replace 3 min read
- How to Implement a Simple Chat Application Using Sockets in Java? In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment). Java sockets can be connection-oriented or connection-less. In Java, we 4 min read
- Image Processing in Java - Face Detection Prerequisites: Image Processing in Java - Read and WriteImage Processing In Java - Get and Set PixelsImage Processing in Java - Colored Image to Grayscale Image ConversionImage Processing in Java - Colored Image to Negative Image ConversionImage Processing in Java - Colored to Red Green Blue Image C 3 min read
- Design Media Sharing Social Networking System PURPOSE OF MEDIA SOCIAL NETWORKING SERVICE SYSTEMThis system will allow users to share photos and videos with other users. Additionally, users can follow other users based on follow request and they can see other user's photos and videos. In this system, you can search users and see their profile if 14 min read
- Java Swing | Create a simple text editor To create a simple text editor in Java Swing we will use a JTextArea, a JMenuBar and add JMenu to it and we will add JMenuItems. All the menu items will have actionListener to detect any action.There will be a menu bar and it will contain two menus and a button: File menuopen: this menuitem is used 6 min read
- Technical Scripter
- Exception Handling
- Java-Exceptions
IMAGES
COMMENTS
May 4, 2010 · My intent in this answer is supplemental to the most basic of concepts of a null pointer. This simplest definition, as listed in many places is whenever a base value pointing to an address gets assigned a '0' or NULL value because the zero page, 0th memory location is part of the operating systems address space and operating system doesn't allow access to its address space by the user's program.
Oct 11, 2024 · NULL Pointer. Void Pointer. A NULL pointer does not point to anything. It is a special reserved value for pointers. A void pointer points to the memory location that may contain typeless data. Any pointer type can be assigned NULL. It can only be of type void. All the NULL pointers are equal. Void pointers can be different. NULL Pointer is a value.
Oct 19, 1993 · Technical Information Database TI500C.txt Null Pointer Assignment Errors Explained Category :General Platform :All Product :Borland C++ All Description: 1.
Criteria Uninitialized Pointer Null Pointer; Initialization: Does not point to a specific memory address until explicitly assigned. There is a need to explicitly assign the "NULL" or "0" value to indicate it does not point to any memory location.
That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal:
Sep 29, 2024 · When a pointer is holding a null value, it means the pointer is not pointing at anything. Such a pointer is called a null pointer. The easiest way to create a null pointer is to use value initialization: int main() { int* ptr {}; // ptr is now a null pointer, and is not holding an address return 0; }
Apr 17, 2024 · Sentinel Values: A null pointer can be used to indicate the end of a data structure or a list like in the linked list last node has a null pointer as the next field. Example of NULL Pointer in C++. The below example demonstrates the dereferencing and assignment of a null pointer to another value. C++
What is a Null Pointer? A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the segment. The null pointer basically stores the Null value while void is the type of the pointer. A null pointer is a special reserved value which is defined in a stddef header file.
5.17 Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types? 5.18 Is a run-time integral value of 0, cast to a pointer, guaranteed to be a null pointer? 5.19 How can I access an interrupt vector located at the machine's location 0? If I set a pointer to 0, the compiler ...
3 days ago · Reasons for Null Pointer Exception. A NullPointerException occurs due to below reasons: Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array. Accessing or modifying the slots of null objects, as if it were an array. Throwing null, as if it were a Throwable value.