r/javahelp • • Aug 14 '22

Basic Java questions thread

Hello, I'm coming from C++ and having to learn some Java pretty quickly. I have some questions, and wanted to post in a single thread, so that I'm not flooding /r/javahelp.

I'll post my questions in the comments. Anyone else is free to answer or ask qs of their own. Thank you.

20 Upvotes

33 comments sorted by

•

u/AutoModerator Aug 14 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

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

u/rootseat Aug 14 '22

I see code

MovieFinder finder = (MovieFinder)ServiceLocator.getService("MovieFinder");

What are some reasons in Java to typecast? I can only think of MovieFinder being a parent class of whatever the .getService() method returns. I guess in C++ and C, you can also perform this to re-factor the members' memory allocation, but I'm not sure if Java does anything like that.

6

u/fletku_mato Aug 14 '22

MovieFinder would probably be a subclass of whatever the ServiceLocator is returning, I'm guessing an Object because it's picking an object from somewhere by String value. The ServiceLocator probably only works with Objects.

1

u/rootseat Aug 14 '22

I'm interested to know why Object class gets a higher probability in your assessment than a class that sits somewhere between Object and MovieFinder. Is there something special about string methods and the Java base Object class?

2

u/fletku_mato Aug 14 '22

I think that in this case ServiceLocator could return any class, and the writer could not know what classes it would be used for.

1

u/rootseat Aug 14 '22

Ah ok, so in part due to the fact that I give no other context than that one line. Makes sense.

2

u/djavaman Aug 15 '22

Object is the root class for all Java classes. So at some point, it has to be Object.

3

u/dionthorn this.isAPro=false; this.helping=true; Aug 14 '22 edited Aug 14 '22

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

Check section 5.5. Casting Conversion thru 5.5.3. Checked Casts at Run Time

1

u/rootseat Aug 14 '22

Is the following true or false?

Java packages are imported. When a source file contains the line import foo.bar.baz, we are asking the compiler to find all the files that contain the line package foo.bar.baz.

So when I have the following in file.java:

package a.b.c

import x.y.z

class Yay {}

Then my intent would be that Yay depends on x.y.z, and also that a.b.c is required by some other class elsewhere.

5

u/dionthorn this.isAPro=false; this.helping=true; Aug 14 '22 edited Aug 14 '22

https://docs.oracle.com/javase/tutorial/java/package/index.html

foo.bar.baz is a package

Do note we cannot give explicit answers to homework questions.

2

u/djavaman Aug 15 '22

"we are asking the compiler to find all the files"

No. We are asking the compiler to find all the classes. The classes are typically compiled and in Jar files.

1

u/fletku_mato Aug 14 '22

If someone wants to import your class, they would have to import a.b.c.Yay

1

u/AreTheseMyFeet Aug 15 '22

Or, for completeness, import a.b.c.*.
The wildcard will import all classes directly under package/folder a.b.c.

Generally reserved for cases where you are importing multiple classes from the same package. Though it's commonly preferred to only use it for ~4-5+ imports, any fewer and it's cleaner/clearer/more readable to implicitly import the handful of classes directly rather than the entire package.

1

u/A_random_zy Nooblet Brewer Aug 15 '22

Unrelated to your question but a tip.

Note that your java src file name should be the same as public class name.

for example xyz.java file should have a public class named xyz.

1

u/[deleted] Aug 15 '22

"a.b.c is required by some other class"

Not necessarily, no. Other classes may import your Yay class and for this they would need to import "a.b.c", yes.

1

u/rootseat Aug 14 '22

This makes sense to me:

class Class {}
obj = Class();
result = obj.call();

I've never seen this kind of thing before:

class JavaClass {}
result = JavaClass.call();

What's going on here?

3

u/MonkConsistent2807 Aug 14 '22

thats only possible when the call() method is a static one so you referenz it via the classname you cann also import the class and just call the method call() within the code (without the JavaClass. thing) but this is more confusing thwn helping

for example in testing code with mockito there is often the static when-method imported that way

hope this helps or give at least a point to look at :)

1

u/rootseat Aug 14 '22

good point

3

u/fletku_mato Aug 14 '22

The call()-method is static. Using static methods makes sense when the method does not need any internal state of an instance of the class.

It very common to create utility classes that have only static methods. Eg. CollectionUtils.isNotEmpty(someList);

2

u/rootseat Aug 14 '22

Crystal clear thanks. Can you have standalone functions in Java? Probably not, right? I noticed that even the call to main() has to be in the context of a class.

7

u/fletku_mato Aug 14 '22

No, you always need a class, there are no standalone functions. Everything lives inside a class which lives inside a package.

2

u/dionthorn this.isAPro=false; this.helping=true; Aug 14 '22

We have some fancy lambdas if you want to inline a function without making a full on method

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

5

u/dionthorn this.isAPro=false; this.helping=true; Aug 14 '22 edited Aug 14 '22

.call() is a static method of the JavaClass object.

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

1

u/rootseat Aug 15 '22

How do you inspect the entire annotation hierarchy for frameworks you're new to? For example, @SpringBootApplication calls @Configuration, @EnableAutoConfiguration, and @ComponentScan. But I wouldn't have known there was a hierarchy from simply reading the code.

From looking at examples of standard annotations, I can see they have a lot of power, i.e. can affect the runtime behavior pretty arbitrarily. For example, @PostConstruct and @PreDestroy. So, how is it doing this behind the syntax? For example, are annotations decorators?

2

u/fletku_mato Aug 15 '22

The annotations are just metadata that is used by the framework or sometimes some code preprocessor (eg. Lombok), so not really the same as decorators.

Spring does a lot of stuff with annotations at runtime.

1

u/rootseat Aug 15 '22

Does this mean all annotations will be found in some xml file somewhere?

Also, the corresponding xml metadata for a given annotated Java entity will have some custom parameters, e.g. 'autowire="byName"'. Then there is a class "org.springframework.beans.factory.annotation.Autowired". Does this mean Autowired will modify the behavior of the annotated class? What is the best way to think about this?

2

u/fletku_mato Aug 16 '22

I'm not an expert on Spring Boot internals, but if you compile and decompile some Spring Boot application, you will see that the annotations are preserved.

When a Spring Boot application starts, it builds an application context. This is where the magic happens. If you have a class that is annotated @Component, Spring knows to create an instance from this class. If the annotated class has some fields annotated @Autowired, Spring knows to set the field values with Reflection API (although I think the way this works might change in near future, as Spring is targeting native).

You can check for example https://github.com/spring-projects/spring-framework/blob/main/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

All of this wiring happens at runtime.

1

u/rootseat Aug 16 '22
  • So you're saying @Autowired is the setter portion of the automated behavior, right? Also, do you've any idea where the term "wiring" comes from?

  • Do you've any idea why annotations are sometimes explicitly taught/advertised as not changing the behavior of the program? Because I'm thinking Spring annotations are all about DI, which in turn is about controlling object dependencies AND object lifetimes, both of which can be seen as changing the behavior of the program, no?

2

u/fletku_mato Aug 16 '22

I think the automated behaviour depends on both, having a bean, a value or a component that is injectable, and the annotation that injects it. It is just wiring one spring-handled object to another. Same as passing it via constructor but more convenient.

I think the claim that they don't change behaviour is wrong. There are annotations like @Transactional which definitely changes behaviour. I think what they mean is that the spring annotations don't change the code.

1

u/fletku_mato Aug 16 '22

What is the best way to think about this?

Personally I wouldn't dig too deep into Spring DI until I need to. 99% of the time it's enough to understand that:

  • @Configuration classes can have @Bean-annotated methods that provide readily configured components. These components can be injected to other Beans or Components.

  • @Component classes can be injected to other Beans or Components.

1

u/rootseat Aug 16 '22

I wouldn't either, it's just something I'm needing to ramp up on for a new position at a company that's largely running Java things.

Thanks for the simple explanation though. I was thinking about it earlier today and realized Annotations center around "meta-programmatic" dependency injection. And that seems to link up with the two bread and butter annotations that you bring up.