Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Variables
Next article icon

Java Data Types

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java is statically typed and also a strongly typed language because 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 declared with the specific data types.

Data types in Java are of different sizes and values that can be stored in a variable that is made as per convenience and circumstances to cover up all test cases.

Why Data Types Matter in Java?

Data types matter in Java because of the following reasons, which are listed below:

  • Memory Efficiency: Choosing the right type (byte vs int) saves memory.
  • Performance: Proper types reduce runtime errors.
  • Code Clarity: Explicit typing makes code more readable.

Java Data Type Categories

Java has two categories in which data types are segregated

  • Primitive Data Type: These are the basic building blocks that store simple values directly in memory. Examples of primitive data types are boolean, char, byte, short, int, long, float, and double.

Note: The Boolean with uppercase B is a wrapper class for the primitive boolean type.

  • Non-Primitive Data Types (Object Types): These are reference types that store memory addresses of objects. Examples of Non-primitive data types are String, Array, Class, Interface, and Object

Primitive vs Non-Primitive Data Types

The table below demonstrates the difference between Primitive and Non-Primitive Data types

Aspect

Primitive

Non-Primitive

Memory

Stored on the stack

Stored on heap

Speed

Primitive data types are faster

Non-primitive data types are slower

Example

int x = 5;

String s = “Geeks”;

Example: This example demonstrates the addition of two integers using the int data type in Java.

Java
// Java Program to demonstrate int data-type import java.io.*;  class GFG  {     public static void main (String[] args)      {       	// declaring two int variables         int a = 10;       	int b = 20;              	System.out.println( a + b );     } } 

Output
30 

The below diagram demonstrates different types of primitive and non-primitive data types.

Java Data Types

Data Types in JAVA

Primitive Data Types in Java

Primitive data store only single values and have no additional capabilities. There are 8 primitive data types. They are depicted below in tabular format below as follows:

Type

Description

Default

Size

Example Literals

Range of values

boolean true or false false JVM-dependent (typically 1 byte) true, false

true, false

byte 8-bit signed integer 0 1 byte (none)

-128 to 127

char Unicode character(16 bit) \u0000 2 bytes ‘a’, ‘\u0041’, ‘\101’, ‘\\’, ‘\’, ‘\n’, ‘β’

0 to 65,535 (unsigned)

short 16-bit signed integer 0 2 bytes (none)

-32,768 to 32,767

int 32-bit signed integer 0 4 bytes -2,0,1

-2,147,483,648

to

2,147,483,647

long 64-bit signed integer 0L 8 bytes -2L,0L,1L

-9,223,372,036,854,775,808

to

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

float 32-bit IEEE 754 floating-point 0.0f 4 bytes 3.14f, -1.23e-10f

~6-7 significant decimal digits

double 64-bit IEEE 754 floating-point 0.0d 8 bytes 3.1415d, 1.23e100d

~15-16 significant decimal digits

Primitive Data Types

1. boolean Data Type

The boolean data type represents a logical value that can be either true or false. Conceptually, it represents a single bit of information, but the actual size used by the virtual machine is implementation-dependent and typically at least one byte (eight bits) in practice. Values of the boolean type are not implicitly or explicitly converted to any other type using casts. However, programmers can write conversion code if needed.

Syntax:

boolean booleanVar;

Size : Virtual machine dependent (typically 1 byte, 8 bits)

Example: This example, demonstrating how to use boolean data type to display true/false values.

Java
// Demonstrating boolean data type public class Geeks {     public static void main(String[] args) {         boolean b1 = true;         boolean b2 = false;          System.out.println("Is Java fun? " + b1);           System.out.println("Is fish tasty? " + b2);      } } 

Output
Is Java fun? true Is fish tasty? false 

2. byte Data Type

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

Syntax:

byte byteVar;

Size : 1 byte (8 bits)

Example: This example, demonstrating how to use byte data type to display small integer values.

Java
// Demonstrating byte data type public class Geeks {     public static void main(String[] args) {         byte a = 25;         byte t = -10;          System.out.println("Age: " + a);           System.out.println("Temperature: " + t);      } } 

Output
Age: 25 Temperature: -10 

3. short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is used when memory savings matter, especially in large arrays where space is constrained.

Syntax:

short shortVar;

Size : 2 bytes (16 bits)

Example: This example, demonstrates how to use short data type to store moderately small interger value.

Java
// Demonstrating short data types public class Geeks {     public static void main(String[] args) {         short num = 1000;         short t = -200;          System.out.println("Number of Students: " + num);           System.out.println("Temperature: " + t);      } } 

Output
Number of Students: 1000 Temperature: -200 

4. int Data Type

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

Syntax:

int intVar;

Size : 4 bytes ( 32 bits )

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

Example: This example demonstrates how to use int data type to display larger integer values.

Java
// Demonstrating int data types public class Geeks {     public static void main(String[] args) {         int p = 2000000;         int d = 150000000;          System.out.println("Population: " + p);          System.out.println("Distance: " + d);     } } 

Output
Population: 2000000 Distance: 150000000 

5. long Data Type

The long data type is a 64-bit signed two’s complement integer. It is used when an int is not large enough to hold a value, offering a much broader range.

Syntax:

long longVar;

Size : 8 bytes (64 bits)

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

Example: This example demonstrates how to use long data type to store large interger value.

Java
// Demonstrating long data type public class Geeks {     public static void main(String[] args) {         long w = 7800000000L;         long l = 9460730472580800L;          System.out.println("World Population: " + w);           System.out.println("Light Year Distance: " + l);     } } 

Output
World Population: 7800000000 Light Year Distance: 9460730472580800 

6. float Data Type

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. The size of the float data type is 4 bytes (32 bits).

Syntax:

float floatVar;

Size : 4 bytes (32 bits)

Example: This example demonstrates how to use float data type to store decimal value.

Java
// Demonstrating float data type public class Geeks {     public static void main(String[] args) {         float pi = 3.14f;         float gravity = 9.81f;          System.out.println("Value of Pi: " + pi);           System.out.println("Gravity: " + gravity);      } } 

Output
Value of Pi: 3.14 Gravity: 9.81 

7. double Data Type

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. The size of the double data type is 8 bytes or 64 bits.

Syntax:

double doubleVar;

Size : 8 bytes (64 bits)

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

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

Example: This example demonstrates how to use double data type to store precise decimal value.

Java
// Demonstrating double data type public class Geeks {     public static void main(String[] args) {         double pi = 3.141592653589793;         double an = 6.02214076e23;          System.out.println("Value of Pi: " + pi);           System.out.println("Avogadro's Number: " + an);      } } 

Output
Value of Pi: 3.141592653589793 Avogadro's Number: 6.02214076E23 

8. char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

Syntax:

char charVar;

Size : 2 bytes (16 bits)

Example: This example, demonstrates how to use char data type to store individual characters.

Java
// Demonstrating char data type public class Geeks{     public static void main(String[] args) {         char g = 'A';         char s = '$';          System.out.println("Grade: " + g);          System.out.println("Symbol: " + s);      } } 

Output
Grade: A Symbol: $ 

Why is the Size of char 2 bytes in Java?

Unlike languages such as C or C++ that use the ASCII character set, Java uses the Unicode character set to support internationalization. Unicode requires more than 8 bits to represent a wide range of characters from different languages, including Latin, Greek, Cyrillic, Chinese, Arabic, and more. As a result, Java uses 2 bytes to store a char, ensuring it can represent any Unicode character.

Example: Here we are demonstrating how to use various primitive data types.

Java
// Java Program to Demonstrate Char Primitive Data Type  class GFG  {     public static void main(String args[])     {          // Creating and initializing custom character         char a = 'G';          // Integer data type is generally         // used for numeric values         int i = 89;          // use byte and short         // if memory is a constraint         byte b = 4;          // this will give error as number is         // larger than byte range         // byte b1 = 7888888955;          short s = 56;          // this will give error as number is         // larger than short range         // short s1 = 87878787878;          // by default fraction value         // is double in java         double d = 4.355453532;          // for float use 'f' as suffix as standard         float f = 4.7333434f;          // need to hold big range of numbers then we need         // this data type         long l = 12121;          System.out.println("char: " + a);         System.out.println("integer: " + i);         System.out.println("byte: " + b);         System.out.println("short: " + s);         System.out.println("float: " + f);         System.out.println("double: " + d);         System.out.println("long: " + l);     } } 

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

Non-Primitive (Reference) Data Types

The Non-Primitive (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.

1. Strings

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

Syntax: Declaring a string

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

Example: This example demonstrates how to use string variables to store and display text values.

Java
// Demonstrating String data type public class Geeks {     public static void main(String[] args) {         String n = "Geek1";         String m = "Hello, World!";          System.out.println("Name: " + n);          System.out.println("Message: " + m);      } } 

Output
Name: Geek1 Message: Hello, World! 

Note: String cannot be modified after creation. Use StringBuilder for heavy string manipulation

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

  • Modifiers : A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java
  • Class name: The name should begin with an initial letter (capitalized by convention).
  • 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.
  • 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.
  • Body: The class body is surrounded by braces, { }.

Example: This example demonstrates how to create a class with a constructor and method, and how to create an object to call the method.

Java
// Demonstrating how to create a class class Car {     String model;     int year;      Car(String model, int year) {         this.model = model;         this.year = year;     }      void display() {         System.out.println(model + " " + year);     } }  public class Geeks {     public static void main(String[] args) {         Car myCar = new Car("Toyota", 2020);         myCar.display();      } } 

Output
Toyota 2020 

3. Object

An Object 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 :

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

Example: This example demonstrates how to create the object of a class.

Java
// Define the Car class class Car {     String model;     int year;      // Constructor to initialize the Car object     Car(String model, int year) {         this.model = model;         this.year = year;     } }  // Main class to demonstrate object creation public class Geeks {     public static void main(String[] args) {         // Create an object of the Car class         Car myCar = new Car("Honda", 2021);          // Access and print the object's properties         System.out.println("Car Model: " + myCar.model);          System.out.println("Car Year: " + myCar.year);       } } 

Output
Car Model: Honda Car Year: 2021 

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

Example: This example demonstrates how to implement an interface.

Java
// Demonstrating the working of interface interface Animal {     void sound(); }  class Dog implements Animal {     public void sound() {         System.out.println("Woof");     } }  public class InterfaceExample {     public static void main(String[] args) {         Dog myDog = new Dog();         myDog.sound();      } } 

Output
Woof 

5. Array

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

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

Example: This example demonstrates how to create and access elements of an array.

Java
// Demonstrating how to create an array public class Geeks {     public static void main(String[] args) {         int[] num = {1, 2, 3, 4, 5};         String[] arr = {"Geek1", "Geek2", "Geek3"};          System.out.println("First Number: " + num[0]);           System.out.println("Second Fruit: " + arr[1]);     } } 

Output
First Number: 1 Second Fruit: Geek2 

Key Points to Remember:

  • Strong Typing: Java enforces strict type checking at compile-time, reducing runtime errors.
  • Memory Efficiency: Choosing the right data type based on the range and precision needed helps in efficient memory management.
  • Immutability of Strings: Strings in Java cannot be changed once created, ensuring safety in multithreaded environments.
  • Array Length: The length of arrays in Java is fixed once declared, and it can be accessed using the length attribute

Understanding Java’s data types is fundamental to efficient programming. Each data type has specific use cases and constraints, making it essential to choose the right type for the task at hand. This ensures optimal memory usage and program performance while leveraging Java’s strong typing system to catch errors early in the development process.

Check Out: Quiz on Data Type in Java



Next Article
Java Variables

S

Shubham Agrawal
Improve
Article Tags :
  • Java
  • java-basics
  • Java-Data Types
Practice Tags :
  • Java

Similar Reads

  • Java Tutorial
    Java is a high-level, object-oriented programming language used to build applications across platforms—from web and mobile apps to enterprise software. It is known for its Write Once, Run Anywhere capability, meaning code written in Java can run on any device that supports the Java Virtual Machine (
    11 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
      9 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, televisions, etc. Originally, C++ was considered to be used in the project, but the idea was rejected for se
      6 min read

    • How to Install Java on Windows, Linux and macOS?
      Java is a versatile programming language widely used for building applications. To start coding in Java, you first need to install the Java Development Kit (JDK) on your system. This article provides detailed steps for installing Java on Windows 7, 8, 10, 11, Linux Ubuntu, and macOS. Download and In
      5 min read

    • Setting up Environment Variables For Java - Complete Guide to Set JAVA_HOME
      In the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
      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
      Understanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is: JDK: Java Development Kit is a software devel
      4 min read

    Java Basics

    • Java Syntax
      Java is an object-oriented programming language that 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. Java Syntax refers to a set of rules that define how Java programs are w
      6 min read

    • Java Hello World Program
      Java is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
      6 min read

    • Java Identifiers
      An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name. Example: public class Test{ public static void main(String[] args) { int a =
      2 min read

    • Java Keywords
      In Java, keywords are the reserved words that have some predefined meanings and are used by the Java compiler for some internal process or represent some predefined actions. These words cannot be used as identifiers such as variable names, method names, class names, or object names. Now, let us go t
      5 min read

    • Java Data Types
      Java is statically typed and also a strongly typed language because 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 declared with the specifi
      15 min read

    • Java Variables
      In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Key Components of Variables in Java: A variable in Java has three components, which are listed below: Data Type: Defines the k
      9 min read

    • Scope of Variables in Java
      The scope of variables 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 the function call stack. In this article, we will learn about
      7 min read

    • Java Operators
      Java operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
      15 min read

    • Java User Input - Scanner Class
      The most common way to take user input in Java is using the Scanner class. It is a part of java.util package. The scanner class can handle input from different places, like as we are typing at the console, reading from a file, or working with data streams. This class was introduced in Java 5. Before
      4 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. Now let's go through a simple Java for l
      5 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: Using a for-each l
      8 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, the continue statement is used inside the loops such as for, while, and do-while to skip the current 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 Geeks { public static void mai
      4 min read

    • Java return Keyword
      return keyword in Java is a reserved keyword which is used to exit from a method, with or without a value. The usage of the return keyword can be categorized into two cases: Methods returning a valueMethods not returning a value1. Methods Returning a ValueFor the methods that define a return type, t
      4 min read

    Java Methods

    • Java Methods
      Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects. Example: Java program to demonstrate how to cre
      8 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 Method vs Instance Method in Java
      In Java, methods are mainly divided into two parts based on how they are associated with a class, which are the static method and the Instance method. The main difference between static and instance methods is: Static method: This method belongs to the class and can be called without creating an obj
      4 min read

    • Access Modifiers in Java
      In Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
      7 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 simplify the creation of methods that need to take a variable number of arguments. Example: We will see the demonstration of using Varargs in Java to pass a variable number of argum
      5 min read

    Java Arrays

    • Arrays in Java
      Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
      15+ min read

    • How to Initialize an Array in Java?
      An array in Java is a linear data structure, which is used to store multiple values of the same data type. In array each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java.
      6 min read

    • Java Multi-Dimensional Arrays
      Multidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
      10 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 an Object class. The methods of this class can be used by the class name itself. Th
      15 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

    • Java Strings
      In Java, a String is the type of object that can store a 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, allowi
      10 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 are going to learn why strings are immutable in Java and how this benefits Java applications. What Does Immutable Mean?When w
      4 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
      A 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 are going to learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import
      7 min read

    • StringBuffer Class in Java
      The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters. Features of StringBuffer ClassThe key features of StringBuffer
      11 min read

    • Java StringBuilder Class
      In Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations. Declaration: StringBuilder sb = n
      7 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. In Java, String, StringBuilder, and StringBuffer are used for handling strings. The main difference is: String: Immutable, meaning its value cannot be changed onc
      6 min read

    Java OOPs Concepts

    • Java OOP(Object Oriented Programming) Concepts
      Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable. The core idea of OOPs is to bind data and the functions that operate on it,
      13 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, or in other words, we can say that a class is a blueprint for objects, wh
      12 min read

    • Java Constructors
      In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
      10 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 of hiding the implementation details and only showing the essential details or features to the user. It allows to focus on what an object does rather than how it does it. The unnecessary details are not displayed to the user. Key features of abstraction: Abstractio
      10 min read

    • Encapsulation in Java
      Encapsulation is one of the core concepts in Java Object-Oriented Programming (OOP). It is the process of wrapping data (variables) and methods that operate on the data into a single unit, i.e., a class. Encapsulation is used to hide the internal implementation details of a class. This technique ens
      10 min read

    • Inheritance in Java
      Java Inheritance is a fundamental concept in 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 an
      14 min read

    • Polymorphism in Java
      Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
      7 min read

    • Method Overloading in Java
      In Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference can be in the number of parameters, the types of parameters, or the order of those parameters. Method overloading in Java is also known as Compile-time Polymor
      10 min read

    • Overriding in Java
      Overriding in Java occurs when a subclass or child class implements a method that is already defined in the superclass or base class. When a subclass provides its own version of a method that is already defined in its superclass, we call it method overriding. The subclass method must match the paren
      15 min read

    • Java Packages
      Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie
      9 min read

    Java Interfaces

    • Java Interface
      An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface: The interface in Java is a mechanism to
      13 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. Example: [GFGTABS] Java //Driver Code Starts{ // A class can implement multiple interfaces import java.io.*; //Driver Code
      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 behaviour of objects.An interface defines the methods that a class must implement.Class
      5 min read

    • Java Functional Interfaces
      A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can have multiple default or static methods, but only one abstract method. Runnable, ActionListener, and Comparator are common examples of Java functional interfaces. From Java 8 onwards, lam
      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
      Marker Interface in Java is an empty interface means having no field or methods. Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. Example: [GFGTABS] Java //Driver Code Starts{ interface Serializable { // Marker Interface } //Dr
      4 min read

    • Java Comparator Interface
      The Comparator interface in Java is used to sort the objects of user-defined classes. The Comparator interface is present in java.util package. This interface allows us to define custom comparison logic outside of the class for which instances we want to sort. The comparator interface is useful when
      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 the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features: Maintained the order of elements in which they are added.Allows
      15+ min read

    • ArrayList in Java
      Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
      10 min read

    • Vector Class in Java
      The Vector class in Java implements a growable array of objects. Vectors were legacy classes, but now it is fully compatible with collections. It comes under java.util package and implement the List interface. Key Features of Vector: It expands as elements are added.Vector class is synchronized in n
      12 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
      The Java Collection framework provides a Stack class, which implements a Stack data structure. The class is based on the basic principle of LIFO (last-in-first-out). Besides the basic push and pop operations, the class also provides three more functions, such as empty, search, and peek. The Stack cl
      12 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 duplicat
      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 a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features: Most implementations, like PriorityQueue, do not allow null elements.Implementation Clas
      12 min read

    • PriorityQueue in Java
      The PriorityQueue class in Java is part of the java.util package. It implements a priority heap-based queue that processes elements based on their priority rather than the FIFO (First-In-First-Out) concept of a Queue. Key Points: The PriorityQueue is based on the Priority Heap. The elements of the p
      9 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, the Map Interface is part of the java.util package and represents a mapping between a key and a value. The Java Map interface is not a subtype of the Collections interface. So, it behaves differently from the rest of the collection types. Key Features: No Duplicates in Keys: Keys should be
      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
      Hashtable class, introduced as part of the 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 hashCode method an
      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
      9 min read

    • Java Comparator Interface
      The Comparator interface in Java is used to sort the objects of user-defined classes. The Comparator interface is present in java.util package. This interface allows us to define custom comparison logic outside of the class for which instances we want to sort. The comparator interface is useful when
      6 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 interfaces 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
      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

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences