Check if a Number is valid using Java

Below is a snippet to check if a number  is valid or not. For example, the string “1.1.1” contains an invalid number, while the string “2.1” contains a valid number. The Code public class Main { public static void main (String[]args) { int i; System.out.println("Enter a Number:"); String str = System.console().readLine (); try { Double.parseDouble(str);... » read more

Retrieve Items from a LinkedList in Java

Here is another Java snippet that can help to enhance your program by using LinkedLists. The code below will retrieve all items from a linkedList and print them one by one to the console. class Main { public static void main(String[] args) { java.util.LinkedList<String> employees = new java.util.LinkedList<String>(); employees.add("Scott"); employees.add("Marie"); employees.add("Dun"); for (String string :... » read more

StringBuilder class constructors in Java

Below is a program that demonstrates the most used StringBuilder constructors in Java. public class Main { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(5); StringBuilder sb3 = new StringBuilder("Hello World"); System.out.printf("StringBuilder I = \"%s\"\n", sb1); System.out.printf("StringBuilder II = \"%s\"\n", sb2); System.out.printf("StringBuilder III = \"%s\"\n", sb3); }... » read more

Calculate the average of array element using Java

Below is a program that calculates the average value of an array using Java. public static void main(String[] args) { int[] arr= new int[]{1,2,3,4,5}; int sum = 0; for(int count=0; count < arr.length ; count++) sum = sum + arr[count]; double average = sum / arr.length; System.out.println("The average value of the array elements is :... » read more

Get the sum of array element using Java

Here is a program in Java that sums up all array element and print out the result to the console. class Main { public static void main(String[] args) { int[] arr = {1,2,3,4,5}; int total = 0; for (int i = 0; i < arr.length; i++) total += arr[i]; System.out.printf("The sum of array elements is:... » read more

Get the square root of a number using Java

Square root can be easily obtained in Java by using the Math.sqrt function. The Math is a class in Java that contains methods that allows you to perform mathematical operations. System.out.println(Math.sqrt(9)); Result 3 More Java Snippets