I am starting to learn the Java programming language and I am a little confused.
I would like to create a simple program like adding two numbers or calculate the sum of n numbers. I can do this in C or Python easily, but in Java, I have to create a class for my program and then create a main class and call my program from it.
I use both Netbeans and IntelliJ.
Can I just create the program directly the way I do it in other languages? I mean is the concept of a class necessary in Java?
The creation of classes in Java is necessary because they give your program structure, and reduce the amount of code that is present in your program. Instead of creating a new state and behavior for each similar object in a program, you can simply call the class that has the template for the creation of that object.
A common reason to define a new class is to encapsulate related data in an object that can be treated as a single unit. That way, we can use objects as parameters and return values, rather than passing and returning multiple values.
Yes. In Java you always need one class with the function main to have the JRE run it.
In object-oriented programming, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
Can I just create the program directly the way I do it in other languages?
No.
I mean is the concept of class necessary in Java?
Yes. Every method, field etc is always in a class (or interface). Yes, that's an overhead for tiny programs - but for larger programs, the impact is pretty tiny.
As ever, use the right tool for the job - if you want a script of a few lines, use a scripting language. If you want more structure and organization, then you should expect a bit of "ceremony" to go with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With