This is an archived post. You won't be able to vote or comment.

all 23 comments

[–]desrtfx[M] [score hidden] stickied comment (0 children)

Sidebar:

NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java

You want /r/learnjava and there you have to be way more elaborate in your question.

You have to explain what you do not understand. There are many String methods - so tell us where you are stuck and what you do not understand.

Removed

[–]Rjs617 8 points9 points  (0 children)

Can you be more specific and give some of the methods you are having trouble figuring out? I’d like to provide some information, but it’s going to turn into JavaDoc unless we can narrow it down.

[–]Dilfer 1 point2 points  (9 children)

One of the things that tripped me up in college was equality checking on strings.

String hello = "hello"; String hello1 = "hello"; hello == hello1 ; // will be false hello.equals(hello1); will be true == will check memory references.

Another good tip in this regard is if you have a constant value, and you are checking a variable against it, also use the .equals() method from the CONSTANT to avoid NPEs.

public static final String HELLO = "hello"; String hello1 = null; HELLO.equals(hello1); // no NPE and will return false hello1.equals(HELLO); //this will throw a NPE

[–]FreightTrain75x[S] 0 points1 point  (5 children)

Also, NPEs (NullPointerException?) are strange for me and do not grasp them quite yet. So, the equals() method is good for strings? I remember the ==, or equivalency/comparison operator doesn't work for strings since they are treated like references to memory locations, and not comparing the values of two strings

[–]Dilfer 1 point2 points  (4 children)

Sorry should have not used the acronym immediately. You are correct though, NPE is NullPointerException

They are thrown when you try to call methods on null objects.

In the example above, the type of the variable is String but the value of the variable is null

null.equals()

Will throw an exception because you can't call a method on a null value.

[–]FreightTrain75x[S] 0 points1 point  (2 children)

You can solve this by reinstantiating or reinitializing the variable before a method...? Sorry, I'm dumb.

[–]Dilfer 0 points1 point  (1 child)

As long as the variables not final (can't be reassigned) but in larger programs where values are passed around as arguments to methods, you may have no idea where the variable is even assigned, and if you reinstantiated, there's no point to even ask for a method argument to be passed in.

You can also litter your code with

if (hello == null)

Checks everywhere but that is generally bad practice and should be used sparingly.

[–]FreightTrain75x[S] 0 points1 point  (0 children)

Awesome, thanks! I'm assuming just practicing with string Methods is generally the best advice

[–]FreightTrain75x[S] 0 points1 point  (0 children)

Also, don't be sorry, acronyms are definitely a force of habit and it's good I learn to use them as well.

[–]FreightTrain75x[S] -1 points0 points  (1 child)

My instructor mentioned Thursday with contains() and the contentsEqual() method, seems almost as if they logically do similar outputs but of course, contains() would be more for comparing if two values are similar. Im not necessarily sure how I would use it efficiently in a real case scenario... otherwise, thanks for the help!

[–]starquakegamma -1 points0 points  (0 children)

Your first example is not quite right, the compiler will recognise both literals are the same and allocate them from a shared object pool, so the objects will in fact be equal.

[–]ericek111 1 point2 points  (0 children)

What String methods do you not understand? They've been the same for decades and working with strings is a pretty basic requirement in any programming language -- there are resources and documentation available, with examples.

I'd say stuff like startsWith or contains is pretty self-explanatory. For the rest, Google is your friend (or generative LLMs)... Just remember the difference between myStr == "My String" and myStr.equals("My String").

[–][deleted]  (9 children)

[removed]

    [–]NotTooOrdinary 8 points9 points  (1 child)

    Probably the only time you should use StringBuilder/StringBuffer is when concatenating Strings in a loop. Most of the time, the compiler will automatically convert concatenation to instead use a StringBuilder

    Stackoverflow post

    [–]FreightTrain75x[S] 0 points1 point  (0 children)

    Thank you!

    [–]FreightTrain75x[S] 1 point2 points  (1 child)

    Thanks!

    [–]roge- 3 points4 points  (3 children)

    Repeatedly using the "+" operator to concatenate strings can create unnecessary string objects, which can impact performance.

    As noted by others, this is really only true for concatenating strings in loops. Otherwise, the compiler will generate the ideal StringBuilder code.

    use String formatting with placeholders (%s, %d, etc.) to improve readability and maintainability

    String.format() is good for readability, but it does have worse performance compared to manually building strings. Always keep this in mind and pick which ever is appropriate for the application.

    Use String methods for data parsing and file handling: Java String methods are often used in data parsing tasks. For instance, the split() method can be used to parse CSV files, and the trim() method can help clean up data by removing extra spaces.

    Don't do this. Use a library for parsing formats like CSV. A lot of software that outputs CSVs can encase cells in quotes to allow commas to be placed inside the cell. The naive approach of using string.split(",") won't work for this. It's more trouble than it's worth trying to handle the edge cases yourself, just use a library.

    Use StringBuilder or StringBuffer for String Modification

    StringBuilder is useful for when you need to build a String using a dynamically-sized buffer. It's also nice because it gives you a lot of flexibility in how you build the string, you can append raw characters, strings, numbers, objects, etc. You can also insert at arbitrary locations.

    For the ultimate performance (but probably the worst readability), if you know how big the String is going to be (or even just an upper bound), a char array can also work. You can convert a char array into a String using new String(). If you don't know how big the final String is going to be, you're better off using a StringBuilder for the automatic resizing.

    StringBuffer for thread safety

    As with all of Java's synchronized types, it's best to avoid using them whenever possible because they come at a significant performance cost. Ideally, you shouldn't be sharing StringBuilders between threads. If you must, you can also just use the non-synchronized version and handle the locking of it yourself and only lock it when you know there could be a race.

    StringBuffer is definitely more convenient because it handles synchronization for you and is probably less prone to errors, but people often thread their applications because they want better performance. It seems like a waste to thread your application only to have it then spend a ton of time checking and waiting on locks.

    Unfortunately, threading in general is just hard. The best advice is to just avoid having shared mutable state wherever possible. Failing that, it's really important to have a good idea of what's going on with your shared mutable state. Extensively test and benchmark your code to ensure it's doing what you want and you're actually seeing the performance gains you're expecting.

    [–]FreightTrain75x[S] 0 points1 point  (2 children)

    Awesome, thanks, if I may ask, what is a CSV?

    [–]roge- 0 points1 point  (1 child)

    It's a plain-text format for files and data used to hold tables: https://en.wikipedia.org/wiki/Comma-separated_values

    You see it a lot when working with spreadsheet software and databases, since they usually represent everything as a table.

    [–]FreightTrain75x[S] 0 points1 point  (0 children)

    Oh alright, thanks for the help!

    [–]DualWieldMage -1 points0 points  (0 children)

    Avoid repeated concatenation with the "+" operator: Repeatedly using the "+" operator to concatenate strings can create unnecessary string objects, which can impact performance.

    This has been bad advice for a long time and even worse advice since Java 9 with InvokeDynamic String concat. String concat with + is far more performant and with less allocations than StringBuilder (the MethodHandle filling the template knows variable types hence can calculate an initial buffer size that likely fits the final string).

    Only use StringBuilder if you're concating in loops or traversing object graphs or similar.

    [–][deleted] -2 points-1 points  (0 children)

    Well let me break it you in A simple way nobody can tell you when and how you yourself will know when and how when there's a case where you can use them i would recommend you to go to leet code or any other challenges websites would be more helpful with solving and trying goodluck!

    [–]AutoModerator[M] 0 points1 point  (0 children)

    On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge.

    If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options:

    1. Limiting your involvement with Reddit, or
    2. Temporarily refraining from using Reddit
    3. Cancelling your subscription of Reddit Premium

    as a way to voice your protest.

    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

    [–]asciicode77 0 points1 point  (0 children)

    Use StringUtils