r/learnjava • u/AinsleyBoy • Sep 12 '21
Beginner, don't understand the general structure of Java
Learned Python when I was 13~, now I'm in high school and we're learning Java. I kind of just.. Don't get it.
Many questions, but:
Why is everything in a class? What's the point of that? In Python, classes were (to me) a better and more organized way of ordering data, for example when I have multiple characters (or even one if there are many many variables), having a class helps for obvious reasons. You can put many things in a framework without having 100+ variables. But.. Why everything? I feel like I don't understand classes enough to realize what they really are, which's support by the fact in python I just copy paste the same code to create classes because I don't get what it means and don't remember it. In anycase, seems really weird your ENTIRE program is just a class.
What's going on with starting up programs? My teacher admitted we're not really supposed to understand what's going on there yet, but I have some general knowledge so I think I could understand. So you have a class (refer to q1), then.. "public"? "static"? "void"? Only familiar face I can see is the "main" you specify for the main operation of the program, and even that I definitely do not fully understand.
Also, variables are kind of annoying. I get the need to define what kind of variable something is, but sometimes it's annoying. I get the fact that Python is slow exactly for reasons like trying to make variables more comfortable, I just wish for a general.. Explanation.
String arrays? Arraylists? Comparisons to Python will help.
Following the end of the third question, most of this comes from the fact I just don't understand the general structure and idea of Java, and what it's doing. Honestly, when I started with Python I saw one comment on my post telling me it's gonna be hard to move to other languages, and it was downvoted to death. Not saying this is hell, just that the extra syntax is kind of annoying, for now.
One last thing. I heard from online discussion that many people hate object oriented programming. Aren't class objects.. Objects? And Java is.. Just classes?
Thanks.
14
u/rootException Sep 12 '21
Java by default requires a bit more organization. When you build anything but single-file samples for class you will quickly appreciate that Java really expects you to put things in packages and classes.
public means "exposed to other code", static means "just a function, not part of an object" and main is just a naming convention from C in the 1960s or 1970s IIRC. So, when you tell Java to run your application, you tell it to find a class (based on the name you give it) and when you launch your app the Java runtime looks for the main method. This is pretty standard for any language descended from C.
You can use the var keyword in a lot of places and Java will just figure out the variable. Java is strongly typed, so it does everything it can to try to get you to tell it what you mean to avoid runtime errors (i.e. errors that appear when you run the program). Compile errors (getting an error when you try to compile) are vastly preferable to runtime errors - especially when you are trying to put software into production and don't want to get evening calls.
Java has a whole set of Collections, including Lists, Sets, Maps, etc. They have an interface (the contract) and then there are implementations (e.g. List is the interface, ArrayList is the implementation). Google something like Java Collections and you can get a good run through.
Yes, a class is basically a template for an object. I might have the Animal base class, a Cat class and a Dog class. Then I might have an instantiated object that's Fido and Meowster and whatever else.
My two cents: classes are a core feature, done (IMHO) well and easily in Java and C#. Having done some JavaScript, classes are really kind of a strange bolt-on with confusing prototype stuff and a lot of strange intermix. Trying to do the Animal, Cat, and Dog stuff in JavaScript is comparatively grim.
You might want to check out a book like Head First Java to supplement your class / teacher.
7
u/ryuzaki49 Sep 12 '21
Seems to me you are not familiar with OOP Foundations. You need to grasp the foundations.
I'll just answer the second question. To execute a Java program, your code needs a very special method:
public static void main(String[] args) {}
Every Java code needs that method to start. That's as simple as it gets. If you change public for private, or remove the static keywords, your Java code won't execute.
Public and private are keywords to modify access for a property or a method. There are different access levels (Public, Private, Protected, Package). And access means if a method inside a class can be called from another class.
Static is a little more complicated. If you don't want to create a new object just to call a method, you can create a static method inside a class. That way, you won't need the good old
MyClass object = new MyClass(); object.doSomething();
You can just say
MyClass.doSomething();
3
u/toltottgomba Sep 12 '21
I could write a long answer but i am tired today so sorry for that beforehand.
Python is a high language where java is a bit lower, you have more control over it.
In object oriented programming the point is to use abstractions, groupings, inheritance and to hide data and wrokings from the outside where noone sees it who shouldn't.
I think for you what you are looking for is OOP basics the idea behind it. It covers most of the questions you asked.
Java is developed with this in mind.
Sorry to not elaborate more on this but it would be too long. I suggest head first java which is a great book that gets you into there or just look up java and oop in general. What you need to understand is what the idea behind oop.
I hope this helped a bit.
3
u/Dantharo Sep 12 '21
by reading your post, maybe u should learn the concept of OOP (object oriented programming) this will give you more context to understand how java works, questioning "why everything is a class" is like "why java is oop"
2
u/slowfly1st Sep 12 '21
Classes are an OOP/OOD concept, not necessarily a java concept. You create objects based on classes. An object does have a specific task. That can be simply to hold data. It can be to validate data, check stock in the inventory, check user credentials or send a user a message that is order has arrived. Maybe think of classes as a tool to split your problems into smaller problems.
Why everything is a class was a design decision back then. Not sure about the answer, but my guess is: Promote OOP/OOD, and not have to deal with non-class based code. In the JVM "everything" is a class, so everything gets compiled into byte code (.class files). Dealing with "non-scoped-non-class-code" sounds complicated.
public static void are reserved words in java. Public means it's accessible from every other class, static means it's a 'class scoped' method, it needs to be static, otherwise the jvm has to instantiate the class, void is the return type.
About variables: Design decision. In later java version, you can declare non member variables without data type.
About Collections: Lookup "Java Collections Framework"
2
u/tidewater41009 Sep 12 '21
First concept: this programming language (Java) places a principal emphasis on reusability. When starting to learn a language (or early programming) one's emphasis is typically on logic or flow of control.
3
u/Spiritual-Day-thing Sep 13 '21 edited Sep 13 '21
Problem is what much of what you think you do know is also a vague assumption or simply wrong.
You learned some sloppy coding through Python. Go in from scratch again. Problem with Python is that it is flexible, can be script-like, object orientated, functional, and people who use it find that really fun to use. For a beginner it's great and not great.
Your frame of reference currently is nothing, just the hacky coding you once did. Lose it, start from scratch, learn what Java is, what OOP is. Stop comparing, as you are comparing it with nothing.
Later you'll go back to Python and understand both Java and Python much much better. Stop assuming and don't make grand theories about programming languages, that's all just noise. And a waste of time, as you could have used that to learn the syntax and acquire the skills.
1
u/ryuzaki49 Sep 12 '21
Classes is like having a blueprint of a house. Objects are materializing the blue prints (Actually using a built house)
1
u/popey123 Sep 13 '21
Implicitaly call of a variable alone bother me with javascript. I m happy with java
1
u/severoon Sep 13 '21
It will help to have a firm grounding in OO. One thing to realize is that pretty much all languages that claim to be object-oriented are really just degrees of object-oriented, but not fully. (There are a few notable exceptions such as Smalltalk, but those tend to be only used in academia.)
So you'll find OO features supported in many languages that aren't really strict about it, C++ and Python being good examples. Even Java is not strictly OO as it has primitives. (If it were designed and released today, it seems unlikely that they would have included primitives as it significantly complicates several of the libraries and the design of the language, and they were originally included only for performance anyway.)
Having said all that, you can think of a class as a template for creating objects of that class. For instance, a class might be Dog, and when you instantiate that class, or create an instance of it, you get a specific dog, like Spot. Generally speaking, classes hide the data they contain and only reveal methods to other code that wants to use the class.
When you learn OO you'll learn that the three pillars of OOP are encapsulation, inheritance, and polymorphism. This is true, and these are crucially important to understand, but what is often not explained early enough when teaching OO is that these are necessary to understand OO but not sufficient. What really matters about OO is how it allows code to interact in ways that create good dependencies in ways that allow software to grow and stay manageable.
What I mean by this is that you generally want to think about software as being split up into major modules, each of which that exists behind an interface that provides the high-level functionality of that module. For example you could think of something complicated like a web app like Gmail that does a great many things, but all of that is hidden from the client behind a control surface that just has functionality like "get messages in inbox" and "send email". So a good OO design follows this kind of approach at every level down, you split up your project into high level modules, and the code in each module depends only on the interfaces of the other modules it uses. Within a module you have a bunch of packages that interact in the same way, and within a package you have classes that also interact in the same way.
1
Sep 13 '21 edited Sep 13 '21
But.. Why everything?
Java is an OOP programming language.
But more importantly, a class is a unit of loadable code, which is what you import.
In Python you import a file and the Python interpreter will load it from the filesystem, executing the file as it is imported. This is why you have to use tricks like:
if __name__ == "__main__":to prevent code from running in a way it's not supposed to.
In Java, it is more structured. A class doubles as not just a class in the OOP sense, but also a module, since you can fill a class with static methods and never instantiate the class into an object.
When you load a class, code won't be executed unless you have special blocks like this:
static {
// code to execute when the class loads
}which is generally seen as bad form, because having random code run when all you import kind of makes things unpredictable.
What's going on with starting up programs?
Java programs do not run like Python programs.
With a Python program, you point the Python interpreter at a Python file, the Python interpreter loads the file and starts running it.
With Java programs, you point the JVM at a classpath (a collection of class files in the filesystem or bundled in a JAR file), and tell it the name of the "main" class. The JVM will figure out where the class actually is, load it and run it.
But run what? When the JVM loads the "main" class, it needs to know which method to call and how to call it. How will the JVM know how to give you the command line arguments?
This problem is solved by convention. You define a method with a specific name and a specific signature: a static method called main with takes a single String[] argument. Now the JVM knows exactly how to start the program.
Also, variables are kind of annoying
Java is statically typed.
Whether that is a good thing or not is a matter of opinion. For example, I find Python to be extremely annoying because it is dynamically typed.
String arrays? Arraylists? Comparisons to Python will help.
Oh boy.
If you're learning Java with a Python background, forget that arrays exist and stick with ArrayList. It's the closest thing to Python's list type.
Java is an old language, and made some choices to maximize performance when computers were more limited than today.
Java has a distinction between "primitives" and "objects". Arrays are kind of in the middle. They are technically objects, but they are very primitive.
An array gives you a chunk of contiguous memory to work with, so its cache friendly. Since reading from RAM is expensive, the processor won't read data from a single memory address but will grab a chunk of neighboring data too and put it into the a cache on the processor, so hopefully it doesn't have to make another trip to RAM.
Objects require "dereferencing", which busts the cache. The thing you want isn't actually in the array, the array just has a pointer to where the data actually is. You just messed up the processor's plan.
A primitive value is stored right there, so when you read another index in the array, the processor already did the work, so your code is friendly to the processor, making it faster.
Strings are objects and don't benefit from this. So use an ArrayList. Don't mess with arrays unless you have to because of an ancient or paranoid API or you have specific performance enhancements in mind.
Python operates at a much higher level, and doesn't concern itself with all this.
Regarding paranoid APIs. I write a lot of security sensitive code. I have to decrypt keys and deal with passwords. I like storing those in arrays because I can store the decrypted data for as long as absolutely necessary and then fill the array with zeros when I'm done. You never know who is snooping your program's memory...
1
u/AutoModerator Sep 13 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
11
u/ignotos Sep 12 '21
It's really just a decision they made when designing Java. There is some benefit to not having any distinction between "code in a class" and "code outside a class", as it makes everything consistent. Also in Java classes are the things which you import, whereas in Python code is wrapped up into modules.
Because there is no "code outside a class" / "main script", there needs to be some way to indicate which code in which class is the start-point for the program, and "public static void main" is the way to do this. "public", "static" and "void" are not totally random, and do have specific meanings and purposes which you will learn over time.
It's more rigid and long-winded, but it's also more thorough and rigourous - it prevents certain kinds of mistakes when coding. Again though, it's just a design decision which was made when creating Java.
Java does actually allow some shortcuts where you don't always need to specify the type of a variable, which you will be introduced to at some point