Posts

Showing posts with the label Misc-Java-Examples

How to count the number of vowels and consonants in a String

In this blog post, I will be demonstrating a Java program that counts the number of vowels and consonants in a String. Consider the following code sample: public class CountVowelsAndConsonantsDemo { private static List<Character> vowels = Arrays.asList('a','e','i','o','u','A','E','I','O','U'); public static void main(String[] args) { System.out.println("Enter a String:"); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); char[] inputArr = input.toCharArray(); int vowelCount = 0; int consonantCount = 0; for(char c:inputArr){ if(vowels.contains(c)){ vowelCount++; } else consonantCount++; } System.out.println("Number of vowels:"+vowelCount); System.out.println("Number of consonants:"+consonantCount); }}   The code declares and initalizes a list ‘vowels’ with all the vowels in lowercas...

How to find the number of digits in a number

This blog post demonstrates how to count the number of digits in a String.   Method 1 – Using division private static int countDigits(int input){int count = 1;if(input > 10){int quotient = 0;do{count ++;quotient = input/10;input = quotient;}while(quotient > 9);}return count;} The code checks if the number is greater than 10. If so, it divides the number by 10 and checks the quotient. It continues doing this as long as the quotient is greater than 9. Method 2 – Using Strings private static int countDigits(int input){String str = String.valueOf(input);return str.length();} Here, the input number is converted to a String and then its length is used to find the number of digits.

How to find the largest number in an array

In this blog post, I will be demonstrating how you can find the largest number in an array or list. Consider the following code snippet: package demo;public class FindLargestNumberDemo {public static void main(String[] args) {int myArray[] = {2,4,6,8,10,45,9,18,90,12};int largest = 0;for(int num:myArray) {if(num &amp;amp;amp;gt; largest)largest = num;}System.out.println("Largest number is "+largest);}}   Here, we are declaring an array with a list of values. We are then iterating through the elements in the array. We are also declaring a variable called largest and setting its value to 0. Each element in the array is compared to the variable largest. If is is greater than largest, the variable largest is assigned the current element. This is continued for all the elements in the input array. So when this code is executed, it will print the following output:    

How to check if a number is even or odd

This blog post demonstrates how you can check if a number is even or odd via Java.   Consider the following code snippet: public class EvenOddDemo {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("Enter your input:");int num = scanner.nextInt();if(num % 2 == 0)System.out.println("The input number "+num+" is even");elseSystem.out.println("The input number "+num+" is odd");scanner.close();}}   This code first reads an input number using the Scanner class. It then uses the % operator. The % operator returns the remainder of division. So the code checks if the remainder obtained after dividing by 2 is 0. If so, the number is odd, otherwise the number is even. So if you run the code with input as 4, the following output is printed: Enter your input:4The input number 4 is even   If you run the code with input as 7, the following output is printed: Enter your input:7The input n...

How to calculate the sum of the numbers in an array

In this blog post, I will be explaining how you can calculate the sum of numbers in an array. Consider the following code snippet: package demo;public class SumDemo {public static void main(String[] args) {int numbers[] = {5,4,7,9,12};int sum = 0;for(int number:numbers){sum += number;}System.out.println("sum="+sum);}}   A variable called sum is used to store the sum of numbers. It is initialized to 0. There is a for loop used. This iterates through the input list. It adds each number in the list to the sum variable. This code will print the following output: sum=37

How to check if a number is a prime number

In this blog post, I will be demonstrating how you can check if a number is a prime number. Consider the following code snippet: public static void main(String[] args) {Scanner scanner= new Scanner(System.in);System.out.println("Input the number to be checked:");int num=scanner.nextInt();boolean isPrime = true;if (num == 0 || num == 1) {isPrime = false;}else{for (int i = 2; i &lt;= num / 2; i++) {if (num % i == 0) {isPrime = false;break;}}}if(isPrime)System.out.println("The number "+num+" is prime!");elseSystem.out.println("The number "+num+" is not prime!");}   The code first accepts a number from the user. It then checks if the number is 0 or 1, both of which are not prime numbers. It then iterates from 2 till the number/2. It checks if the remainder obtained after dividing the input number with the current index of the for loop is 0. If so, the number is not prime and so it exits the for loop. So if you run the code for the v...

Java loops Examples

In this blog post, I am going to demonstrate all of Java’s loops. I am going to write loops that prints the sum of numbers in a List. For Loop private static int sumFor(List<Integer> numbers){int sum = 0;for(int i=0; i < numbers.size();i++){sum += numbers.get(i);}return sum;}   For Each Loop private static int sumForEach(List<Integer> numbers){int sum = 0;for(int num:numbers){sum += num;}return sum;} While Loop private static int sumWhile(List<Integer> numbers){int sum = 0;int i = 0;while (i < numbers.size()){sum += numbers.get(i);i++;}return sum;} Do While Loop private static int sumDoWhile(List<Integer> numbers){int sum = 0;int i = 0;do{sum += numbers.get(i);i++;}while (i < numbers.size());return sum;}

How to add two numbers in Java

This blog posts shows how to add two numbers in Java:   public class Demo {public static void main(String args[]){int a = 10;int b = 20;int result = add(a,b);System.out.println("Result is "+result);}private static int add(int a,int b){int result = a+b;return result;}}   Here, we are using the method add to add two numbers. It accepts 2 integer values, adds them and returns the result. You can change the data type/ return value to anything else like long,short, float, double, etc. If you run the code, the following output will get printed to the console:   Result is 30

How to find the factorial of a number

In this post, I will be showing you how to find the factorial of a number in Java. The method used in this example does not use recursion. The following code snippet demonstrates how to find the factorial of the given number:. private static int findFactorial(int num){int result = 1;for(int i =1; i <= num;i++){result = result * i;}return result;} So this method iterates from 1 till the input number. It multiplies the current value of i to the result. It continues this till the input number is reached. So if you run this code for the number 5, you will get the result as 120.      

How to find the largest number in an array

The following code demonstrates how to find the largest number in an array:   package demo;public class LargestNumberDemo {public static void main(String[] args) {Integer[] intArr = {45,21,88,210,550,1,34};int max = 0;for(int num:intArr){if(num > max)max = num;}System.out.println("Biggest number is "+max);}}   So the for loop iterates through the array. Initially, the variable max is set to 0. Each number is compared with ‘max’ and if it is greater than max, then it is assigned to ‘max’. This process is repeated till all the elements in the array are exhausted.   This will print the following output: Biggest number is 550   You can use this code to find the largest number from any Collection type like Set or List.