16

I can iterate through the alphabet, but I'm trying to keep the last iteration and add on the next letter. this is my code.

for(char alphabet = 'a'; alphabet <='z'; alphabet ++ )
        {

            System.out.println(alphabet);
        }

I want it to print out something that looks like this.

a

ab

abc

abcd

abcde..... and so forth. How is this possible?

pewpew
  • 700
  • 2
  • 9
  • 32

6 Answers6

23

You need to add the char alphabet to a string.

String output = "";

for(char alphabet = 'a'; alphabet <='z'; alphabet++ )
    {
        output += alphabet;
        System.out.println(output);
    }

This should work for you ;)

Stefan
  • 652
  • 5
  • 10
  • 12
    Never use `String += String` in a loop. Use `StringBuilder`. Sure, this is a small inconsequential loop, but start doing it the right way, so it becomes second nature. – Andreas Oct 16 '15 at 05:43
  • i edited like 2 seconds after i posted lol! such fast response time haha. One thing to note. the output += alphabet needs to be inside the print statement System.out.println(output += alphabet); – pewpew Oct 16 '15 at 05:45
  • 1
    I don't think that has to be in the System.out. Why do you think so? – Stefan Oct 16 '15 at 05:48
  • 1
    @pewpew Sure that's shorter, but "needs to be"? No. – Andreas Oct 16 '15 at 05:49
  • Ok i see what you did there ;) – pewpew Oct 16 '15 at 05:55
  • 1
    @pewpew Of all the answers, you accept the one with the worst performance of them all. It *is* a bit simpler to write than the rest, I'll give you that. It's a good thing there's only 26 letters in the alphabet. – Andreas Oct 16 '15 at 06:36
9

I will go with StringBuffer or StringBuilder. Something like:

StringBuffer

StringBuffer sb = new StringBuffer();
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
    sb.append(alphabet);
    System.out.println(sb.toString());
}

StringBuilder

StringBuilder sb = new StringBuilder();
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
    sb.append(alphabet);
    System.out.println(sb.toString());
}

String vs StringBuffer vs StringBuilder:

String: It is immutable, so when you do any modification in the string, it will create new instance and will eatup memory too fast.

StringBuffer: You can use it to create dynamic String and at the sametime only 1 object will be there so very less memory will be used. It is synchronized (which makes it slower).

StringBuilder: It is similar to StringBuffer. The olny difference is: it not synchronized and hence faster.

So, better choice would be StringBuilder. Read more.

Using Java 8

StringBuilder sb = new StringBuilder();

IntStream.range('a', 'z').forEach(i -> {
    sb.append((char) i);
    System.out.println(sb.toString());
});
Ambrish
  • 3,627
  • 2
  • 27
  • 42
  • `StringBuffer` is obsolete. Use `StringBuilder`. Quoting [javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html): *"As of release JDK 5, `StringBuffer` has been supplemented with an equivalent class designed for use by a single thread, `StringBuilder`."* – Andreas Oct 16 '15 at 05:46
  • I have added both in my solution. – Ambrish Oct 16 '15 at 05:49
  • `StringBuffer` is synchronized, which makes it slower. Unless you're in an extremely rare situation where multiple threads append to the same buffer, you should never use it. Always use `StringBuilder`. Make it a habit. I'd suggest removing `StringBuffer` from answer, so as not to misguide any newbie Java developers coming here. – Andreas Oct 16 '15 at 05:53
  • 1
    @Andreas I dont suggest removing I would suggest the Ambrish should clarify the difference so that OP can choose any method accoding the requirement – singhakash Oct 16 '15 at 05:54
  • @Andreas I have added details and also better solution: Java8. – Ambrish Oct 16 '15 at 06:08
  • Java 8 stream is a nice touch, but I disagree with calling it a "better solution". To me, it's actually slightly worse, but I'd be good with simply calling it "another" way of doing it. – Andreas Oct 16 '15 at 06:16
5

I'd suggest using a StringBuilder:

// Using StringBuilder
StringBuilder buf = new StringBuilder();
for (char c = 'a'; c <= 'z'; c++)
    System.out.println(buf.append(c).toString());

You could also do it slightly faster by using a char[], however StringBuilder is more obvious and easier to use:

// Using char[]
char[] arr = new char[26];
for (int i = 0; i < 26; i++) {
    arr[i] = (char)('a' + i);
    System.out.println(new String(arr, 0, i + 1));
}

Alternatives that you shouldn't use:

  • StringBuffer: Same as StringBuilder, but synchronized, so slower.
  • s = s.concat(new String(c)): Allocates 2 Strings per iteration, instead of only 1.
  • s += c: Internally += is compiled to s = new StringBuilder().append(s).append(c).toString(), so horrendously slow with exponential response times.
Andreas
  • 154,647
  • 11
  • 152
  • 247
0
String s = "" ;  
for(char alphabet = 'a'; alphabet <='z'; alphabet ++ )
        {
            s = s.concat(String.valueOf(alphabet));
            System.out.println(s);
        }
Rahman
  • 3,755
  • 3
  • 26
  • 43
  • I am assuming he will declare it outside of that for loop :). Anyways edited the answer – Rahman Oct 16 '15 at 05:52
  • While this may theoretically answer the question, it's not really a good answer, since it doesn't teach the OP. Instead it gives an alternative solution without explanation. This will usually lead to OP not learning, and coming back for asking a new question when a similar problem occurs. Would you mind adding some explanation? – Vogel612 Oct 16 '15 at 10:39
0

Offtopic, Using Java 8 IntStream it is as simple as:

 StringBuilder builder = new StringBuilder("");
 "abcdefghijklmnopqrstuvwxyz".chars().mapToObj(i -> builder.append((char) i))
      .forEach(System.out::println);

Usage:

 public class AlphabetsLooping {
    static final String input = "abcdefghijklmnopqrstuvwxyz";

    public static void main(String[] args) {

    StringBuilder builder = new StringBuilder("");
    input.chars().mapToObj(i -> builder.append((char) i))
            .forEach(System.out::println);
  } 
}
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
0

Actually to use IntStream.range You would need to add +1 to have last letter Z

So, it would be

StringBuilder sb = new StringBuilder();

IntStream.range('a', 'z'+1).forEach(i -> {
    sb.append((char) i);
    System.out.println(sb.toString());
});