You've Been Using Java Strings WRONG All This Time!

Поделиться
HTML-код
  • Опубликовано: 8 июн 2024
  • Discover the truth about Java Strings in this eye-opening tutorial! If you've been struggling with Java String manipulation, or feel like you're not using them as efficiently as possible, this video is a game-changer for you.
    I reveal the most common mistakes Java developers make when working with Strings, and provide expert tips on how to avoid them, boosting your coding performance.
    In this video, you'll learn:
    - The hidden pitfalls of Java String handling and how to overcome them
    - The secret to mastering Java String concatenation, comparison, and performance optimization
    - Best practices for using Java Strings that every programmer should know
    - Incredible Java String tips and tricks for faster and more efficient coding
    Whether you're a Java beginner or an experienced programmer, these insights will help you level up your Java String skills and make you a more effective developer. Don't miss out on this opportunity to improve your coding game and stay ahead in the competitive world of Java development!
    Don't Forget to
    ===========================================
    💯 Subscribe to Amigoscode - bit.ly/2HpF5V8
    💯 Courses Available for free here - amigoscode.com/courses
    💯 Join Private Facebook Group and Discord - amigoscode.com/p/join-community
    ⭐ Table Of Contents ⭐
    ===========================================
    00:00 - Intro
    00:33 - The Right Way to Use Strings
    08:04 - Outro
    🙊 Here are the goods for all my videos video 🙊
    ► Recommended Books
    ===========================================
    - Clean Code - amzn.to/2UGDPlX
    - HTTP: The Definitive Guide - amzn.to/2JDVi8s
    - Clean Architecture - amzn.to/2xOBNXW
    ► Computer and Monitor
    ===========================================
    - New Apple MacBook Pro - amzn.to/3464Mmn
    - Dell 27 INCH Ultrasharp U2719D Monitor - amzn.to/2xM3nW1
    - Double Arm Stand Desk Mount - amzn.to/3aYKKfs
    - USB C Hub Multiport Adapter - amzn.to/2Jz7NlL
    ► Camera Gear
    =============================================
    - Sony ILCE7M3B Full Frame Mirrorless Camera - amzn.to/346QIJn
    - Sigma 16 mm F1.4 DC DN - amzn.to/2wbic3Q
    - Sigma 33B965 30 mm F1.4 DC DC - amzn.to/39G37Fd
    ► IDE & Tools I use for coding 💻 🎒
    ===========================================
    - ITerm
    - VsCode
    - GoLand
    - IntelliJ Ultimate
    - Sublime
    P.S
    ===========================================
    💯 Don't forget to subscribe | bit.ly/2HpF5V8
    💯 Join Private Facebook Group and Discord - amigoscode.com/p/join-community
    💯 Follow me on Instagram | bit.ly/2TSkA9w
    ❤️ Thanks for watching
  • НаукаНаука

Комментарии • 155

  • @omer_usta
    @omer_usta Год назад +196

    Dont forget one important note that StringBuilder is not thread-safe , it should not be used in a multithreaded environment without proper synchronization. If you need to use StringBuilder in a multithreaded environment, you should use StringBuffer instead, which is a thread-safe alternative

    • @GFunkEra1992
      @GFunkEra1992 Год назад +2

      yes, but using multithreading is very specific. Not all companies uses it.

    • @RobertSaulnier
      @RobertSaulnier Год назад +11

      I can't think of a single use case where a StringBuffer makes sense, even in a multithreaded environment. Threads will most likely call append multiple times so what will the output look like? Garbage

    • @adityabhale1858
      @adityabhale1858 Год назад

      Thanks Omer for the information 👍

    • @vishwajitswami6450
      @vishwajitswami6450 Год назад

      Thanks Omer , Nice explanation

    • @kishoreramana1
      @kishoreramana1 Год назад

      @@GFunkEra1992 there is no impact of multithreading for local vraibles

  • @V4dk4n
    @V4dk4n Год назад +19

    We were taught at school not to use strings, but stringbuilders for concat, for this very reason, I just never thought that the difference would be this big, thanks for the video!

  • @rpdemo
    @rpdemo Год назад +10

    What I most like on your videos is your sense of humor, making learning into a funny thing.
    Nice work man!

  • @ghostcoderz
    @ghostcoderz Год назад +33

    Great video... Thanks for making this video. Nobody tells these small things that make a big difference in production.

    • @DevToolsMadeSimple
      @DevToolsMadeSimple Год назад

      True

    • @z00lus
      @z00lus Год назад +4

      Its classic. Read Effective Java by Joshua Bloch. Item 63 about performance of string concatenation. And in general whole book is very good.

  • @bkaaron3728
    @bkaaron3728 Год назад +2

    You are a great teacher. I have improved a lot as a back end developer. Just from your videos. So many Java developers here in Uganda use your content, its so easy to understand. I got to understand security from your videos

  • @CottidaeSEA
    @CottidaeSEA Год назад +4

    Whether to use StringBuilder/StringBuffer (StringBuffer is thread safe) or just do += or similar depends primarily on many times you're doing it. If it's just one or two times you might as well use += because the performance drops are negligible.

  • @misaelpereira9679
    @misaelpereira9679 Год назад +2

    Awesome learning! I could not imagine the performance impact!

  • @martins2246
    @martins2246 Год назад +6

    How I code for real, and how I code in interviews are different. The interview test is high pressure, and challenging. I like to stick with the old += and then mention "I know there is an optimization for this if we concat a lot of strings in a loop..." and away we go. I feel the same way about Autoboxing. I like to keep things easier to flow with under those conditions and then mention "I can optimize these Autoboxes later..." and it usually gets a grunt that sounds positive.

  • @ax8635
    @ax8635 Год назад

    Great to see live memory usages for those examples.

  • @hardikpanchal9726
    @hardikpanchal9726 Год назад +3

    Hi Amigo,
    That's for the detailed explanation. These are some small mistake which youngsters are making special in production environment which sometimes creates large delaye in applications execution. It was very helpful.

    • @Markus-fw4px
      @Markus-fw4px Год назад

      But why? If you know better, why don't you code it the proper way right away? It doesn't seem to be more effort.

  • @iluvsyphonfilter
    @iluvsyphonfilter Год назад

    I didn't know these differences, thanks for the tip!

  • @kchemutai3483
    @kchemutai3483 11 месяцев назад

    Thank you so much @AmigisCode, this was eye opening

  • @cloey_b
    @cloey_b Год назад

    WONDERFUL, my friend. Thanks for this really helpful video and for sharing valuable knowledge with us. Greetings from Argentina💟

  • @ahmedal-sharabi5322
    @ahmedal-sharabi5322 Год назад

    Great video and thumbnails always cracks me up 😂

  • @DIFIWIFILUPO
    @DIFIWIFILUPO Год назад

    Thank you, you explain so well! thank you brother

  • @Edzward
    @Edzward Год назад

    Very insightful! I remember seeing that a long time ago while learning Java.
    The most probably reason is because Strings are actually a Array of Chars.

  • @carmenbravo8606
    @carmenbravo8606 5 месяцев назад

    This is a great explanation of this common mistake! Awesome

  • @gorandev
    @gorandev Год назад +5

    At 4:22 there is no need to invoke "toString()" on the StringBuilder instance. If you look under the hood, "String.valueOf(sb)" calls the "toString()" method for you. That is why it gets greyed out in your IDE, it is redundant.

  • @Educationship
    @Educationship Год назад

    WOW! Very insightful.

  • @frankmeneses5947
    @frankmeneses5947 Год назад

    Great video!

  • @JorgetePanete
    @JorgetePanete Год назад +1

    It's important to know how in Java 9 or 10 (idk) the bytecode changes, if you do several + to form a full string, like a text block without text block syntax, it's performant

    • @orbyfied
      @orbyfied Год назад +2

      isnt that just the compiler making it into a constant at compile time
      the compiler knows when you do `"a" + "b"` that it will always result in "ab"

  • @awabalbaalbaky3508
    @awabalbaalbaky3508 Год назад +1

    I always use StringBuilder but you just said in the beginning that the compiler optimize it to use StringBuilder automatically, or that's different?

  • @vanoanhpham2861
    @vanoanhpham2861 Год назад +2

    Please explain the advantages of LocalDataTime with java.util.Data or Calendar . why choose LocalDateTime i think Data or Calendar have some bugs , Right ?

  • @user-ix7mk3gg1w
    @user-ix7mk3gg1w Год назад

    Thanks, mate!

  • @G-33k
    @G-33k Год назад +5

    Wa alaykom salam brother Amigo, nice informations as usual

  • @albertoazinar1209
    @albertoazinar1209 Год назад

    Great video!!!!!🎉

  • @Alan-rf3im
    @Alan-rf3im Год назад

    You are a good boy man. Thanks a lot.

  • @tlf94949
    @tlf94949 Год назад

    Hello
    What about using concatenating with primitive instead of string object in your exemple

  • @gavipk
    @gavipk Год назад

    what's in the stringbuilder? an arrayList that holds chars that assembles a string all in one object? how would someone go about crafting their own stringbuilder in Java?

  • @code-discover
    @code-discover Год назад

    StringBuffer can be used in this case but it different with StringBuilder is synchronize and non-synchronize. =))

  • @mookayreet8518
    @mookayreet8518 Год назад

    I want to see an implementition of API key Authentication and management if possible please

  • @LthiagoR
    @LthiagoR Год назад

    Beautiful video

  • @user-hg6td9ob9z
    @user-hg6td9ob9z Год назад +2

    Hi, Amigo.
    What's your IntelliJ theme that your folders and subfolders like that ?
    Thanks.

  • @harshrajpal1828
    @harshrajpal1828 Год назад

    Bro which video editing tool you are using ?

  • @tommy--k
    @tommy--k Год назад

    Good stuff, thanks!

  • @dimmetrious
    @dimmetrious Год назад +1

    Good video. could you please name plugin for that big 'run\debug' at the top?

  • @iZakirSheikh
    @iZakirSheikh Год назад

    What the name of theme that you r using for intellij idea

  • @SouravBanik90
    @SouravBanik90 Год назад

    Recently i ran into this issue comparing deserialized json.

  • @chang112x
    @chang112x Год назад

    WOW, this is a huge difference!

  • @albaniaiptv8335
    @albaniaiptv8335 Год назад

    im android developer , and i use + or += but when the app is compiled , in the byte code it shows stringbuilder .

  • @tiennguyennhu5604
    @tiennguyennhu5604 Год назад

    Is that IntelliJ IDEA or how to config that like yours?

  • @vladimirnechiporyuk2948
    @vladimirnechiporyuk2948 Год назад

    Thanks a lot.

  • @rutvikrajpura7618
    @rutvikrajpura7618 Год назад

    Can you make more videos on Thread and threadpool.....🎉

  • @RiesenpiIz
    @RiesenpiIz Год назад

    Which ide are you using?

  • @murilofernandesdasilva4170
    @murilofernandesdasilva4170 Год назад

    what theme are you using in your ide bro?

  • @user-ld3co7fy4e
    @user-ld3co7fy4e Год назад +2

    Hello. Thanks for usefull video.
    Can anyone explain WHY "slow method" (by creating new String variable) is slower than "fast method"(by using .addend of StringBuilder)? Is it bcause of number of operations for creation of new variable?

    • @LOLdjrabaanLOL
      @LOLdjrabaanLOL Год назад +4

      every addition to string creates a new string, and a string is a object stored in java memory, which needs to be created and managed. as you can imagine instaciating milion objects is expensive

    • @ampo287
      @ampo287 Год назад

      ​@@LOLdjrabaanLOL in addition, when it create millon length long string. it will takes so many memories to allocate it.

    • @youssefbouchara1179
      @youssefbouchara1179 Год назад

      Strings are immutable so you can't just add a star to an existing one.. StringBuilders in the other hand are mutable so you can just change them

  • @reddish98
    @reddish98 Год назад +4

    I agree with the lesson of this video, although I´d like to point out that in real usage the slow vs fast methods would not have that much of a performance difference. I can't think of any scenarios where the same string would be appended to 1 million times. Assuming that each string is only appended to 10s or maybe 100s of times before a brand new one is created, using a StringBuilder would still be faster but not near to the performance gains shown in this example. Nevertheless a great point and video

    • @xSferQx
      @xSferQx Год назад +2

      In systems which generate files, reports etc. for example ERP systems, appending string multiple times is pretty frequent functionality

    • @reddish98
      @reddish98 Год назад

      @@xSferQx I really don't know a lot about those types of systems but I´d be surprised if they append the same string millions of times without writing it to a file (and clearing the string)

    • @simonfarre4907
      @simonfarre4907 Год назад

      This is bad advice. I don't use Java myself, at work or at home, because, hey, it's just not great - but that's beside the point - why this is bad advice is because String is an immutable type. Writing code like that, informs the human on the other side that you're doing some form of mutation. You're essentially making a logic or reasoning error.
      StringBuilder (although a _terrible_ name, Java should have just went with what other languages do, and make a String class that is not immutable and a StringRef that is) should be used regardless. Because that signals that "hey, I'm doing some mutation here". Secondly
      s += "foo"
      using an immutable type comes with another problem (in a single threaded context) - you're throwing away the reference to the prior string. That means now, the GC has to perform extra work. Whether or not you are "appending" a million times or a hundred times, you are creating objects, fragmenting the heap and adding additional work for the GC. This _is_ costly. Particularly since GC's, in 2023 aren't great, they never will be great, because that's just a fact of life in that problem domain (I'm not saying GC's should never be used, I'm just saying they come with overhead).
      So it's not just about performance, although that *certainly* is the most important part, but it's also about the logic of the code. Strings are immutable. And when you do += you have not just created a new string, you have discarded the reference to the old one. That is _not_ the intention of appending, and most likely not what the programmer intended either, although it is explicitly what happens.

    • @RobertSaulnier
      @RobertSaulnier Год назад

      @@simonfarre4907 your obviously haven't kept up with GC performance. ZGC runs full gcs in less than a millisecond with Tera bytes of heap

    • @simonfarre4907
      @simonfarre4907 Год назад

      @@RobertSaulnier Do you know what trade offs ZGC has made to be able to be faster? Because there are no silver bullet GC's. GCs are a tool we use to make certain development more ergonomic, but it always comes at the cost of performance. Yes, GC's are faster today than they were 10-15 years ago, but guess what, so are computers.
      Garbage collection come with inherent constraints, it's part of the trade off game we play. But GC is always, always less performant.

  • @mdabdurrakib6965
    @mdabdurrakib6965 Год назад

    Thank you so much

  • @user-vr1od8gk5d
    @user-vr1od8gk5d Год назад

    Thanks,
    What about String.concat() or stream(). ... . joining() ?

  • @networkingknowledge6261
    @networkingknowledge6261 11 месяцев назад

    good to know , thx

  • @ahmedbishree9429
    @ahmedbishree9429 Год назад

    Essalamo Aleykum brother, thanks for the excellent example, I d like to ask you about your Adidas shirt from where you got it and appreciate that for you

  • @nightfox6738
    @nightfox6738 Год назад

    I'm curious why Java's String class doesn't do append behind the scenes for +=. That seems like a bit of a serious oversight.

  • @bilos125
    @bilos125 2 месяца назад

    How did it auto complete when he wrote sout?

  • @anothermouth7077
    @anothermouth7077 Год назад

    Although Sonar suggest to use + instead of append

  • @Ram-ly6hb
    @Ram-ly6hb Год назад

    Which IDE are you using?

  • @user-pu6ll6xd2b
    @user-pu6ll6xd2b Год назад

    hi , How to create an anti optimally inside the loop?

  • @hemant8223
    @hemant8223 Год назад

    It's really great video.

  • @dmitrik4610
    @dmitrik4610 Год назад

    Hello. Your test is not representative. When you build string with plus symbol java create new object and add it into string pool on each iteration. you used only 1 symbol at fast implementation and collect 1m links in string builder

  • @hamednikbakht9708
    @hamednikbakht9708 Год назад

    how to add entity in loop?

  • @video-markt
    @video-markt Год назад

    this are the things you learn if you wan to be java certify. lern it long a go. but the exam was to hard. did not passed.

  • @mdzaidsiddiqui4262
    @mdzaidsiddiqui4262 Год назад +1

    What is the ide you're using? Great video btw!

    • @IvanRandomDude
      @IvanRandomDude Год назад +1

      Intellij IDEA

    • @VidhanTube
      @VidhanTube Год назад +1

      Intellij IDE but with new UI enabled (which is in beta).

    • @ynl9296
      @ynl9296 Год назад

      How to download it😮

    • @VidhanTube
      @VidhanTube Год назад

      @@ynl9296 Either enable it through settings or search for certain plugin to enable new ui on google

    • @vicary__
      @vicary__ Год назад

      @@ynl9296 u have beta version in settings, just turn it on

  • @user-kx5zl7rb1d
    @user-kx5zl7rb1d Год назад

    Any tutorial series on C++?

  • @alekhaidari9605
    @alekhaidari9605 Год назад

    Basically, awesome 👏🏻 😃

  • @manikantareddy7595
    @manikantareddy7595 Год назад +1

    Slightly confused now, why isn't there an invoke dynamic call that appends these million to a StringBuilder and finally unwrap to String

    • @simonfarre4907
      @simonfarre4907 Год назад +1

      Because optimizers, regardless of the language, can only do so much heavy lifting for you. In the end, you have to be smart enough to not do things like this. Don't get me wrong, compilers and optimizers are fantastic, and they can optimize code in *amazing ways* but most people would be surprised with how fast an optimizer gets to a point where it can not guarantee a specific thing and therefore have to skip optimizing it entirely.

    • @manikantareddy7595
      @manikantareddy7595 Год назад

      @@simonfarre4907 thanks for the reply, but wouldn't it be cool if compiler works for human and not the other way around 😉

  • @soniablanche5672
    @soniablanche5672 Год назад

    Doesn't java optimize string concatenation in loops by using StringBuilder? I know modern Javascript engines do, so I would assume Java does the same thing since it's a very common operation.

    • @KingstonFortune
      @KingstonFortune Год назад

      Yes Java does optimize string concatenation using StringBuilder even if you don’t explicitly use it. Under the hood Java would create a new StringBuilder object and use the append method and once done it converts it to a string by using the toString method. And yeah as you mentioned SB provides much better performance if you wona concatenate in a loop 😇

  • @diamantbrandy
    @diamantbrandy Год назад

    oh thanks

  • @asatbekxalimjonov4005
    @asatbekxalimjonov4005 Год назад

    useful video

  • @hstivggfghyhgfg8359
    @hstivggfghyhgfg8359 Год назад

    String is just a fixed size array of bytes

  • @georgeshchennikov6423
    @georgeshchennikov6423 Год назад +2

    Yeah! I always use StringBuilder 😀

    • @omer_usta
      @omer_usta Год назад +3

      Using Always StringBuilder is also not suitable for all things. it's important to note that StringBuilder is not thread-safe, which means that it should not be used in a multithreaded environment without proper synchronization

    • @ynl9296
      @ynl9296 Год назад

      but I think it depends on your businesses logic

    • @georgeshchennikov6423
      @georgeshchennikov6423 Год назад

      @@omer_usta yes, of courses)

    • @georgeshchennikov6423
      @georgeshchennikov6423 Год назад

      @@ynl9296 yep

  • @thirdstreetnorth
    @thirdstreetnorth Год назад

    Great video! One small comment - an empty string is not a null - regarding your comment during the video. cheers!

  • @georgivalkanov2377
    @georgivalkanov2377 Год назад

    Please give the same comparison but in Python.

  • @mrMarseleene
    @mrMarseleene Год назад

    I knew about string and for concat use stringbuilder, but concat with null was mind blowing, i didn't even expect. Great job! more videos about java "underwear". Inshallah

  • @rahff99
    @rahff99 Год назад

    great

  • @phucle-cb1fl
    @phucle-cb1fl Год назад

    How about template for Intelij IDE bro 😊?

  • @macaroane
    @macaroane Год назад

    In what real world scenario you would append to a string for let's say 1000 times, not 1 mil? can't think of any

  • @user-ty6oz3gv8z
    @user-ty6oz3gv8z Год назад +1

    why your theme is more darker than mine in linux?

  • @plinplinplonn
    @plinplinplonn Год назад

    Why is his intelijidea looking that dope

  • @vishwa4827
    @vishwa4827 Год назад +3

    Can anyone tell me the road map to learn java as a beginner

    • @ChandlerBing11
      @ChandlerBing11 Год назад

      Primitive types, String, OOP, Collections, Stream, Optional, Lambda and JDBC.

    • @ascar66
      @ascar66 Год назад

      ask google. There is a plethora of road maps

    • @DevToolsMadeSimple
      @DevToolsMadeSimple Год назад

      You can find it here: www.geeksforgeeks.org/java-developer-learning-path-a-complete-roadmap/

    • @vishwa4827
      @vishwa4827 Год назад

      @@ChandlerBing11i don't know what is stream and optional

    • @vishwa4827
      @vishwa4827 Год назад

      @@ascar66 ok bro tq

  • @techme6053
    @techme6053 Год назад

    Is laptop necessary for coding 😔

  • @sbks7273
    @sbks7273 Год назад

    @2:00 I see what you did there :3

  • @abelmengesha3773
    @abelmengesha3773 Год назад

    Imagine being amigos colleague

  • @kasperserzysko1167
    @kasperserzysko1167 Год назад

    What is this intelij theme?

  • @alimrad7760
    @alimrad7760 Год назад

    🎉🎉🎉

  • @aayush5474
    @aayush5474 Год назад

    Java peeps decided to discard operator overloading but kept it in case of Strings meh

  • @LehmannMr
    @LehmannMr Год назад

    I personally prefer using + concatenation because of its readability. How often do you have such huge concatenations ?
    1.000,000 = 22 sec means even 1000 concatenations will take = 0,02 sec

  • @sohpol
    @sohpol Год назад

    F*ck me. I didn't expect this amount of slowness.

  • @nson22
    @nson22 Год назад

    🤯

  • @XNEP1
    @XNEP1 Год назад

    Why are you able to concatenate strings with the '+' operator. This is so dumb.

  • @RiorXD
    @RiorXD Год назад

    died laughing at a and then null

  • @raidenluikang5532
    @raidenluikang5532 Год назад

    Java String s always not intuitive for developers of other languages:
    1. String may be null and may be empty
    2. String contents compared with equals() method, not with == operator
    3. null String added to other string as "null" :)
    4. String + Integer --> String : "75" + 6 -> "756", Hi from JavaScript.
    5. String non mutable, for mutable operations always use StringBuilder
    6. Java Strings may be globally cached
    7. Doe not have operator [] for access to elements by index, welcome charAt
    ... And more ..

  • @elrolo6858
    @elrolo6858 Год назад

    I just realized I know nothing.
    Thanks amigo

  • @Roger-we3co
    @Roger-we3co Год назад

    Anull... lol

  • @markross89
    @markross89 Год назад

    This is a cool topic, but it's rather basic knowladge. I'm not surprised people don't know this small things, I was the same after my Java bootcamp. Trust me it is worth to get back to basic things and master them properly as it is speeding your work. I'm studing with Oracle OCA studie book that was not recomended by my bootcamp teachers. It explaines all small things like this topic. Even if you dont want to get oracle certification, this book (and this channel 😅) is great way to gain basic knowledge, and stop constantly looking on stackoverflow.

  • @valkokk
    @valkokk Год назад

    A title (and speech) is also part of the video, and I don't feel included in this issue... Don't use "You've been doing it wrong" and not all of us do it like you show it... Instead use "Some of you ..." ... because, you know, some of us also know how to code correctly, and even so, we like to come here.

  • @YusufIbr
    @YusufIbr Год назад +1

    pertamax gan

  • @andrews1318
    @andrews1318 Год назад

    But this example taken to real life is not necessary

  • @AvalancheGameArt
    @AvalancheGameArt Год назад

    Calling the java compiler a COMPILER is a crime. you compile to machine code, in java you translate unto a bytecode for the jvm. is not the same thing,

    • @omer_usta
      @omer_usta Год назад +5

      Actually compiler in here correct, the term "compiler" is a general term used for any software that translates source code written in one programming language into another language. If we were talking about typescript or similar languages which are converting them to another language , the correct verb/word should be "transcompiler".

  • @umairasad3896
    @umairasad3896 Год назад

    Once again first one

  • @assilbenchaaben2573
    @assilbenchaaben2573 Год назад

    The fact that you are using java is already wrong 😂

  • @Damian-qu9us
    @Damian-qu9us Год назад

    good video but u say basically too much man