
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program Without Making Class
Is it possible to create and run a Java program without any class? The answer is Yes. The trick is to use an enum instead of a Class.
Enums are similar to classes, but instead of using the class keyword, we use enum to define them. An enum is used to represent a public static constant. It can have a static main method as well.
Steps to write Java program without making class
Following are the steps to write a Java program without making class ?
- We will start by defining an enum instead of a class. An enum typically represents constants, but it can also include methods.
- Define the constants and add constants inside the enum.
- Inside the enum, define the main() method as you would in a class. This is where the program execution starts.
- Print enum values and use the toString() method to print the enum values.
- Since the program has a main() method, you can run it directly without a class.
Java program without making class
Below is the Java program without making class ?
public enum Tester { C, Java, PHP; public static void main(String[] args) { System.out.println("Programming in " + Tester.C.toString()); System.out.println("Programming in " + Tester.Java.toString()); System.out.println("Programming in " + Tester.PHP.toString()); } }
Output
Programming in C Programming in Java Programming in PHP
Code Explanation
In the above example, the enum Tester defines three constants: C, Java, and PHP. The main() method prints these constants by calling the toString() method on each one. Even though it's an enum, Java allows the program to run without any issues because the main() method is included within the enum, effectively replacing the need for a class.