Does Java support structs?

JavaData Structures

Java Problem Overview


Does Java have an analog of a C++ struct:

struct Member {
  string FirstName; 
  string LastName;  
  int BirthYear; 
};

I need to use my own data type.

Java Solutions


Solution 1 - Java

The equivalent in Java to a struct would be

class Member
{
    public String firstName; 
    public String lastName;  
    public int    birthYear; 
 };

and there's nothing wrong with that in the right circumstances. Much the same as in C++ really in terms of when do you use struct versus when do you use a class with encapsulated data.

Solution 2 - Java

Java definitively has no structs :) But what you describe here looks like a JavaBean kind of class.

Solution 3 - Java

Java 14 has added support for Records, which are structured data types that are very easy to build.

You can declare a Java record like this:

public record AuditInfo(
    LocalDateTime createdOn,
    String createdBy,
    LocalDateTime updatedOn,
    String updatedBy
) {}
 
public record PostInfo(
    Long id,
    String title,
    AuditInfo auditInfo
) {}

And, the Java compiler will generate the following Java class associated to the AuditInfo Record:

public final class PostInfo
        extends java.lang.Record {
    private final java.lang.Long id;
    private final java.lang.String title;
    private final AuditInfo auditInfo;
 
    public PostInfo(
            java.lang.Long id,
            java.lang.String title,
            AuditInfo auditInfo) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.lang.Long id() { /* compiled code */ }
 
    public java.lang.String title() { /* compiled code */ }
 
    public AuditInfo auditInfo() { /* compiled code */ }
}
 
public final class AuditInfo
        extends java.lang.Record {
    private final java.time.LocalDateTime createdOn;
    private final java.lang.String createdBy;
    private final java.time.LocalDateTime updatedOn;
    private final java.lang.String updatedBy;
 
    public AuditInfo(
            java.time.LocalDateTime createdOn,
            java.lang.String createdBy,
            java.time.LocalDateTime updatedOn,
            java.lang.String updatedBy) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.time.LocalDateTime createdOn() { /* compiled code */ }
 
    public java.lang.String createdBy() { /* compiled code */ }
 
    public java.time.LocalDateTime updatedOn() { /* compiled code */ }
 
    public java.lang.String updatedBy() { /* compiled code */ }
}

Notice that the constructor, accessor methods, as well as equals, hashCode, and toString are created for you, so it's very convenient to use Java Records.

A Java Record can be created like any other Java object:

PostInfo postInfo = new PostInfo(
    1L,
    "High-Performance Java Persistence",
    new AuditInfo(
        LocalDateTime.of(2016, 11, 2, 12, 0, 0),
        "Vlad Mihalcea",
        LocalDateTime.now(),
        "Vlad Mihalcea"
    )
);

Solution 4 - Java

Actually a struct in C++ is a class (e.g. you can define methods there, it can be extended, it works exactly like a class), the only difference is that the default access modfiers are set to public (for classes they are set to private by default).

This is really the only difference in C++, many people don't know that. ; )

Solution 5 - Java

Java doesn't have an analog to C++'s structs, but you can use classes with all public members.

Solution 6 - Java

Yes, Java doesn't have struct/value type yet. But, in the upcoming version of Java, we are going to get inline class which is similar to struct in C# and will help us write allocation free code.


inline class point { 
  int x;
  int y;
}

Solution 7 - Java

With Project JUnion you can use structs in Java by annotating a class with @Struct annotation

@Struct
class Member {
  string FirstName; 
  string LastName;  
  int BirthYear; 
}

More info at the project's website: https://tehleo.github.io/junion/

Solution 8 - Java

Yes, a class is what you need. An class defines an own type.

Solution 9 - Java

Structs "really" pure aren't supported in Java. E.g., C# supports struct definitions that represent values and can be allocated anytime.

In Java, the unique way to get an approximation of C++ structs

struct Token
{
    TokenType type;
    Stringp stringValue;
    double mathValue;
}

// Instantiation

{
    Token t = new Token;
}

without using a (static buffer or list) is doing something like

var type = /* TokenType */ ;
var stringValue = /* String */ ;
var mathValue = /* double */ ;

So, simply allocate variables or statically define them into a class.

Solution 10 - Java

Along with Java 14, it starts supporting Record. You may want to check that https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Record.html

public record Person (String name, String address) {}

Person person = new Person("Esteban", "Stormhaven, Tamriel");

And there are Sealed Classes after Java 15. https://openjdk.java.net/jeps/360

sealed interface Shape permits Circle, Rectangle {

  record Circle(Point center, int radius) implements Shape { }

  record Rectangle(Point lowerLeft, Point upperRight) implements Shape { } 
}

Solution 11 - Java

The short answer: NO.

The long answer:

  1. The main different between class and struct (in C++) is all properties in struct is public, which can be accessed from anywhere. For the class, you can apply limit it with different level of privacy.
  2. If you wanna have a data structure same as struct in C++, just make all properties public.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDmitryView Question on Stackoverflow
Solution 1 - JavaTom QuarendonView Answer on Stackoverflow
Solution 2 - JavaHeiko RuppView Answer on Stackoverflow
Solution 3 - JavaVlad MihalceaView Answer on Stackoverflow
Solution 4 - JavaDamian WojakowskiView Answer on Stackoverflow
Solution 5 - JavaEugene BurtsevView Answer on Stackoverflow
Solution 6 - Javaganesan arunachalamView Answer on Stackoverflow
Solution 7 - JavaLeoView Answer on Stackoverflow
Solution 8 - JavaMarkusView Answer on Stackoverflow
Solution 9 - JavaKlaider AnimekistView Answer on Stackoverflow
Solution 10 - JavaOrcunView Answer on Stackoverflow
Solution 11 - JavaPhung Manh CuongView Answer on Stackoverflow