/r/javahelp

Photograph via snooOG

General subreddit for helping with Java code.


General subreddit for helping with Java code.

Message the mods if you have suggestions.



Java Discord server (unofficial)


Learning Java

Please head over to /r/learnjava and read the sidebar there.

The best free Java tutorials are:

Use the MOOC as main course and Java for Complete Beginners as secondary resource.

Don't forget the Official Oracle Java Tutorials and the Official Java Documentation as they are extremely valuable resources.


Where should I download Java?

With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free.

If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others:

Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!


Posting rules

  1. DO NOT DELETE your posts once they are solved!

  • Use the "Solved" flair instead. This allows others to learn, too, and makes the helpers' efforts more effective.
  • No illegal/pirated content!

    • Anybody asking for or posting links to or suggesting to search for illegal/pirated content will be permanently banned without further warning!
  • No "Do my homework" posts!

    • Do not ask for complete solutions. We are here to help but not to /r/domyhomework. You do the work, and we help you. So - what have you tried?
    • For complete solutions, use a search engine instead. stackoverflow.com has a rich library of complete Java answers.
  • Describe the problem and what you want to achieve.

    • You get better tips if the readers know what you ultimately want to achieve, tips you didn't expect.
    • And in regards to describing your problem: "..., but it doesn't work." is insufficient! Do not expect people to put your code into their IDEs just to find out how the problem expresses itself.
    • If applicable, include the full error message or exception text!
  • Do not ask for or reply with solutions or keys to solutions.

    • Rather comment explanations and guides. Comments with solutions will be removed and commenters will automatically be banned for a week.
  • Use the search function.

    • Search for similar problems before posting.
  • No offers/requests to/for help via PM, Discord, Skype, etc.

    • Post your questions here so that other people can learn as well.
  • Post titles must be descriptive.

    • Bad title: "I'm new to Java and need help."
    • Good title: "How can I sort values without loops?"
    • The title should not describe your problem in full - that's what the post body is for.
    • No links in the titles - they are not clickable.
    • Nothing is "URGENT", nor "ASAP" - if you have waited too long, this is your problem, not ours. Such posts will be removed without warning.
  • No promises of rewards of any kind!

    • This includes both solicitation of services from those providing help and offers to pay from those requesting help.
    • Any post or comment that mentions payment may be subject to immediate ban from the subreddit.
  • Don't be a Jerk!

    • Don't insult, threaten, mock or harass other users. Please, maintain proper language.
    • We don't tolerate foul language for any reason. Any violation will result in an immediate thinking period ban of at least 4 days. Second offence will result in a permanent ban.
  • No JavaScript, Android, Minecraft or Processing!

  • No links to your stackoverflow questions.

    • We are not a second opinion to stackoverflow, nor are you going to get answers here when you didn't get satisfying ones there.
  • Format your code.

    • Please, properly format your code. This includes proper indentation. There are guidelines on how to format code in the sidebar in both, abridged form directly in the sidebar and in long form in the linked post.
    • For small bits of code (less than 50 lines in total, single classes only), use Reddit directly (one blank line, then 4 spaces before each line).
    • Otherwise: The sidebar has no-login links that even support syntax highlighting!
  • No screenshots of code!

    • You can add a screenshot of your IDE if it is relevant, but regarding the code itself, you must provide it in text form and properly formatted (and, please, properly indented).
  • No AI generated content!

    • We explicitly forbid any form of AI generated content. Posting any AI content results in an instant, permanent, and irrevocable ban without warning.
    • Code posting
    • Do not submit executable jar or compressed (zip, rar, 7z, etc.) files!
    • For small bits of code (less than 50 lines in total, single classes only), the default code formatter is fine (one blank line, then 4 spaces before each line).
    • Pastebin for programs that consist of a single class only
    • Gist for multi-class programs, or programs that require additional files
    • Github or Bitbucket repositories are also perfectly fine as are other dedicated source code hosting sites.
    • Ideone for executable code snippets that use only the console
    • Repl.it - online IDE for many different programming languages
    • Browxy - online IDE for several programming languages
    • Google Drive, Dropbox, Mediafire, etc. are not suitable for code posting!
  • Check out the wiki for frequently asked questions. Please feel free to contribute!

  • Sort by: Unsolved Solved Codeless Advent Of Code

    /r/javahelp

    98,555 Subscribers

    1

    Why might two distinct HashMap instances produce identical hash collisions, and how can it be avoided?

    Is it all about the hashCode() implementation, or does something else come into play?

    1 Comment
    2024/12/04
    11:11 UTC

    2

    Is there a way to create a new class without directly writing the class name?

    I recently found out about being able to summon (minecraft) entities and overriding methods which would be useful with what I wanna do. Although I have 0 idea of how to create a class based on what the already-defined entity's class is. What I want to do (with "entity" variable):

    Example (and the.. thing I want to do):

    Entity zombie = new Zombie(EntityType.ZOMBIE, _level)
    
    Entity zombie = new entity.getType().getBaseClass().class(EntityType.ZOMBIE, _level)
    6 Comments
    2024/12/04
    08:33 UTC

    1

    Mocking mockito

    Don't have my pc right now but I was doing some testing(new at it by the way) and part of the tasks is checking that the code logs are present and making a makeshift external service that offers a Double(both of these are in their own packages and classes) I used logging.Logger for the logs and now I'm just trying to figure out how to do those tests as for mocking the external service it refuses .....I'll put the error later on when I see it

    1 Comment
    2024/12/04
    08:06 UTC

    2

    Running Python Script with WebApp with Spring Boot Backend

    Hello everyone.. i want to ask is it possible to add a python script like this?

    I have a functional spring boot + react app for users and they already using it. But they have a new change request to add a button to download the file as an excel with templates and data was fetch from the db. My friend help me by building a python script to generate this file (since we think python is good for working with data)

    Is it possible to add a button in my react front end to run the python script and download the data as excel?

    2 Comments
    2024/12/04
    07:34 UTC

    2

    There is no “open with” option

    I’m trying to download Java for Minecraft mods and there is no “open with” option. It only gives me the option to open, and that’s it. I downloaded the default Java, then the x64 installer, and then the jarfix. I even restarted and undownloaded a bunch of time: and still nothing. What should I do?

    4 Comments
    2024/12/04
    05:21 UTC

    2

    Advent Of Code daily thread for December 04, 2024

    Welcome to the daily Advent Of Code thread!

    Please post all related topics only here and do not fill the subreddit with threads.

    The rules are:

    • No direct code posting of solutions - solutions are only allowed on the following source code hosters: Github Gist, Pastebin (only for single classes/files!), Github, Bitbucket, and GitLab - anonymous submissions are, of course allowed where the hosters allow (Pastebin does). We encourage people to use git repos (maybe with non-personally identifiable accounts to prevent doxing) - this also provides a learning effect as git is an extremely important skill to have.
    • Discussions about solutions are welcome and encouraged
    • Questions about the challenges are welcome and encouraged
    • Asking for help with solving the challenges is encouraged, still the no complete solutions rule applies. We advise, we help, but we do not solve.
    • As an exception to the general "Java only" rule, solutions in other programming languages are allowed in this special thread - and only here
    • No trashing! Criticism is okay, but stay civilized.
    • And the most important rule: HAVE FUN!

    /u/Philboyd_studge contributed a couple helper classes:

    Use of the libraries is not mandatory! Feel free to use your own.

    /u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627 If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb to join. Note that people on the board will see your AoC username.

    Happy coding!

    1 Comment
    2024/12/04
    05:00 UTC

    2

    How does Minecraft achieve the macOS native Window menu bar items?

    EXAMPLE IMAGE HERE

    Hey guys, I'm wondering how to incorporate the macOS Window menu bar features on a Swing application as depicted in the screenshot above.

    Even just a link to a project on GitHub which does this would suffice.

    Thanks so much!

    4 Comments
    2024/12/04
    03:58 UTC

    2

    Bizarre error with my final project

    Hi, I am in an introductory course for java programming, I am an anthropology major so this is not my strong suit. I am working on my final project where I am creating a calculator that converts a number of kilometers into miles. All of the code I have written seems to be in order and no errors come up yet whenever I run the code it prompts you to type a number of kilometers twice, only then will it convert it and run through the rest of the code. The end of the program prompts the user if they would like to go again, but when you do, no matter the number you type in to be converted it will convert the first number again.

    Here is the paste bin of the code I have written:

    https://pastebin.com/uZfXjb9C

    2 Comments
    2024/12/04
    03:20 UTC

    1

    PriorityQueue not working despite providing Comparator

    For the record, I am very new to Java, and am working on a project for university, and I am tearing my hair out trying to figure out why this isn't working as currently implemented. I am trying to create a PriorityQueue for a best first search algorithm in Java, where instances of the Node class are given integer values by instances of the interface NodeFunction. I have created a comparator which, given an instance of NodeFunction, can compare two instances of Node, and as far as I can tell it should now be working, however I am getting the following error

    Exception in thread "main" java.lang.ClassCastException: class search.Node cannot be cast to class java.lang.Comparable (search.Node is in unnamed module of loader com.sun.tools.javac.launcher.MemoryClassLoader u/36060e; java.lang.Comparable is in module java.base of loader 'bootstrap')

    The relevant parts of the code are below:

    public class BFF{
        PriorityQueue<Node> queue;
        NodeFunction function;
    
        public BFF(NodeFunction f){
            function = f;
            queue = new PriorityQueue<>(new NodeComparator(function));
        }
    
        public void addNode(Node node){
            queue.add(node);   // This is where the error is coming from
        }
    
    public class NodeComparator implements Comparator<Node>{
        NodeFunction function;
    
        public NodeComparator(NodeFunction function){
            this.function = function;
        }
    
        @Override
        public int compare(Node n1, Node n2){
            return Integer.compare(function.value(n1), function.value(n2));
        }
    }
    
    public interface NodeFunction {
        int value(Node node);
    }

    I don't believe the problem lies in the implementation of Node, nor the specific implementation of the interface NodeFunction, so I will omit these for brevity, but I could provide them if they would be of assistance. Like I said, as far as I can tell looking online the PriorityQueue should be able to compare instances of Node now the comparator is provided, but for some reason can not. Any help in figuring out why would be appreciated.

    4 Comments
    2024/12/04
    02:19 UTC

    3

    What is a tool that will automatically import source code repositories into my project?

    Let's say that I have application A, which depends on libraries B and C. These are all written by me, and all in separate source code repositories.

    Is there some tool that, when I clone application A, can be run to automatically clone the source code for libraries B and C?

    I want to clone the source code - not download compiled jars - so I don't think Maven is the right solution.

    I'm using IntelliJ; ideally this would be an easy operation to do from within the IDE.

    6 Comments
    2024/12/04
    01:46 UTC

    0

    Why is ui dysfunctional

    Some button & slider aren’t responding to mouse clicks normally now they only work occasionally the code seems right idk what’s wrong anyone had the same problem before?

    2 Comments
    2024/12/04
    01:33 UTC

    0

    installed Java Development Kit and there is no EXE file to open, please help

    So I'm trying to make a minecraft mod for the first time and it said I needed JDK. So after a while of figuring out how to extract it (Winrar helped me) there is no EXE file anywhere. It was extracted in the same place. Do I have to put the files in another Java Program? Is there something I am missing? I am a total beginner so any help is appriciated, thank you.

    3 Comments
    2024/12/04
    01:17 UTC

    1

    Why does getClass().getClassLoader().getResource(".") returns null in recent versions, and what's the new alternative?

    I found myself updating some old codebase (Java 7) which had the following line of code:

    var path = getClass().getClassLoader().getResource(".");

    It used to work well and returned the resource folder. Be it on the file system, in a jar or anywhere, actually.

    Now with Java 21 it returns null.

    Why is it so, and what is the updated way of having this work?

    Edit:

    The exact code I run is the following:

    public class Main {
      public static void main(String[] args) {
        System.out.println(Main.class.getClassLoader().getResource("."));
      }
    }
    10 Comments
    2024/12/03
    20:50 UTC

    2

    Need help with respect to Mockito to solve a specific use case

    I have the following function which I need to test -

    private HashMap<String, Dataset<Row>> getDataSources(SparkSession spark) {
            HashMap<String, Dataset<Row>> ds = new HashMap<String, Dataset<Row>>();
    
            Dataset<Row>dimTenant = spark.table(dbName + "." + SparkConstants.DIM_TENANT)
                    .select("tenant_key", "tenant_id");
    
            Map<String, String> options = new HashMap<>();
                    mockOptions.put("table", bookValueTable);
                    mockOptions.put("zkUrl", zkUrl);
    
    
            Dataset<Row> bookValue = spark.read().format("org.apache.phoenix.spark")
                    .options(options)
                    .load();
    
    
            ds.put("dimTenant", dimTenant);
            ds.put("bookValue", bookValue);
    
            return ds;
        }

    In this case, I actually need to execute spark.table but need to mock the output of spark.read().format(formatParam).options(optionsParam).load() based on formatParam and optionsParam

    Note that spark.table internally calls spark.read().table

    How can I achieve this?

    2 Comments
    2024/12/03
    20:07 UTC

    2

    Error 1603

    hey, I keep trying to install JRE 64-bit, but always getting error 1603. There is no problem with permissions. I tried on different folder, even on different disk - same error. I can install with online installer no problem, but that's 32 bit version. I tried older versions - same stuff. I'm running windows 11.
    Can someone please help me? Been stuck for hours

    1 Comment
    2024/12/03
    19:48 UTC

    0

    explosion interaction with Neighbors

    im dowing a 2d game, i created a bomb but i dont know how to make it unregister actors of the cells next to her

    thx

    2 Comments
    2024/12/03
    17:37 UTC

    1

    How to use form data in Azure function written Java

    I am building a website using Microsoft Powerpages and I want to post data to our SQL database using an Azure function. The function receives the multipart/form-data from the frontend, but I am unable to read the values into my function. I want my Azure function to do something like this:

    1  package com.itstyringsmartsales;
    2  import java.util.*;
    3  import com.microsoft.azure.functions.annotation.*;
    4  import com.microsoft.azure.functions.*;
    5  
    6  import java.io.ByteArrayInputStream;
    7  import java.io.IOException;
    8  // import <package.Class>
    9  import java.io.InputStream;
    10 import java.sql.Date;
    11 import java.util.Map;
    12 
    13 import javax.faces.annotation.RequestParameterMap;
    14 
    15 import java.util.HashMap;
    16 
    17 /* 
    18  * TODOS: 
    19  * - Add connection string
    20  * - Parse multipart/formdata
    21  * - 
    22  */
    23 
    24 /**
    25  * Azure Functions with HTTP Trigger.
    26  */
    27 
    28  // This function receives form data from the client and triggers a storedprocedure with a connection string.
    29  // - receives form data
    30  // - the form data is parsed by the function
    31  // - the stored procedure is triggered with the parsed form data as parameters
    32  public class Sales implements org.apache.commons.fileupload.UploadContext {
    33     /**
    34      * This function listens at endpoint "/api/Sales". Two ways to invoke it using "curl"      command in bash:
    35      * 1. curl -d "HTTP Body" {your host}/api/Sales
    36      * 2. curl {your host}/api/Sales?name=HTTP%20Query
    37      **/
    38 
    39     @FunctionName("Sales")
    40     public HttpResponseMessage run(
    41             @HttpTrigger(
    42                 name = "req",
    43                 methods = {HttpMethod.POST}, 
    44                 authLevel = AuthorizationLevel.ANONYMOUS) 
    45                 HttpRequestMessage<Optional<String>> request,
    46                 @RequestParameterMap
    47             final ExecutionContext context)  {
    48         context.getLogger().info("Java HTTP trigger processed a request.");
    49 
    50         // - [x] get request body
    51         String requestBody = request.getBody().orElse("");
    52 
    53         String product_name = "Football";
    54         int production_cost = "";
    55         float price = "";
    56         int units_sold = "";
    57         float profit = "";
    58         String date = "";
    59         int month_number = "";
    60         int year = "";
    61         float indirect_costs = "";
    62 
    63         // parse the request body
    64         try {
    65             
    66             
    67             // - [ ] trigger stored procedure with parsed data as parameters
    68             Connection connection = new SQLConnection("<connection-string>");
    69               connection.triggerSproc.addSale(product_name, production_cost, price, 70units_sold,         profit, date, month_number, year, indirect_costs);
    71         } catch (Exception e) {
    72             context.getLogger().severe("Failed to parse form data: " + e.getMessage());
    73             return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
    74                           .body("Invalid form data")
    75                           .build();
    76         }
    77             return request.createResponseBuilder(HttpStatus.OK).body(requestBody).build();
    78         }
    79 }

    My question boils down to the lines 53 to 61. How do I store each field in the form inside their own variable?
    Once that is done I can easily use JDBC to trigger a stored procedure in SQL Server. Is there a term for what my question is about? The closest thing I can think of is parsing.

    1 Comment
    2024/12/03
    13:28 UTC

    4

    Does anyone know a simple and non-abstracted example of Spring Security with JWT

    Ive been trying to understand it for a week now and have gotten nowhere. I feel like if i can just find a good simple example i can understand it.

    10 Comments
    2024/12/03
    15:46 UTC

    3

    ForkJoinPool and Nested (Parallel) Streams - Or why are inner streams faster with new pools ?

    Hi all, so I've been doing some benchmarking at work to suss out how good (or bad) things are at various places. One of the instances I benchmarked recently was an instance where someone had coded up two nested parallelStreams. Something like so:

    inputStream.parallel().forEach(
      streamElement -> someList.stream().parallel()
                          .forEach( 
                            innerEle -> {
                            // some work here using streamElement and innerEle
                            }).toList();
    )

    My immediate thought was that since all parallelStreams draw from ForkJoinPool.commonPool() they'd end up fighting for resources and potentially make the whole thing slower.

    But my next thought was...how much slower ?

    So I went ahead and made a benchmark with JMH where I tested 3 conditions:

    • Nested parallel streams
    • Outer parallel stream and inner sequential stream
    • Nested parallel streams but with a new forkJoinPool for the inner stream so that it doesn't compete with the common pool. There's no real reason for me adding this in other than sheer curiosity.

    The results are ... interesting. Here's my benchmarking code:

    public class ParallelPerf {
      u/State(Scope.Benchmark)
      public static class StateData{
        public static final List<Integer> outerLoop = IntStream.range(0, 32).boxed().toList();
        public static final List<Integer> innerLoop = IntStream.range(0, 32).boxed().toList();
      }
      private static void runInNewPool(Runnable task) {
        ForkJoinPool pool = new ForkJoinPool();
        try {
          pool.submit(task).join();
        } finally {
          pool.shutdown();
        }
      }
      private static void innerParallelLoop() {
        StateData.innerLoop.parallelStream().unordered().forEach(i -> {
          try {
            Thread.sleep(5);
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        });
      }
      private static void innerSequentialLoop() {
        StateData.innerLoop.stream().unordered().forEach(i -> {
          try {
            Thread.sleep(5);
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        });
      }
      @Benchmark
      public void testingNewPool(Blackhole bh){
        StateData.outerLoop.parallelStream().unordered().forEach(i -> {
          runInNewPool(ParallelPerf::innerParallelLoop);
          bh.consume(i);
        });
      }
    
      @Benchmark
      public void testingCommonPoolWithSequentialInner(Blackhole bh){
        StateData.outerLoop.parallelStream().unordered().forEach(i -> {
          innerSequentialLoop();
          bh.consume(i);
        });
      }
      @Benchmark
      public void testingCommonPool(Blackhole bh){
        StateData.outerLoop.parallelStream().unordered().forEach(i -> {
          innerParallelLoop();
          bh.consume(i);
        });
      }
    }

    And here are the results on my system:

    Benchmark                                           Mode  Cnt   Score   Error  Units
    ParallelPerf.testingCommonPool                     thrpt   25   1.992 ± 0.018  ops/s
    ParallelPerf.testingCommonPoolWithSequentialInner  thrpt   25   1.802 ± 0.015  ops/s
    ParallelPerf.testingNewPool                        thrpt   25  23.136 ± 1.738  ops/s

    Assuming my benching code is correct and I haven't screwed anything up, I'm quite surprised that the code with new pools is around 20x faster than the others. Why is it so much faster ?

    One potential reason I could think of (caveat - I haven't verified this at all) is that maybe the new pool is able to grab one of the waiting threads from the common pool ? But this would indicate that the threads within commonPool are unable to do so, which doesn't seem right.

    So fellow redditors - any guesses/insights as to what might be happening here ?

    8 Comments
    2024/12/03
    09:26 UTC

    2

    Advent Of Code daily thread for December 03, 2024

    Welcome to the daily Advent Of Code thread!

    Please post all related topics only here and do not fill the subreddit with threads.

    The rules are:

    • No direct code posting of solutions - solutions are only allowed on the following source code hosters: Github Gist, Pastebin (only for single classes/files!), Github, Bitbucket, and GitLab - anonymous submissions are, of course allowed where the hosters allow (Pastebin does). We encourage people to use git repos (maybe with non-personally identifiable accounts to prevent doxing) - this also provides a learning effect as git is an extremely important skill to have.
    • Discussions about solutions are welcome and encouraged
    • Questions about the challenges are welcome and encouraged
    • Asking for help with solving the challenges is encouraged, still the no complete solutions rule applies. We advise, we help, but we do not solve.
    • As an exception to the general "Java only" rule, solutions in other programming languages are allowed in this special thread - and only here
    • No trashing! Criticism is okay, but stay civilized.
    • And the most important rule: HAVE FUN!

    /u/Philboyd_studge contributed a couple helper classes:

    Use of the libraries is not mandatory! Feel free to use your own.

    /u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627 If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb to join. Note that people on the board will see your AoC username.

    Happy coding!

    0 Comments
    2024/12/03
    05:00 UTC

    6

    How do I dynamically map bean A to B?

    Hi,

    I have a requirement where I have two beans, namely Form and DTO, both having the same properties for which I have to map property values from Form -> DTO in JDK 21.

    Example bean POJO:

    Form{mask: Boolean, height: Integer, active: Boolean, name: String, history: List<String>}

    DTO{id: UUID, height: Integer, active: Boolean, name: String, history: List<String>}

    Now, I receive a collection of property names as Set<String> belonging to Form type bean that I have to consider while mapping the values of the properties specified in the received set from Form to DTO. This collection of property names specifies the properties in the instance of Form type in context that has its values changes as compared to its counterpart on the DTO side.

    Since, the collection of property names is dynamic in nature, how do I perform a dynamic mapping from Form -> DTO using the provided collection of property names?

    I have tried different mapping frameworks like JMapper and Dozer but they are all last supported till 2016 and 2014 respectively and does not offer concrete examples or strong documentation to my liking. MapStruct does not seem to offer any API way of doing it.

    My last resort is to implement my own mapping framework using reflections but I really don't want to go down that rabbit hole. Any suggestions on how I can achieve this with a readymade mapping library?

    TLDR: How can I dynamically map a set of properties from bean A to B where the property names to be considered for mapping are only available at runtime and a full mapping from A to B should never be considered unless specified?

    39 Comments
    2024/12/03
    04:56 UTC

    0

    Java for Aspies?

    Firstly, I am autistic. I've tried to learn java from more “traditional” languages (C# & Python), but I just can't understand java and OOP in general. I just want to learn enough to make Minecraft mods (Minecraft subs told me to post here instead), so does anyone have anything that could help me understand java? My main problems are with general OOP and Javas buses.

    3 Comments
    2024/12/03
    04:27 UTC

    2

    Need help adding a key listener

    I've looked up so many tutorials trying to get this but none seem to work. What's the most straightforward way to activate a method when a certain button is pressed? Where can I read about the specifics of your answer? All the tutorials I've found are too surface level for me to know how to adapt them to my project. I'm using javafx if that makes a difference.

    5 Comments
    2024/12/02
    21:44 UTC

    5

    Constructor inheritance limited...

    Let's assume we have class B, contents of which is irrelevant to the following discussion. I want this class with one additional field. Solutions? Well, there are two I've found.

    1. Derived class.

      public class D extends B { public int tag = 0; }

    Cool, but if I want to use this class as the replacement of B, I have to duplicate all constructors of B:

    public class D extends B {
        public int tag = 0;
        public D () { super B (); }
        public D (int x) { super (x); }
        public D (String x) { super (x); }
        public D (int x, int y, String z) { super (x, y, z); }
        // TODO: all others
        }
    B x = new D (...);
    1. Java has anonimous classes. They do inherit base class constructors!

      B x = new B (...) { public int tag = 0; };

    Wait how am I supposed to get value of this field?..


    So I've started to ask myself the following question: why constructor inheritence is limited to anonymous classes?

    39 Comments
    2024/12/02
    17:25 UTC

    1

    Pac-Man

    Hello all I am still learning a for a final project I have to make Pac-Man move by inputting 1 - forward, 2 - left, 3 - right and 4 - stop and any other number won’t work. Can anyone give me any pointers by using while or if statements or something. Thnaks

    2 Comments
    2024/12/02
    10:35 UTC

    4

    Current scenario of development in JAVA

    So I am thinking of learning java and get serious about my career I know programming as companies ask for DSA so I was thinking of doing it in java but problem is i am not aware of development scenario in JAVA like JAVA have springboot but i don't think it is demand same for app development people are using kotlin so wanted to ask is it worth learning or i am not informed yet ?

    3 Comments
    2024/12/02
    05:38 UTC

    2

    Advent Of Code daily thread for December 02, 2024

    Welcome to the daily Advent Of Code thread!

    Please post all related topics only here and do not fill the subreddit with threads.

    The rules are:

    • No direct code posting of solutions - solutions are only allowed on the following source code hosters: Github Gist, Pastebin (only for single classes/files!), Github, Bitbucket, and GitLab - anonymous submissions are, of course allowed where the hosters allow (Pastebin does). We encourage people to use git repos (maybe with non-personally identifiable accounts to prevent doxing) - this also provides a learning effect as git is an extremely important skill to have.
    • Discussions about solutions are welcome and encouraged
    • Questions about the challenges are welcome and encouraged
    • Asking for help with solving the challenges is encouraged, still the no complete solutions rule applies. We advise, we help, but we do not solve.
    • As an exception to the general "Java only" rule, solutions in other programming languages are allowed in this special thread - and only here
    • No trashing! Criticism is okay, but stay civilized.
    • And the most important rule: HAVE FUN!

    /u/Philboyd_studge contributed a couple helper classes:

    Use of the libraries is not mandatory! Feel free to use your own.

    /u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627 If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb to join. Note that people on the board will see your AoC username.

    Happy coding!

    0 Comments
    2024/12/02
    05:00 UTC

    1

    Trying to install Visual Studio and Java JDK. please help

    Whenever I open up visual studio and go to java I get an error saying “Cannot find 1.8 or higher” I have 0 clue what this means other than its not detecting the jdk

    The other problem is my coding pack from the same website isn’t finishing installation either so im looking for any advice if possible.

    9 Comments
    2024/12/02
    03:06 UTC

    1

    Wondering if there is any way to optimize this code (getting every combination of substrings of a string)

    I am wondering if this code can be further optimized to reduce runtime?

    It is supposed to find all of the combinations possible for a given string.

    So for the string "ABC": A, AB, ABC, AC, ACB, B, BA, BAC, BC, BCA, C, CA, CAB, CB, CBA

        protected void getCombos(String str, String sub) {
            int stringLen = str.length();
    
            System.out.println(sub);
            
            if (stringLen > 0) {
                for (int i = 0; i < stringLen; i++) {
                    getCombos(str.substring(0, i) + str.substring(i + 1, stringLen), sub + str.charAt(i));
                }
            }
        }
    6 Comments
    2024/12/01
    21:15 UTC

    0

    Do I have to Go Through an OS Textbook Before Tackling Goetz' JCiP?

    The title, basically.

    Thanks!

    1 Comment
    2024/12/01
    19:16 UTC

    Back To Top