Reverse String in Java Practice Program #41

Поділитися
Вставка
  • Опубліковано 23 гру 2024

КОМЕНТАРІ • 200

  • @alexlorenlee
    @alexlorenlee  Рік тому +2

    If you’re new to programming but want a career in tech, I HIGHLY RECOMMEND applying to one of Springboard’s online coding bootcamps (use code ALEXLEE for $1,000 off): bit.ly/3HX970h

  • @vishy
    @vishy 5 років тому +27

    Really enjoyed working through this practice program ... will be working through the rest of your practice programs and tutorials! Please continue uploading programs and tutorials - they are invaluable. As always, thanks loads Alex!

  • @jorgerivera7008
    @jorgerivera7008 5 років тому +84

    This channel is keeping me sane as I study for my Java Final next Monday!! Super underrated channel, cant wait for the blow-up!!

    • @alexlorenlee
      @alexlorenlee  5 років тому +3

      Jorge Rivera thanks! Good luck!

    • @remax110
      @remax110 5 років тому +1

      I agree, Alex does a very very good job with explaining especially for beginners like me. I'm glad to find this channel.

  • @marko8640
    @marko8640 4 роки тому +8

    Here's by far the simplest solution I've found so far (with user input):
    Scanner scan = new Scanner (System.in);
    System.out.println("Enter a String: ");
    String s = scan.nextLine();
    System.out.println(new StringBuilder(s).reverse().toString());

    • @subhakar9015
      @subhakar9015 3 роки тому +2

      new StringBuilder(s).reverse() is enough
      toString() no need

    • @keithtammi2106
      @keithtammi2106 2 роки тому +5

      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter a Word: ");
      String r = reverse(scanner.nextLine());
      System.out.println(r);

    • @DriveandThrive
      @DriveandThrive 2 роки тому

      @@keithtammi2106 you would still need to create a reverse method.
      private static String reverse(String nextLine) {
      StringBuilder stringBuilder = new StringBuilder(nextLine);
      return stringBuilder.reverse().toString();
      }
      Then that would work.

  • @kamalkaur1479
    @kamalkaur1479 3 роки тому +2

    Alex you know, I am beginner of java but after listen your video my enthusiasm is build up. I am really apricated by heart to see your amazing job

  • @ClarkieReidri
    @ClarkieReidri 4 роки тому +6

    A more efficient way of coding this is to just make it one for loop to decrement through the initial String but making a int tempIndex starting at 0, counting through the decrements, to add each char to the array using the string constructor to pass the now reversed char array to a string.

  • @anathadenver6027
    @anathadenver6027 2 роки тому +2

    That was a great tutorial. I didn't expect that you'd explain how would the computer read the code. That made me easier to compose in my mind all the codes that you've written. Thank you so much.

  • @qwerasdfhjkio
    @qwerasdfhjkio 4 роки тому +5

    I found an easier way!
    public String reverseString(String s) {
    String reversedString = "";
    for (int i = s.length()-1; i >= 0; i--)
    reversedString += s.charAt(i);
    s = reversedString;
    return s;
    }
    Basically, you take a string as a parameter.
    Then you create an empty string. We'll need it later.
    Then, you start a loop which basically says to copy each character of "s" starting from the left to this empty string.
    then set "s" to the reversedString and return.

  • @linusziegler2413
    @linusziegler2413 3 роки тому +5

    I gotta admit, learning with this channel is much more fun, keep it up :D

  • @werren894
    @werren894 4 роки тому +47

    if java can make dog to god, imagine what java could do to you

  • @mamtasingha6949
    @mamtasingha6949 4 роки тому +4

    You are great Alex, Really njoyed working with you... I can easily understand all your concepts ... It's supper fun Thank you ❤️

  • @richardsonmoraes2893
    @richardsonmoraes2893 4 роки тому +1

    the best java channel of all youtube.

  • @imtiazbasha3324
    @imtiazbasha3324 2 роки тому +1

    Amazing and crystal clear explanation. Really enjoyed this practice program. Thank you Alex

  • @flashinstincts5032
    @flashinstincts5032 3 роки тому

    i think u are an angel. u are amazing. i learn how helpful humans are from ur kind work.

  • @DC-xj2fe
    @DC-xj2fe 2 роки тому

    Used this week 2 day 2 of Revature Java training. Very helpful. Thanks!

  • @daltonmiltimore2376
    @daltonmiltimore2376 2 роки тому

    Your videos are singlehandedly allowing me to pass my class

  • @marinastr3429
    @marinastr3429 4 роки тому +2

    Thank you very much for this video! I am studying applied informatics and I’m in the first semester. During corona everything‘s a little complicated, so I’m even more glad that you uploaded this tutorial. Have a good one! ☺️

  • @ItzKingzz
    @ItzKingzz 4 роки тому +6

    I think this code is a lot easier, just so we don't have to use arrays:
    public class ReverseString {
    public static void main(String[] args) {
    String test = "dog"; // have the string "dog"
    reverse(test); // reverses and prints out dog
    }
    public static void reverse(String s){
    StringBuilder result = new StringBuilder(); // creating a new string called result
    for (int h = s.length() - 1; h >= 0; h--) { // go through the s backwards
    result.append(s.charAt(h)); // appends or add the characters into our new string result
    }
    System.out.println(result); // print out the reverse version
    }
    }

    • @ItzKingzz
      @ItzKingzz 4 роки тому +3

      or you could simply have something like this:
      public class ReverseString {
      public static void main(String[] args) {
      String test = "dog"; // have the string "dog"
      reverse(test); // reverses and prints out dog
      }
      public static void reverse(String s){
      for(int i = s.length() - 1 ; i >= 0 ; i--) {
      System.out.print(s.charAt(i));
      }
      }
      }

    • @hydrogennetwork
      @hydrogennetwork 11 місяців тому

      that makes sense

  • @AngieGiovanna
    @AngieGiovanna 10 місяців тому

    omg i was finally able to run my first program after watching this video! this helped me so much!

  • @rittenbrake1613
    @rittenbrake1613 4 роки тому +4

    I think Alex can be patented as an cartoon character, super viewer friendly

  • @ferfykins
    @ferfykins 4 роки тому +1

    Excellent video, can't wait to see more!!

  • @volkancamas986
    @volkancamas986 2 роки тому +4

    Hi Alex ,
    Instead of the for loop you wrote at 6:42, we can reach the result by creating a string as follows. I wanted to write to support.
    Which one is better for performance, I don't know :)
    String reversedString = new String(letters);
    return reversedString;

    • @rikkoo
      @rikkoo Рік тому

      he couldve used reversedString += charAt(i) while decrementing the i or even used a StringBuilder, thats beyond the point, its only to teach you the logic, did i mention its free?

  • @hammershigh
    @hammershigh 3 роки тому +1

    A few questions:
    1. line 11 - Is char array an object, since you use "New"?
    2. line 21 - Does the + operator add ANY datatype to a string, since letters[i] is a char?
    Great videos, btw :)

  • @crazywarrior1232
    @crazywarrior1232 5 років тому +10

    Hey Alex I have recently joined your discord server and wondered if u are available anytime as I have some questions as I have just started coding. Love your content by the way! Much easier to learn Java with you than any channel I have found before.

    • @alexlorenlee
      @alexlorenlee  5 років тому +5

      Crazywarrior123 sure! I’ll hop over in the discord and I’ll see what I can help you with

  • @reshmashaik3091
    @reshmashaik3091 4 роки тому +2

    You got a new subscriber from India

  • @shirinelmanson7839
    @shirinelmanson7839 3 роки тому

    Alex you are good teacher
    String name = "Shirin";
    for (int i =name.length()-1;i>=0;i--) {
    System.out.print(name.charAt(i));
    }

  • @indranildutta4252
    @indranildutta4252 3 роки тому

    made this code to have ask for input --- works charm

  • @mohammadmursalin6412
    @mohammadmursalin6412 3 роки тому

    Pure gem this channel

  • @yashwanthpraveen6798
    @yashwanthpraveen6798 2 роки тому

    This is like the most complicated version of explanation for an easy problem.

  • @searemebrahtu8113
    @searemebrahtu8113 2 роки тому +2

    public static void main(String[] arg){
    String myStr = "hello";
    String h ="";
    for(int i = myStr.length() - 1; i >= 0; i--){
    h = h + myStr.charAt(i);
    }

    System.out.println(h);
    }
    Wouldnt this be easier?

    • @sareer
      @sareer 3 місяці тому

      Exactly

  • @dragomirpetrov5138
    @dragomirpetrov5138 2 роки тому +2

    Really sad that you decided to stop making Java tutorials. I believe you have a gift for teaching! Best wishes, man!

    • @dimitarvelinov277
      @dimitarvelinov277 2 роки тому

      @Dragomir Petrov, another Bulgarian here who agrees with you!

  • @osidarap8561
    @osidarap8561 4 роки тому

    thanks for the help man, keep up the great work!

  • @zaur884
    @zaur884 3 роки тому

    I like when you explain everything again in the end. Thanks.

  • @SimpleProgrammer0
    @SimpleProgrammer0 3 роки тому

    I Thought in starting you are going to remove ln form S.out.println but after that in last you are explaining it amazingly

  • @rittenbrake1613
    @rittenbrake1613 4 роки тому

    Very Clear , Thank you Alex

  • @AktherBrothersOfficial
    @AktherBrothersOfficial 2 роки тому

    Which code is more efficient, the one in video or the one below?
    String text = sc.nextLine();
    int[] chars = text.chars().toArray().clone();
    for(int i=chars.length-1; i>=0; i--) {
    char c = (char)chars[i];
    result += c;
    }

  • @swedishguyonyoutube4684
    @swedishguyonyoutube4684 3 роки тому

    Much appreciated!
    /First year CS student!

  • @규-l4y
    @규-l4y 5 років тому

    thank you sm Alex, i'm a beginner and your videos are really helping me to understand things.

  • @conanimation
    @conanimation 3 роки тому

    are u gonna do API like Lamda and Stremes ,btw grreat vids

  • @salaamdev
    @salaamdev 3 роки тому

    i did this and worked, is it a must to do your way?
    public static void main(String[] args){
    String rev = "hello";

    for(int i = rev.length() -1; i >= 0; i--)
    System.out.println(rev.charAt(i));
    }

  • @MisterWealth
    @MisterWealth 5 років тому +1

    Why is it s.length() - 1? What does the minis one do?

  • @SMIlYER
    @SMIlYER 3 роки тому

    INSANE INFORMATIONS!!

  • @sebon11
    @sebon11 3 роки тому

    Woooow, dude this tutorial is great and very helpful! Thanks

  • @irvingpurata2939
    @irvingpurata2939 4 роки тому +2

    Why do you need an other for loop if this one reverses the string?
    for(int i = str.length() -1 ; i > =0 ; i--) {
    System.out.print( str.charAt(i));
    }

    • @Paramjit_purewal
      @Paramjit_purewal 4 роки тому +1

      Yes but it stores it in a array of char, the other loop helps in putting that elements in a string.

  • @jenniferbijan1912
    @jenniferbijan1912 5 років тому +1

    thank the lord I found these videos. I'm currently taking a Data Structures and Algorithms course and I am L O S T.

  • @lolabello
    @lolabello 4 роки тому

    Thank you very much! this is super helpful ❤️

  • @sheetalpatil8591
    @sheetalpatil8591 2 роки тому

    Why there is a second for each loop can u tell in first only we are taking the character in reverse order can not we directly print?

  • @keanaleong7745
    @keanaleong7745 3 роки тому +1

    Hello Alex. Line 15 at 9:26 would it be correct to have something like letters[0] instead of creating the letterIndex variable in line 13?

    • @krm.073
      @krm.073 Рік тому

      with the variable letterIndex you have some sort of counter for the reversed string/the char array. you start at index 0 and go up thus filling the array slots bit by bit with the characters of the string you want to reverse. if you used 0 or any constant number instead, you would redifine the character at the same slot with each itteration instead of moving to the next slot. (it's been 1 year but i still hope this was helpfull haha)

  • @peppermintdior
    @peppermintdior 4 роки тому

    very well explained alex :)

  • @jmc7773
    @jmc7773 Рік тому

    You made it more complicated than it needed to be 🙂

  • @ferfykins
    @ferfykins 4 роки тому

    Was also hoping you could do another video on this, exactly the same but with an enhanced for loop.

  • @vanamutt43
    @vanamutt43 3 роки тому +1

    Love your tutorials man.
    would this shorter bit of code be okay as well? achieves same result:
    String string = "Hello";
    char buf;
    String reversed = "";
    int i = string.length() - 1;
    while (i >= 0)
    {
    buf = string.charAt(i);
    reversed += String.valueOf(buf);
    i--;
    }

  • @udayendubose1166
    @udayendubose1166 3 роки тому

    This guy got my intrest in computer science

  • @TomaAndreiMusic
    @TomaAndreiMusic 2 роки тому

    This code is cleaner and it does the same thing:
    class HelloWorld {
    public static void main(String[] args) {
    System.out.println(reverse("Alex"));
    }
    static String reversed = "";
    public static String reverse(String s){
    for(int i = s.length() - 1; i >= 0; i--){
    reversed += s.charAt(i);
    }
    return reversed;
    }
    }

  • @GenjaOrigins
    @GenjaOrigins 3 роки тому

    Very Good i had some problems on learning how to use Eclipse but very good video. I need examples.

  • @pokemonbakogan7442
    @pokemonbakogan7442 4 роки тому

    hi , thank you for the explaing , but can you plz explain how to create A program in which all arguments passed to the input string are displayed in reverse order. For example, if 2 arguments were passed - make install, then llatsni ekam should be displayed. Note *: to parse a word by letter, you must use the charAt () function. For example, str.charAt (i) will return the character at position i in the word written to the string variable str. Str command

  • @emrekorkmaz5469
    @emrekorkmaz5469 3 роки тому

    you can basiclly write print instead of println?

  • @amiraibrahim5174
    @amiraibrahim5174 4 роки тому

    Thank you and ily you saved my life !!

  • @bennevisson7787
    @bennevisson7787 Рік тому

    can u please make a video on the USSDMenu program

  • @somkhit_phosavath
    @somkhit_phosavath Рік тому

    Here's one of two ways I do reverse String:
    public static void reverseString() {
    String dog = "dog", dogs = "";
    int reverse = dog.length();
    for(int i = reverse - 1; i >= 0; i --) {
    dogs = dogs + dog.charAt(i);
    }
    System.out.println(dogs);
    }

  • @parvezquazi6424
    @parvezquazi6424 2 роки тому

    best explanation on whole youtube

  • @StyleNasty
    @StyleNasty 3 роки тому

    Hey man you have helped me a lot ! Bless ya

  • @markk5495
    @markk5495 4 роки тому +1

    Great video. It really makes programming a lot more fun when doing programming exercises. Btw, what's wrong with the
    for (int i = s.length() - 1; i >= 0; i--){
    System.out.println(s.charAt(i));
    } ? I mean, the code worked fine and the result is good too.
    Why did you have to create another for-loop?

  • @Harshada1638
    @Harshada1638 3 роки тому +1

    Thank you so much

  • @sajedamirza6252
    @sajedamirza6252 4 роки тому +1

    Hi, is it possible for you to organize java tutorials and java OOP tutorials separately. So that , it would be easier to find. Thanks. You are doing great!

  • @eduartzina
    @eduartzina 3 роки тому

    hello, i may need some help here with a code i got. I have 2 string arrays with names. from a method, I feed with 2 string Arrays and return strings with names, and by using "string.join" I have to print all names present in arrays . any idea how to solve this?

  • @veervikramsingh8911
    @veervikramsingh8911 Рік тому

    sir How have you written String r = reverse("dog");

  • @remax110
    @remax110 5 років тому +1

    I like this java practice. I understand the concept a lot better. Thank you.

  • @marko8640
    @marko8640 3 роки тому +1

    Hey, there's another, much simpler way, by using String Buffer class. The beer's on you, guys.
    String One = "JavaTutorial";
    StringBuffer sbuff = new StringBuffer(One);
    System.out.println(sbuff.reverse());

    • @dafneylogan7433
      @dafneylogan7433 2 роки тому +1

      Awesome!!! It was so much simpler and it's easier to remember.

  • @mohanrajpalanisamy2469
    @mohanrajpalanisamy2469 2 роки тому

    {
    String s="Dog",rev="";
    Int l=s.length();
    For(i=l-1;1>=0;1--)
    {
    rev=rev+s.charAt(i);
    }
    sysout(rev)
    }

  • @humanbeing8048
    @humanbeing8048 3 роки тому

    Nice Alex. great explaination

  • @morgvng8437
    @morgvng8437 Рік тому +1

    simple, you chose god and dog because in italian its translated with "dio cane" a very common phrase here

  • @zeeu
    @zeeu 3 роки тому +1

    public static String reverseStr(String str) {
    String finalStr = "";

    for(int i=str.length()-1; i >= 0;i--) {
    finalStr += Character.toString(str.charAt(i));
    }

    return finalStr;
    }

    • @salaamdev
      @salaamdev 3 роки тому

      public static void main(String[] args){
      String rev = "hello";

      for(int i = rev.length() -1; i >= 0; i--)
      System.out.println(rev.charAt(i));
      }

  • @kamalkaur1479
    @kamalkaur1479 3 роки тому

    can you please also help
    me Convert roman number to integer number?

  • @eien7228
    @eien7228 5 років тому +9

    i still dont understand wht is the String reverse = ""; for

  • @cabreraaubrey4569
    @cabreraaubrey4569 3 роки тому

    is it with return and with parameter method?

  • @fizzics5588
    @fizzics5588 4 роки тому

    where is that keyboard from??

  • @ax8621
    @ax8621 3 роки тому

    It works just fine 💎👌

  • @shives179
    @shives179 2 роки тому

    how to use input hello world and output world hello in java

  • @ClarkieReidri
    @ClarkieReidri 4 роки тому

    Nice custom keeb, silent tacts?

  • @shaccc3728
    @shaccc3728 3 роки тому

    This is briefly how I did it:
    for (int i = len -1; i > 0; i--) {
    rev += norm.charAt(i);
    }

  • @sincodemayo9119
    @sincodemayo9119 4 роки тому

    How can I reverse a string that the user inputs?

  • @ЦветославПаскалев-д9х

    I like your tutorials, keep it up :)

  • @TheBoDuddly
    @TheBoDuddly 2 роки тому

    Great tuts as always....you could simplify this one though and not even use a char array.
    Just concatenate the charAt(i) straight into your empty string and return the result. :)
    public static String reverse(String s){
    String result = "";
    for (int i = s.length() -1; i>=0; i--){
    result += s.charAt(i);
    }
    return result;
    }

    • @sesebere
      @sesebere Рік тому

      Is believe he's aware this but doesn't want to do anything advanced for this tutorial, for the sake of beginners

  • @sazidulhoque9892
    @sazidulhoque9892 Рік тому

    thanks bro 👍

  • @selimaltayev3034
    @selimaltayev3034 4 роки тому

    Every time we concating a new character to the string are we creating new string object?

  • @samarthvs3338
    @samarthvs3338 2 роки тому

    A less complex method-
    public class Main
    {
    static String reverse(String s)
    {
    String reversed = "";
    for(int i = s.length()-1; i >= 0; i--){
    reversed = reversed + s.charAt(i);
    }
    return reversed;
    }
    public static void main(String[] args) {
    System.out.println(reverse("0123456"));
    }
    }

    • @kakashi99908
      @kakashi99908 2 роки тому

      yeah the char array was totally unnecessary and added more complexity.

  • @ferfykins
    @ferfykins 4 роки тому

    Love your channel/videos.... Was hoping to get your advice on something... I recently finished a course on java that was 70+ hours worth of video..... So I know the basics of the language.. Wondering where i should go from there... For example... Currently i have no idea where to start with building a project, for example, say a game of tetris, i have no idea where to start on this. Any advice? Thanks!!

  • @kylebaker8548
    @kylebaker8548 4 роки тому

    so how would I do this if I wanted to make it a stack instead of a char[ ] array? I know I would have to us push()

  • @bernhardtrian7471
    @bernhardtrian7471 3 роки тому

    why -1 at for loop ?

  • @keeprunning5457
    @keeprunning5457 Рік тому

    thanks!

  • @monicapacheco933
    @monicapacheco933 3 роки тому

    Love your video, Thanks

  • @trodg
    @trodg 2 роки тому

    Thanks alex!

  • @josh7297
    @josh7297 4 роки тому

    Can someone explain what the static does? I thought it just makes stuff constant. Sorry I'm still new to java

  • @CrazyChaosClara
    @CrazyChaosClara 4 роки тому

    Might be a stupid question... but why can't I create another string and call the method by writing s.reverse?

    • @marko8640
      @marko8640 4 роки тому

      It's a totally valid question because I tried to do something similar in my code. It didn't work, so here I am, looking here for help. It bothers me, why it can't be simpler, like writing just a line or two of code. It's just writing a sentence backward.

  • @mjbuenaventura8169
    @mjbuenaventura8169 3 роки тому

    1. Create a program that will let the user to enter decimal numbers and will sort the inputted values into descending order. Make sure that the user will be able to decide how many numbers he or she wanted to enter. Use one dimensional array.
    2. Create a program that will let the user to enter decimal numbers and will sort the inputted values into ascending order. Make sure that the user will be able to decide how many numbers he or she wanted to enter. Use one dimensional array.
    3. Using the following initial values, 90,87,1,99,34,23,1000 and 78, create a program that will search where an element is located on an index of the array.
    4. Create a program that will let the user to enter decimal numbers and will search and display the location of an element.
    hello I'm a student also a beginner and I don't know how to solve this problems. thank you😇

  • @bhargavsai2449
    @bhargavsai2449 4 роки тому

    you are awesome buddy

  • @himusardar8329
    @himusardar8329 4 роки тому

    I didn't like the dog & god example. But I understood the method. Thanks for that ❤️.

  • @thimiradk
    @thimiradk 4 роки тому +2

    this method is very easy. look.
    public class ReverseString {
    public static void main(String[] args) {
    String str= "Hello World!";
    String reverse= new StringBuilder(str).reverse().toString();
    System.out.println(reverse);
    }
    }

    • @latedeveloper7836
      @latedeveloper7836 4 роки тому

      This actually helped me more than the video - much more succinct and worked perfectly - thanks!

    • @thimiradk
      @thimiradk 4 роки тому +1

      @@latedeveloper7836 you welcome dr. 🙋

    • @marko8640
      @marko8640 4 роки тому

      Wow. Both thumbs up!

  • @DMPDEV
    @DMPDEV 3 роки тому

    hey @Alex Lee, thanks for the help, I`ve been looking all around, and you are the best at it. Short and to the point. Anyway, I´m using Netbeans, not Eclipse. cause of school. so for some reason, its not working. It aint broken, it´s just not printing what it is supposed to.
    public static void main(String[] args) {
    String r = reverse("dog");
    System.out.println(r);
    }
    public static String reverse(String s) {
    int i; = 0 ; i--){
    letterIndex = s.charAt(i);
    letterIndex++;
    }
    String reverse = "";
    return reverse;
    }
    so if you , or anyone in the comments could help out I would really appreciate it.
    Thanks, *firm handshake from Argentina