Python try-except- else vs finally with example program

  • For detail explanation of try and except block please check below link
  • Python try and except blocks with an example program
  • We will place all statements which are proved to generate exceptions in try block.
  • If any exception occurred then exception block will handle the exceptions.
  • If no exception raised in try block then except block wont be executed and else block will be executed.
  • In this scenario we might move the code from else to try block. If any exception raised in try block other statements in try block wont be executed and also else block will not be executed.
  • Finally block will always executes irrespective of any kind of exceptions.
  • So if we place any statements inside finally block of python script then those those statements will be executed for sure.
  • Else block will be executed when no exception occurred in try and finally will executes irrespective of any exception.
  • Lets see an example python program on try-except-else and try except-else-finally.




#1: Write a Python program which explains usage both else and finally blocks in python programming.

  1. #try_except with both else and finally blocks:
  2. string=input("enter some string: ")

  3. try:
  4.     x=string[5]
  5.     print("char at index 5 is: ",x)
  6.     print("no exception")
  7. except IndexError as e:
  8.     print("exception raised: ",e)
  9. else:
  10.     print("else block is executing becoz of no exception")
  11. finally:
  12.     print("finally block will always executes")


Output

  1. enter some string: python
  2. char at index 5 is:  n
  3. no exception
  4. else block is executing becoz of no exception
  5. finally block will always executes


python else vs python finally

Python finally block example with program

  • Before discussing about finally block, please check our previous articles on try, except and else blocks. 
  • Basic python programs on try , except and else
  • As we already know about try like its duty is to find any exceptions if occurs and pass it to python except block so that except block will assign exception class object to handle exceptions.
  • Else will be executed if no exception occurs.
  • Finally block will executes even exceptions occurs. so in some situations we need to execute some statements compulsory even if any exceptions occurs in that scenario we will use python finally block
  • We will place all statements which would be executes irrespective of exceptions.
  • Lets see an example program on python finally block.
  • Python try except finally example
     



#1: Write a python program which explains usage of finally block in exception handling of python programming.

  1. try:
  2.   x = int(input("enter first number: "))
  3.   y = int(input("enter second number: "))
  4.   result=x/y
  5. except ArithmeticError as e:
  6.    print("cannot devide a number by zero: ", e)
  7. finally:
  8.    print("finally block")

Output
  1. enter first number: 10
  2. enter second number: 0
  3. cannot devide a number by zero:  division by zero
  4. finally block

finally block python

Python try except else with example program

  • Please read below post to get an idea of try and except blocks in detail
  • Python try except example program
  • We will place all statements which are proven to generate exceptions in try block so that if any error occurred it will immediately enters into except and assign exception object to corresponding class.
  • If any exception occurs in try then except will be executed in order to handle the exception.
  • If no exception occurred in the try the it will executes else block.
  • So in Python exception handing else block will be executed if and only if no exceptions are occurred in try block and all the statements in try executed.
  • Lets see an example program on how can we use else in python exception handling
  • try-except-else 




#1: Write a python example program which explains usage of else block in exception handling of python programming.

  1. try:
  2.     x = int(input("enter 1st number: "))
  3.     y = int(input("enter 2nd number: "))
  4.     print(x/y)
  5.     string=input("enter some string: ")
  6.     print(string[8])
  7. except (IndexError, ZeroDivisionError) as e:
  8.     print("An error occurred :",e)
  9. else:
  10.     print("no error")

Output

  1. enter 1st number: 2
  2. enter 2nd number: 0
  3. An error occurred : division by zero

  4. enter 1st number: 2
  5. enter 2nd number: 1
  6. 2.0
  7. enter some string: python
  8. An error occurred : string index out of range

  9. enter 1st number: 2
  10. enter 2nd number: 1
  11. 2.0
  12. enter some string: python is very easy
  13. s
  14. no error  


python else example program

Python try except example program

  • Exceptions are the objects representing the logical errors that occur at run time.
  • When python script encounters any error at run time it will create python object.
  • So we need to handle this situation otherwise python program will terminates because of that run time error ( Exception Object).
  • So we can handle this by assigning this python exception object to corresponding python class.
  • For that Python provides try and except blocks to handle exceptions.
  • In try block we need to keep all the statements which may raise exceptions at run time.
  • except block will catch that exception and assigns to corresponding error class.
  • Lets see an example python program on exception handling using try and except blocks.




#1: Example Program to handle exception using try and except blocks in python programming.

  1. #use of try_catch in functions:
  2. def f():
  3.    x=int(input("enter some number: "))
  4.    print(x)

  5. try:
  6.     f()
  7.     print("no exception")
  8. except ValueError as e:
  9.     print("exception: ", e)
  10.     print("Rest of the Application")

Output

  1. enter some number: 2
  2. 2
  3. no exception
  4. >>> 



  5. enter some number: "python"
  6. exception:  invalid literal for int() with base 10: '"python"'
  7. Rest of the Application
  8. >>> 

try and except python example

How to Convert string to StringBuilder and vise versa in Java


  • We can Covert String to string builder in two ways
  1. Using constructor of StringBuilder(String s)
  2. Using append method of StringBuilder 
  • Lets see a java program to convert java String object to StringBuilder using constructor of StringBuilder class.

#1: Java program to convert string to StringBuilder using constructor of StringBuilder class.



  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert String to StringBuilder
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {
  11. String str="java";
  12. StringBuilder sb = new StringBuilder(str);
  13. String s = sb.toString();
  14. System.out.println(s);
  15. StringBuilder stebldr= new StringBuilder("convert string to stringbuilder");
  16. String st = stebldr.toString();
  17. System.out.println(st);
  18. }

  19. }

Output

  1. java
  2. convert string to stringbuilder

#2: Java program to convert string to StringBuilder using append method of StringBuilder class.
  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert String to StringBuilder
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {

  11. StringBuilder sb = new StringBuilder();
  12. sb.append("Java convert string to StringBuilder ");
  13. System.out.println(sb);
  14. String str= "Convert string to Stringbuilder" ;
  15. sb.append(str);
  16. System.out.println(sb);
  17. }

  18. }


Output

  1. Java convert string to StringBuilder 
  2. Java convert string to StringBuilder Convert string to Stringbuilder

  • We can Convert StringBuilder to String by using toString() method of StringBuilder class.
  • How to convert StringBuilder to String in java.


#3: Java program to convert string to StringBuilder using append method of StringBuilder class.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert StringBuilder to String
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {

  11. StringBuilder sb = new StringBuilder();
  12. sb.append("Java convert  StringBuilder to string");
  13. String str=sb.toString();
  14. System.out.println(str);
  15. String s= "Convert Stringbuilder to string " ;
  16. sb.append(s);
  17. String st=sb.toString();
  18. System.out.println(st);
  19. }

  20. }

Output

  1. Java convert  StringBuilder to string
  2. Java convert  StringBuilder to stringConvert Stringbuilder to string 


java program to convert string to string builder

Java Program to check a String is palindrome or not by ignoring its case


  • A palindrome is a word that reads the same backward or forward.
  • Lets see what if the characters in a palindrome string are in different case. i.e should not be case sensitive. 
  • So now we will see how to check a string is palindrome or not by ignoring its case.
  • Write a function which checks  that string is palindrome or not by converting the original string to lowercase or uppercase.
  • Method should return true if it is palindrome, return false if not a palindrome.


#1 : Java Program to check given string is palindrome or not by ignoring its case.

  1. package com.instanceofjava;

  2. public class CheckPalindrome {
  3. public static boolean isPalindrome(String str) {
  4. StringBuffer strone=new StringBuffer(str.toLowerCase());
  5. StringBuffer strtwo=new StringBuffer(strone);
  6.  
  7.   strone.reverse();
  8.  
  9.   System.out.println("Orginal String ="+strtwo);
  10.   System.out.println("After Reverse ="+strone);
  11.  
  12. if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
  13. return true;
  14.     else
  15.     return false;
  16. }
  17. public static void main(String[] args) {
  18. boolean ispalindrome= isPalindrome("DeleveleD");
  19. System.out.println(ispalindrome);
  20.  
  21.     }

  22. }

Output

  1. Orginal String =deleveled
  2. After Reverse =deleveled
  3. true

check palindrome or not ignore case sensitive

How to Delete folder and subfolders using Java 8

  • How to delete folder with all files and sub folders in it using java 8.
  • We can use java 8 Stream to delete folder recursively 
  • Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  • .sorted(Comparator.reverseOrder())
  • .map(Path::toFile)
  • .peek(System.out::println)
  • .forEach(File::delete);

  1. Files.walk -  this method return all files/directories below the parent folder
  2. .sorted - sort the list in reverse order, so the folder itself comes after the including subfolders and files
  3. .map - map the file path to file
  4. .peek - points to processed entry
  5. .forEach - on every File object calls the .delete() method 




#1: Java Example program to delete folders and subfolders using java 8 stream

  1. package com.instanceofjava;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.FileVisitOption;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.util.Comparator;
  9. /**
  10.  * @author www.Instanceofjava.com
  11.  * @category interview questions
  12.  * 
  13.  * Description: delete folders and sub folders using java 8
  14.  *
  15.  */

  16. public class DeleteFolder {

  17. public static void main(String[] args) {
  18. Path rootPath = Paths.get("C:\\Users\\Saidesh kilaru\\Desktop\\folder1");
  19. try {
  20. Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  21.     .sorted(Comparator.reverseOrder())
  22.     .map(Path::toFile)
  23.     .peek(System.out::println)
  24.     .forEach(File::delete);
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }

  29. }

Output:

  1. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder\file2 in sub folder.docx
  2. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder
  3. C:\Users\Saidesh kilaru\Desktop\folder1\file1.docx
  4. C:\Users\Saidesh kilaru\Desktop\folder1



How to Convert integer set to int array using Java 8

  • How to convert Integer Set to primitive int array.
  • By Using java 8 Streams we can convert Set to array.
  • set.stream().mapToInt(Number::intValue).toArray();
  • Lets see an example java program on how to convert integer set to int array using java 8

#1: Java Example program on converting Integer Set to int Array

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class SetToArray {
  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programming questions
  9.  * 
  10.  * Description: convert Integer set to int array using java 8
  11.  *
  12.  */
  13. public static void main(String[] args) {
  14. Set<Integer> hashset= new HashSet<>(Arrays.asList(12,34,56,78,99));
  15. int[] array = hashset.stream().mapToInt(Number::intValue).toArray();
  16. for (int i : array) {
  17. System.out.println(i);
  18. }

  19. }

  20. }

Output:

  1. 34
  2. 99
  3. 56
  4. 12
  5. 78





integer set to integer array java


In Java, a Set is a collection that contains no duplicate elements and is unordered. To convert a Set to an array, you can use the toArray() method of the Set interface. This method returns an array containing all of the elements in the Set in the order they are returned by the iterator.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

Integer[] array = set.toArray(new Integer[set.size()]);



In this example, we first create a HashSet of integers, add some elements to it, then we use the toArray method to convert it to an array of integers.

toArray(T[] a) method where we can pass an empty array of a specific type, the method will fill the array with the elements from the set, this is useful if you know the size of the array that you need.

converting a Set to an array in Java can be done using the toArray() method of the Set interface. The method returns an array containing all of the elements in the Set in the order they are returned by the iterator. This method can also accept an empty array of a specific type, the method will fill the array with the elements from the set.

Initializing a boolean array in java with an example program

  • Initializing a boolean variable : boolean b=true;
  • In some cases we need to initialize all values of boolean array with true or false.
  • In such cases we can use Arrays.fill() method
  • Arrays.fill(array, Boolean.FALSE);
  • java initialize boolean array with true:  Arrays.fill(array, Boolean.FALSE);
  • Lets see an example java program on how to assign or initialize boolean array with false or true values.



#1: Java Example program on initializing boolean array.

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview questions
  6.  * 
  7.  * Description: Initialize boolean array values with false or true
  8.  *
  9.  */
  10. public class InitializeBoolean {

  11. public static void main(String[] args) {
  12. Boolean[] array = new Boolean[4];
  13. //initially all values will be null
  14. for (int i = 0; i < array.length; i++) {
  15. System.out.println(array[i]);
  16. }
  17. Arrays.fill(array, Boolean.FALSE);
  18. // all values will be false
  19. for (int i = 0; i < array.length; i++) {
  20. System.out.println(array[i]);
  21. }
  22. Arrays.fill(array, Boolean.TRUE);
  23. // all values will be false
  24. for (int i = 0; i < array.length; i++) {
  25. System.out.println(array[i]);
  26. }
  27. }

  28. }

Output:

  1. null
  2. null
  3. null
  4. null
  5. false
  6. false
  7. false
  8. false
  9. true
  10. true
  11. true
  12. true


java initialize boolean array with true

Java 8 initialize set with values with an example program

  • We can initialize set while defining by passing values to constructor.
  • For example to initialize HashSet we can use Arrays.asList(value1,value2).
  • Set<Integer> hashset = new HashSet<>(Arrays.asList(12, 13));

#1: Java Example program to initialize set without using java 8

  1. import java.util.Arrays;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5.  * @author www.Instanceofjava.com
  6.  * @category interview questions
  7.  * 
  8.  * Description: Initialize set 
  9.  *
  10.  */
  11. public class InitializeSet {

  12. public static void main(String[] args) {

  13. Set<Integer> hashset = new HashSet<>(Arrays.asList(12, 13));
  14. System.out.println(hashset);
  15. }

  16. }

Output:

  1. [12, 13]


  • We can initialize set in java 8 using Stream.
  • Stream.of("initialize", "set").collect(Collectors.toSet());



#2: Java Example program to initialize set without using java 8

  1. import java.util.Set;
  2. import java.util.stream.Collectors;
  3. import java.util.stream.Stream;
  4. /**
  5.  * @author www.Instanceofjava.com
  6.  * @category interview questions
  7.  * 
  8.  * Description: Initialize set using java 8 Stream
  9.  *
  10.  */
  11. public class InitializeSet {

  12. public static void main(String[] args) {

  13. Set<String> set = Stream.of("initialize", "set").collect(Collectors.toSet());
  14. System.out.println(set);
  15. }

  16. }



Output:

  1. [set, initialize]


  • We can initialize Set in java 8 by creating stream from an Array and list


#3: Java Example program to initialize set without using java 8


java 8 initialize set with values with an example program

Top 10 Java array example programs with output

1.Java Example program to find missing numbers in an array.


2. Java interview Example program to find second maximum number in an integer array


3.Java Practice programs on arrays: find second smallest number.


4. How many ways we can print arrays in java: lets check below link for 5 different ways.


5.Advantages and disadvantages of arrays




6. Benefits of arraylist over arrays


7. Creating Array of objects in java 


8. Find top two maximum numbers in an array : java array practice programs


9. Remove duplicates from an array java


10. Sort integer array using Bubble Sort in java


How to run multiple java programs simultaneously in eclipse

  • In some cases we may need to run two java programs simultaneously and need to observe the ouput of two progarsms. In such cases we need to run multiple java programs parallel.  
  • Now we will see how to run two java programs simultaneously
  • First thing we need to understand is we can run multiple java programs at a time in eclipse.
  • Second thing is we can view multiple consoles in eclipse.   



#1. How can we open multiple consoles in eclipse?

  • In Eclipse console window right side we will have one rectangular box with Plus symbol on it to open a new console. by clicking on it we can open a new console view.

open multiple consoles  view in eclipse


2: Create two java programs.

ClassOne:
  1. package com.instanceofjava;

  2. public class ClassOne {
  3. /**
  4. * @author www.Instanceofjava.com
  5. * @category interview questions
  6. * Description: how to run two java programs simultaneously
  7. *
  8. */
  9. public static void main(String[] args) throws InterruptedException {

  10. for (int i = 0; i < 100; i++) {
  11. Thread.sleep(1000);
  12. System.out.println(i);
  13. }
  14. }
  15. }

ClassTwo
  1. package System.out;

  2. public class ClassTwo {
  3. /**
  4. * @author www.Instanceofjava.com
  5. * @category interview questions
  6. * Description: how to run two java programs simultaneously
  7. *
  8. */
  9. public static void main(String[] args) throws InterruptedException {
  10. for (int i = 100; i < 200; i++) {
  11. System.out.println(i);
  12. Thread.sleep(1000);
  13. }


  14. }

  15. }


  • Run ClassOne and ClassTwo.
  • Pin console.

pin console.png



  • You can see both the running programs with output with different console views.
how to run two java programs simultaneously

Log4j example in java using properties file

  • Logging is very important part of programming. Logging helps programmer to understand process flow and identify the problems where actually occurred.
  • Log4J will be configured externally using properties file. We can print the logging statements in the console or we can push them in to a log file based on the requirement.
  •  org.apache.log4j class will provide required classes to implement logging
  • We need to add Log4J dependency in our project.
  • Create instance of logger by using Logger.getLogger(Log4JExample.class);
  • Lets see how to create log4j.properties file in eclipse



1. Create a maven project and add Log4J dependency:


how to create log4j.properties file in eclipse

2. Create log4j.properties file


log4j.properties example file

  1. log4j.rootLogger=INFO, console

  2. log4j.appender.console=org.apache.log4j.ConsoleAppender

  3. log4j.appender.console.layout=org.apache.log4j.PatternLayout
  4. log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz}

3.Create java example program to read log4j.properties file

  1. import org.apache.log4j.BasicConfigurator;
  2. import org.apache.log4j.Logger;

  3. public class Log4JExample {

  4. static Logger logger = Logger.getLogger(Log4JExample.class);
  5.     public static void main(String[] args)
  6.     {
  7.     BasicConfigurator.configure();
  8.     logger.info("main method start!!");
  9.    
  10.     System.out.println("hi");
  11.     logger.info("log4j properties configuration example");
  12.      
  13.     logger.info("main method end!!");
  14.     }
  15. }

Output:

  1. 2018-02-08 23:09:10.747 IST0 [main] INFO Log4JExample  - main method start!!
  2. hi
  3. 2018-02-08 23:09:10.752 IST5 [main] INFO Log4JExample  - log4j properties configuration example
  4. 2018-02-08 23:09:10.753 IST6 [main] INFO Log4JExample  - main method end!!

Java program to reverse ArrayList elements

  • How to reverse an ArrayList in java.
  • By using Collections.reverse() method we can reverse ArrayList in java.



#1: Java Example program to reverse ArrayList 

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Collections;

  4. public class ReverseArrayList {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview questions
  8. * Description: Java Example program to reverse an ArrayList
  9. *
  10. */
  11. public static void main(String[] args) {
  12. ArrayList<String> arrayList= new ArrayList<>();
  13. arrayList.add("Apple");
  14. arrayList.add("Banana");
  15. arrayList.add("Orange");
  16. Collections.reverse(arrayList);
  17. System.out.println(arrayList);
  18. }

  19. }


Output:

  1. [Orange, Banana, Apple]


#2: Java Example program to print arraylist in reverse order 


reverse arraylist in java example program

How to convert list to set in java with example program

  • Java program to convert list to set.
  • Convert ArrayList of string to HashSet in java example program
  • How to convert List to Set in java 
  • Set<String> strSet = new HashSet<String>(arrList);
  • HashSet having a constructor which will take list as an argument.
  • Lets see how to convert list to Set using java program.



#1: Java Example Program to Convert List to Set.


  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = new HashSet<String>(arrList);
  18. System.out.println(strSet);

  19. }

  20. }

Output:

  1. [Java, Example Program, List to String]

  • Using java.util.stream we can convert List to set in java 8
  • We can use java 8 java.util.stream.Collectors
  • arrList.stream().collect(Collectors.toSet());

#2: Java Example program to convert List to Set using java 8.

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Set;
  4. import java.util.stream.Collectors;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = arrList.stream().collect(Collectors.toSet());
  18. System.out.println(strSet);

  19. }

  20. }


Output:

java convert list to set

How to convert list to comma separated string using java 8

  • Howto convert list to comma separated string using java 8 stream.
  • By using collect() method of stream  and Collectors.join(",") method we can convert list to comma separated string in java 8.
  • Java Example program to convert list of strings to comma separated string.



#1: Java Example program to convert list to comma separated string using java 8 stream.

  1. package com.instanceofjava;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.stream.Collectors;

  5. /**
  6.  * @author www.Instanceofjava.com
  7.  * @category interview programming questions
  8.  * 
  9.  * Description: convert ArrayList of strings tp comma separated string using java 8
  10.  *
  11.  */
  12. public class ArrayToString {

  13. public static void main(String[] args) {
  14. ArrayList<String> colours =new ArrayList<>();
  15. colours.add("Red");
  16. colours.add("Green");
  17. colours.add("Orange");
  18.    String result = colours.stream().collect(Collectors.joining(","));
  19.    System.out.println(result);
  20.    
  21. }
  22. }


Output:
  1. Red,Green,Orange


convert list to comma separated string using java 8

How to remove square brackets from string in java

  • Remove square brackets from string in java.
  • We can remove square brackets from string by  using regular expressions.
  • By using regular expressions we can remove any special characters from string.
  • Now , we will check how to remove brackets from a string using regular expressions in java.



#1: Java Example program to remove brackets from string using regex.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: remove square brackets from string 
  7.  *
  8.  */
  9. public class ArrayToString {

  10. public static void main(String[] args) {
  11.  String strbrackets = "[String nundi ][brackets][remove cheyyadam][yela?]";
  12.  strbrackets = strbrackets.replaceAll("\\[", "").replaceAll("\\]","");
  13.  System.out.println(strbrackets);
  14.  
  15. }
  16. }


Output:

  1. String nundi bracketsremove cheyyadamyela?


#2: Java program to remove curly brackets from string 



remove square brackets from string java curly

How to convert array to string without brackets in java

  • Converting array to string and string should not contain any brackets.
  • We can convert array to string by iterating array and capturing each element from an array and append to StringBuilder/StringBuffer so that final output will be string without brackets.
  • Lets see an example java program to convert array to string by removing brackets.
  • So that we can remove brackets from string.



#1 : Java Example program to convert array to string without brackets.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: convert array to string without brackets.
  7.  *
  8.  */
  9. public class ArrayToString {

  10. public static void main(String[] args) {
  11.  String array[]= {"java","string","without","brackets"};
  12.  StringBuffer strbuffer = new StringBuffer();
  13.  for (String str : array) {
  14.   strbuffer.append(str).append(" ");
  15.  }
  16.  String result = strbuffer.toString();
  17.  System.out.println(result);
  18.  
  19. }

  20. }

Output:

  1. java string without brackets 



convert array to string without brackets

Java Program to convert ArrayList to String array

  • Java code to convert arraylist to string array.
  • We can convert ArrayList of strings to String array by using  toArray() method.
  • Lets see an Example java program to convert ArrayList to string array.



#1:  Java example program to convert ArrayList to String Array

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. public class ArrayListToStringArray {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview programs
  8. * Description: Java Prorgam to convert ArrayList to String array
  9. *
  10. */
  11. public static void main(String[] args) {
  12. List<String> lstflowers = new ArrayList<String>();
  13. lstflowers.add("Rose");
  14. lstflowers.add("Lilly");

  15. String[] arrayflower = new String[lstflowers.size()];
  16. arrayflower = lstflowers.toArray(arrayflower);

  17. for(String flower : arrayflower)
  18.     System.out.println(flower);
  19. }

  20. }


Output:


  1. Rose
  2. Lilly

#2:  Java example program to convert ArrayList to String Array Using java 8

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. public class ArrayListToStringArray {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview programs
  8. * Description: Java Prorgam to convert ArrayList to String array using java 8
  9. *
  10. */
  11. public static void main(String[] args) {
  12. List<String> lstflowers = new ArrayList<String>();
  13. lstflowers.add("Rose");
  14. lstflowers.add("Lilly");

  15. String[] arrayflower = lstflowers.toArray(new String[lstflowers.size()]);

  16. for(String flower : arrayflower)
  17.     System.out.println(flower);
  18. }

  19. }


java program to convert arraylist to string array

Java 8 subtract N minutes from current date

  • Java 8 provides java.time.LocalDateTime class.
  • By using minusMinutes() methods of LocalDateTime class we can subtract minutes from date or current date in java.
  • Lets see an example program on how to remove / subtract n minutes from current date using java 8.



  1. package com.instanceofjava.java8;

  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: subtract minutes to current date using java 8
  8.  *
  9.  */
  10. public class AddMinutesToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13.     LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before subtracting 30 minutes to date: "+datetime);
  15.     //add seconds by using minuesMinutes(seconds) method
  16. datetime=datetime.minusMinutes(30);
  17. System.out.println("After subtracting 30 minutes to date: "+datetime);

  18. }

  19. }

Output:

  1. Before subtracting 30 minutes to date: 2018-02-05T22:41:42.463
  2. After subtracting 30 minutes to date: 2018-02-05T22:11:42.463


subtract minutes from java 8 date time.png

Select Menu