Back to Java
2026-02-216 min read

Structs (Java)

Learn Structs (Java) step by step with clear examples and exercises.

Why This Matters

In this full guide on Java Structs, we will delve deep into the world of Java Structs, exploring their significance, prerequisites, core concepts, worked examples, common mistakes, practice questions, and frequently asked questions. Let's embark on this exciting journey together!

The Importance of Structs in Java

Structured data is a cornerstone in programming, allowing for efficient handling of complex information. Java Structs offer a simple yet powerful way to group related variables together, making it easier to work with them as a single entity. They are particularly useful when dealing with system calls, graphics, and custom data structures. In interviews, understanding Structs can help you tackle real-world programming problems and demonstrate your mastery of Java.

Prerequisites

To fully grasp the concept of Java Structs, you should have a solid foundation in:

  1. Basic Java syntax (variables, operators, loops, functions)
  2. Understanding classes and objects in Java
  3. Familiarity with data structures like arrays and lists
  4. Adequate understanding of inheritance and interfaces in Java (optional but beneficial for advanced topics)
  5. Knowledge of object-oriented programming principles
  6. Comfortable working with Java libraries such as Apache Commons Lang

Core Concept

A Java Struct is similar to a C struct but has some key differences. Unlike C, Java does not have built-in support for Structs. Instead, we create them using classes. Here's a simple example of a Point Struct:

public class Point {
private int x;
private int y;

// Constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

// Getters and Setters
public int getX() {
return x;
}

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

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}

In this example, x and y are private instance variables of the Point class, representing the coordinates of a point. To create an instance (object) of the Point Struct, you can use:

Point p = new Point(3, 4);

You can also define constructors, methods, and getters/setters within the class to make working with Structs more convenient. Additionally, using private instance variables and providing public getters and setters helps to encapsulate data, making it more secure.

Worked Example

Let's create a Student Struct that stores student information:

import java.util.ArrayList;

public class Student {
private String name;
private int age;
private double gpa;
private ArrayList<String> subjects;
private ArrayList<Double> grades;

// Constructor
public Student(String n, int a, double g) {
this.name = n;
this.age = a;
this.gpa = g;
this.subjects = new ArrayList<>();
this.grades = new ArrayList<>();
}

// Method to add a subject and grade
public void addSubjectAndGrade(String subject, double grade) {
subjects.add(subject);
grades.add(grade);
}

// Method to calculate and display the average grade
public void displayAverageGrade() {
double totalGrade = 0;
int count = subjects.size();

for (int i = 0; i < count; i++) {
totalGrade += grades.get(i);
}

System.out.println("Average Grade: " + (totalGrade / count));
}

// Method to display student information along with subject grades
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Subjects and Grades:");

for (int i = 0; i < subjects.size(); i++) {
System.out.println(subjects.get(i) + ": " + grades.get(i));
}
}
}

Now, let's create an instance of the Student Struct and display its information:

public class Main {
public static void main(String[] args) {
Student s1 = new Student("John Doe", 20, 3.5);
s1.addSubjectAndGrade("Math", 4.0);
s1.addSubjectAndGrade("English", 3.5);
s1.addSubjectAndGrade("Science", 3.8);
s1.displayInfo();
s1.displayAverageGrade();
}
}

This will output:

Name: John Doe
Age: 20
GPA: 3.5
Subjects and Grades:
Math: 4.0
English: 3.5
Science: 3.8
Average Grade: 3.7

Common Mistakes

  1. Forgetting to create a constructor: While Java automatically creates a no-argument constructor, it's essential to define one when initializing multiple instance variables.
  1. Accessing private instance variables without getters or setters: Always use getters and setters to access private instance variables of a Struct.
  1. Incorrectly defining the type of instance variables: Ensure that the data types of instance variables match their expected values.
  1. Ignoring the importance of encapsulation: Encapsulating data using private instance variables, getters, and setters provides a way to make the data more secure and easier to manage.
  1. Not understanding the difference between Structs and classes: Although similar, Structs and classes have key differences in terms of their usage and capabilities. While classes can contain methods and inheritance, Structs are primarily used for grouping variables together.
  1. Using public instance variables instead of private variables with getters and setters: Public instance variables make data more vulnerable to unintended modifications and should be avoided.

Practice Questions

  1. Create a Rectangle Struct with instance variables for width, height, area, perimeter, and a method to calculate the perimeter.
  1. Modify the Student Struct from the worked example to include additional instance variables like an address and phone number. Add getters and setters for these new variables, as well as a method to display the student's complete information.
  1. Create a Car Struct with instance variables for make, model, year, color, speed, and methods to increase the car's speed, decrease the car's speed, and display the car's current speed.
  1. Implement a Person Struct that includes instance variables for name, age, gender, and occupation. Add getters and setters for these variables, as well as a method to calculate and display the person's full-time equivalent (FTE) based on their occupation. For simplicity, assume that the FTE is 1 for employees, 0.5 for part-time workers, and 0.25 for interns.

FAQ

  1. Why can't I use C-style Structs in Java?
  • Java does not support C-style Structs directly due to differences in language design and syntax. Instead, we create Struct-like classes in Java.
  1. What are the advantages of using Structs in Java?
  • Structs simplify data management by grouping related variables together, making it easier to work with complex information. They also help reduce code duplication and improve readability.
  1. Can I define a static method within a Struct class in Java?
  • Yes, you can define static methods within a Struct class in Java. However, they cannot access instance variables directly without an object (instance) of the class.
  1. What is the difference between a Java class and a Struct?
  • A Java class represents an object with properties (instance variables) and behaviors (methods). On the other hand, a Struct is a simple data structure used to group related variables together without methods or inheritance.
  1. Why are getters and setters important in Java?
  • Getters and setters provide a way to encapsulate data, making it more secure and easier to manage. They also enable the creation of immutable objects and allow for easier unit testing.
  1. What is the difference between private, protected, and public access modifiers in Java?
  • Private variables can only be accessed within the same class, while protected variables can be accessed by the same class and subclasses within the same package or other packages. Public variables can be accessed from anywhere.
  1. What is the difference between a final variable and a constant variable in Java?
  • A final variable can be assigned a value once and cannot be changed afterward, while a constant variable (declared using the final keyword followed by an uppercase identifier) has a compile-time constant value that cannot be changed at runtime.
Structs (Java) | Java | XQA Learn