0
0
Javaprogramming~15 mins

Static vs non-static behavior in Java - Hands-On Comparison

Choose your learning style8 modes available
folder_codeStatic vs Non-Static Behavior in Java
📖 Scenario: Imagine you are creating a simple program to track the number of books created in a library system. Each book has its own title, but the total number of books is shared across all books.
🎯 Goal: You will build a Java program that shows the difference between static and non-static behavior by counting how many book objects are created and displaying each book's title.
📋 What You'll Learn
Create a Book class with a non-static title variable
Add a static variable bookCount to count all books created
Create a constructor that sets the title and increments bookCount
Write code to create multiple Book objects
Print each book's title and the total number of books using static and non-static variables
💡 Why This Matters
🌍 Real World
Tracking shared data like total users, total sales, or total items created is common in many software systems.
💼 Career
Understanding static vs non-static behavior is essential for writing efficient and correct Java programs in professional development.
Progress0 / 4 steps
1
Create the Book class with a non-static title
Create a class called Book with a non-static String variable called title. Add a constructor that takes a String parameter called title and sets the class variable this.title to it.
Java
💡 Need a hint?

Remember, non-static variables belong to each object. Use this.title to set the instance variable.

2
Add a static variable to count books
Inside the Book class, add a static integer variable called bookCount and initialize it to 0. Then, inside the constructor, add code to increase bookCount by 1 each time a new Book object is created.
Java
💡 Need a hint?

Static variables belong to the class, not to individual objects. Increment bookCount inside the constructor.

3
Create multiple Book objects in main method
Create a public static void main(String[] args) method inside a class called Library. Inside main, create three Book objects with titles "Java Basics", "Python Guide", and "Web Development".
Java
💡 Need a hint?

Remember to create the Library class and write the main method inside it. Use the new keyword to create objects.

4
Print each book's title and total book count
Inside the main method, add code to print each book's title using System.out.println and the non-static title variable. Then print the total number of books created using the static variable Book.bookCount.
Java
💡 Need a hint?

Use System.out.println to print each book's title and the static bookCount with the class name Book.bookCount.