Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#For loop' - 5 code snippet(s) found

 Sample 1. Write a Program to reverse a string iteratively and recursively

Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

Strategy - Loop through each character of a String from last to first and append the character to StringBuilder / StringBuffer

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

Strategy - Call the method with substring starting from 2nd character recursively till we have just 1 character.

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

   Like      Feedback     string  StringBuffer  recursion  for loop  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation


 Sample 2. Retry in case of exception

public static final int NUMBER_OF_RETRIES = 5;

try {
   // do something
} catch (Exception e) {
   int count;
   for (count = 1; count <= NUMBER_OF_RETRIES; count++) {
      Thread.sleep(5000);
   } catch (InterruptedException e1) {
      try {
         // do something again
         break;
      } catch (Exception ex) {
   }
}

   Like      Feedback     exception handling   exception   Retry in case of exception   for loop   for   Thread.sleep   InterruptedException


 Sample 3. Write a method to input 10 numbers and then print the sum.

public void calculateSum() {
   Scanner scanner=new Scanner(System.in);
   int sum=0;
   for(int counter=1;counter<=10;counter++)
      sum=sum+(scanner.nextInt());

   System.out.println("The sum is: "+sum);
}

   Like      Feedback     scanner  for loop  scanner.nextInt   input numbers and print sum


 Sample 4. Display elements of a List using For loop

List myList = new ArrayList();
      
myList.add("A");
myList.add("B");
myList.add("C");

for(String str:myList){ // prints A B C
   System.out.println(str);
}

   Like      Feedback     Print elements of a list   for loop   arraylist  list  collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Display elements of a List using For Loop and index

List myList = new ArrayList();
      
myList.add("A");
myList.add("B");
myList.add("C");

for(int index=0;index < myList.size(); index++){
   System.out.println(myList.get(index));
}

   Like      Feedback     Print elements of a list   arraylist  list  collections   for loop



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus