Basic java programs – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 14 Feb 2023 11:25:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Basic java programs – Java2Blog https://java2blog.com 32 32 Count occurrences of Character in String https://java2blog.com/count-number-occurrences-character-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=count-number-occurrences-character-string-java https://java2blog.com/count-number-occurrences-character-string-java/#respond Mon, 05 Apr 2021 17:12:39 +0000 https://java2blog.com/?p=13391 In this article, we will look at a problem: Given an Input String and a Character, we have to Count Occurrences Of character in String.

For Example, If the Given String is : "Java2Blog" and we have to count the occurrences of Character ‘a’ in the String.

Therefore, Count of 'a' is : 2 , in the String “Java2Blog” . We will discuss different approaches to do this :

Note: The search of the Character will be Case-Sensitive for any String.

1. Using String Library Methods

This is the most conventional and easiest method to follow in order to find occurrences of character in a string . For this, we use the charAt() method present in the String Class of java.lang package. The signature of method is :

public char charAt(index) – index of the character to be found.

  • Iterate throughout the length of the input String
  • Check whether each character matches the character to search
    • If yes, increment the count
    • else do nothing
Let us look at the implementation:

public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int count=0;
  for(int i=0; i<input.length(); i++)
  {
      if(input.charAt(i) == search)
      count++;
  }
  
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

2. Using Recursion

This is a rather interesting and tricky solution. Here, we call our function for the start index 0 of the String. If character matches to searched character, we add 1 to our result variable and recur for index+1, until we reach the end point of the string.

Let us look at the code:

public class CountOccurences
{

  static int findOccurrences(String str, char search, int index)
  {
      if(index >= str.length())
      return 0;
      
      int count=0;
      
      if(str.charAt(index) == search)
      count++;
      
      return count + findOccurrences(str,search,index+1);
  }
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int result = findOccurrences(input,search,0); //start index 0 for       start of string.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

3. Using Hashing Concept

Using Arrays

In this approach, we use a primitive integer type array of size 26. Then for each character in the string we encounter we increment it’s hash value in the array. For each character, char its index in array will be : Arr[ char – 97].

Note: This is a Case Sensitive Approach. If we use Uppercase Characters the index value will be: Arr[ char – 65]. The space we use is constant does not depend on size of input String.

Let us look at the implementation.

public class CountOccurences
{
   
  public static void main(String args[]) 
  {
 
  String input = "aaaabbcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  int hash_arr[] = new int[26];
  
  for(int i=0;i<input.length();i++)
  {
      hash_arr[input.charAt(i) - 97]++;
  }
  
  int result = hash_arr[search-97]; // we get count value of character from the array.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Using Collections (Map)

Here we will do the same thing as above for each character in the input string we will put it in our Map with value 1, if it is seen for the first time. If the character repeats or the character is already present in our Map, we update the value of the character in the map by adding 1 to it. We can use any type of Map; HashMap, TreeMap, https://java2blog.com/linkedhashmap-in-java-with-example/. In this example we used a simple HashMap.

Note: This approach works for both Uppercase and Lowercase Characters. Hence, Case In-Sensitive.

import java.util.*;
public class CountOccurences
{
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbAAAAcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  Map<Character,Integer> hash = new HashMap<Character,Integer>();
  
  for(int i=0;i<input.length();i++)
  {
      if(hash.containsKey(input.charAt(i)))
      hash.put(input.charAt(i), hash.get(input.charAt(i))+1);
      
      else
      hash.put(input.charAt(i), 1);
  }
  
  int result = hash.get(search);
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

4. Using Java 8 Features

If we use Java 8 or above JDK Version, we can use the feature of lambdas and Stream to implement this. We will use the IntStream class methods, chars() method and codePoints() method which returns the integer codepoints (Unicode value) of the character stream. We will then filter them using Lambda expression with the search character and count their occurrences using count method. We will look at each of their implementation.

import java.util.*;
public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaabbAAAAAcccd";
  char search = 'A';             // Character to search is 'a'.
  
  //Example 1
  long count = input.chars().filter(ch -> ch == search).count();
  // chars() method return integer representation of codepoint values of the character stream
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  
  //Example 2
  count = input.codePoints().filter(ch -> ch == search).count();
  // codePoints() just return the actual codepoint or Unicode values of the stream.
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  }
}

Output:

The Character 'A' appears 5 times.
The Character 'A' appears 5 times.

So that’s it for how to count Occurrences Of Character in String, you can try out with other examples and execute the code for better understanding.

]]>
https://java2blog.com/count-number-occurrences-character-string-java/feed/ 0
How to capitalize first letter in java https://java2blog.com/capitalize-first-letter-java/?utm_source=rss&utm_medium=rss&utm_campaign=capitalize-first-letter-java https://java2blog.com/capitalize-first-letter-java/#respond Thu, 24 Dec 2020 17:56:45 +0000 https://java2blog.com/?p=11250 In this post, we will how to capitalize first letter in java

Capitalize first letter of String

Here are the steps to convert first letter of string to uppercase in java

  • Get first letter of String firstLetStr using str.substring(0,1).
  • Get remaining String remLetStr using str.substring(1).
  • Convert first letter of String firstLetStr to upper Case using toUpperCase() method.
  • Concatenate both the String firstLetStr and remLetStr.

package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {

        // create a string
        String name = "java2blog";
        System.out.println("Original String: " + name);
        // get First letter of the string
        String firstLetStr = name.substring(0, 1);
        // Get remaining letter using substring
        String remLetStr = name.substring(1);

        // convert the first letter of String to uppercase
        firstLetStr = firstLetStr.toUpperCase();

        // concantenate the first letter and remaining string
        String firstLetterCapitalizedName = firstLetStr + remLetStr;
        System.out.println("String with first letter as Capital: " + firstLetterCapitalizedName);

    }
}

Output:

Original String: java2blog
String with first letter as Capital: Java2blog

Capitalize first letter of each word

Here are the steps to capitalize first letter of each word.

  • Split String by space and assign it String array words
  • Iterate over the String array words and do following:
    • Get first letter of String firstLetter using str.substring(0,1).
    • Get remaining String remainingLetters using str.substring(1).
    • Convert first letter of String firstLetter to upper Case using toUpperCase() method.
    • Concatenate both the String firstLetter and remainingLetters.

package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {
        // create a string
        String str = "this is java code";
        String words[]=str.split("\\s");
        String capitalizeStr="";

        for(String word:words){
            // Capitalize first letter
            String firstLetter=word.substring(0,1);
            // Get remaining letter
            String remainingLetters=word.substring(1);
            capitalizeStr+=firstLetter.toUpperCase()+remainingLetters+" ";
        }
        System.out.println(capitalizeStr);
    }
}

Output:

This Is Java Code

That’s all about How to capitalize first letter in java.

]]>
https://java2blog.com/capitalize-first-letter-java/feed/ 0
Find first and last digit of a number https://java2blog.com/java-program-find-first-last-digit-number/?utm_source=rss&utm_medium=rss&utm_campaign=java-program-find-first-last-digit-number https://java2blog.com/java-program-find-first-last-digit-number/#comments Fri, 09 Oct 2020 12:30:26 +0000 https://java2blog.com/?p=10870 In this article, we are going to find first and last digit of a number.
To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log() methods of Math class etc.

Let’s see some examples.
Before moving to example, let’s first create an algorithm to find first and last digit of a number.

Algorithm

Step 1: Take a number from the user.
Step 2: Create two variables firstDigit and lastDigit and initialize them by 0.
Step 3: Use modulo operator(%) to find last digit.
Step 4: Use either while loop and division operator (/) or log() and pow() methods of Math class to find

.
Step 5: Display the result.

Using while loop

It is easy to use modulo operator that will return the last digit of the number, and we can use while loop and division operator to get first digit of number.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;

        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);

        while(number!=0) {
            firstDigit = number%10;
            number /= 10;
        }
        System.out.println("First digit: "+firstDigit);
    }
}

Output

Last digit: 7
First digit: 5

Using log() and pow() methods

If we want to use built-in methods like log() and pow() of Math class, then we can use log() method to get the number of digits and pow() method to get divisor value that later on used to get the first digit of number. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;

        // find last digit
        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);

        int digits = (int)(Math.log10(number)); 
        // Find first digit 
        firstDigit = (int)(number / (int)(Math.pow(10, digits)));
        System.out.println("First digit: "+firstDigit);
    }
}

Output

Last digit: 7
First digit: 5

Using while loop and pow() method

If we don’t want to use log() method then use while loop to count the number of digits and use that count into the pow() method to get divisor. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;
        int count = 0;

        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);
        int n = number;
        while(n!=0) {
            count++;
            n = n/10;
        }
        firstDigit = number/(int)Math.pow(10, count-1);
        System.out.println("First digit: "+firstDigit);
    }
}

Output:

Last digit: 7
First digit: 5

That’s all about how to find first and last digit of number.

]]>
https://java2blog.com/java-program-find-first-last-digit-number/feed/ 1
Happy Number program in Java https://java2blog.com/happy-number-program-java/?utm_source=rss&utm_medium=rss&utm_campaign=happy-number-program-java https://java2blog.com/happy-number-program-java/#respond Sat, 03 Oct 2020 05:57:52 +0000 https://java2blog.com/?p=10681 In this article, we are going to learn to find Happy Number using Java. Let’s first understand, what is Happy Number?

What is a Happy Number?

A number which leaves 1 as a result after a sequence of steps and in each step number is replaced by the sum of squares of its digit. For example, if we check whether 23 is a Happy Number, then sequence of steps are

Step 1: 2×2+3×3 = 4+9 = 13 // Sum of square of each digit
Step 2: 1×1+3×3 = 1+9 = 10
Step 3: 1×1+0x0 = 1 (A Happy Number)

We will see two approaches to find happy number in java.

Using Hashset

In this approach, we will use Hashset to tract the cycle and if sum=1 at the end of the cycle, then it is happy number.

Algorithm

  1. Take one variable sum for storing sum of square.
  2. Intialize a HashSet numbers, we will use this HashSet to track repeating cycle.
  3. Iteate through while loop until we get same number again and do following:
    1. Calculate the square of each digit present in the number and add it to the variable sum and divide the number by 10.
    2. Assign sum to number after each iteration
  4. If result sum is equal to 1, then the number is a Happy Number.
  5. Else the number is not happy Number.

Note: A number can not be a Happy Number if it makes a loop in its sequence. For example,

4x4 = 16

1x1+6x6 = 37

3x3+7x7 = 58

5x5+8x8 = 89

8x8+9x9 = 145

1x1+4x4+5x5 = 42

4x4+2x2 = 20

2x2+0x0 = 4 // Number itself

4 = 16  // Repeating process (loop), see step 1

Example

Here is complete example to find Happy number in java.

import java.util.HashSet;
import java.util.Set;

public class Main
{
    public static void main(String args[]) 
    {
        int number  = 1111111;
        int sum = 0;
        Set numbers = new HashSet();
        while(numbers.add(number)){     
            sum = 0;
            while(number>0) {
                sum += (number % 10)*(number % 10); 
                number /=10;
            }
            number = sum;
        }

        // if sum = 1, it is happy number 
        if(sum == 1) {
            System.out.println("It is a happy number");
        }else {
            System.out.println("It is not a happy number");
        }
    }
}

Output

It is a happy number

Using slow and fast pointers

In this approach, we will use slow and fast pointer to track the cycle.

Algorithm

  1. initialize two variables slow and fast with given number.
  2. Iterate through do while loop until we get a cycle (slow!=fast)
    1. Move slow pointer once by calling getSumOfSquareOfDigit() once.
    2. Move fast pointer twice by calling getSumOfSquareOfDigit() twice.
  3. If slow is equal to 1 at the end of cycle, it means it is happy number.

Example

Here is complete example to find Happy number in java.

package org.arpit.java2blog;

public class HappyNumberSlowFast {
    static int getSumOfSquareOfDigit(int num) {
        int ss = 0;
        while (num != 0) {
            ss += (num % 10) * (num % 10);
            num /= 10;
        }
        return ss;
    }

    // method return true if n is Happy number
    static boolean isHappynumber(int num) {
        int slow, fast;

        // initialize slow and fast by num
        slow = fast = num;
        do {
            // move slow number by one step
            slow = getSumOfSquareOfDigit(slow);

            // move fast number by two steps
            fast = getSumOfSquareOfDigit(getSumOfSquareOfDigit(fast));

        } while (slow != fast);

        // If slow and fast point meet and slow is equals to 1,
        // then it is happy number
        return (slow == 1);
    }

    // Main method
    public static void main(String[] args) {
        int n = 1111111;
        if (isHappynumber(n))
            System.out.println(n + " is a Happy number");
        else
            System.out.println(n + " is not a Happy number");
    }

}

Output

1111111 is a happy number

That’s all about How to find Happy Number in Java

]]>
https://java2blog.com/happy-number-program-java/feed/ 0
Find Perfect Number in Java https://java2blog.com/perfect-number-java/?utm_source=rss&utm_medium=rss&utm_campaign=perfect-number-java https://java2blog.com/perfect-number-java/#respond Tue, 29 Sep 2020 18:33:55 +0000 https://java2blog.com/?p=10799 In this article, we are going to find whether a number is perfect or not using Java.

A number is called a perfect number if the sum of its divisors is equal to the number. The sum of divisors excludes the number. There may be several approaches to find the perfect number.
For example:

28 is perfect number:
– 28’s divisors are 1, 2, 4, 7, 14
– sum of divisors of 28 excluding itself is 28.


Here, we are using two main approaches iterative and recursive approach.

Let’s see the example.

Iterative approach

In this example, we are using the while loop to find divisors of the number and then get sum of them.
Here are the steps:

  1. Initiaze sum=0 and loop variable i=1.
  2. Iterate a while loop until condition i<=number/2 is false.
  3. Check remainder of number%i using modulo operator. If remainder is 0, then add it to the sum.
  4. If sum is equals to number after all iterations, then it is perfect number.
    public class Main
    {
    public static void main(String args[]) 
    {
        int number = 28;
        int sum = 0;
        int i = 1;
        while(i<=number/2)
        {
            if(number%i == 0)
            {
                sum+=i;
            }
            i++;
        }
        if(sum == number)
            System.out.println("It is Perfect Number");
        else System.out.println("It is not Perfect Number");
    }
    }

Output

It is Perfect Number

Recursive approach

We can use recursion technique, if don’t want to use while loop. It reduces code statements but provides the accurate result.
Here are the steps:

  1. Initialize static variable sum=0.
  2. Create a function findPerfect() which will take two parameters number and div
  3. Check if div<=number/2 is true. This will be the terminal condition for recursion.
    1. Check remainder of number%i using modulo operator. If remainder is 0, then add it to the sum.
    2. Increment div
    3. Call findPerfect() recursively.
  4. If returned output of findPerfect() is equals to number, then it is perfect number.
    See the example below.

public class Main
{   
    static int number = 8128;
    static int sum = 0;
    static int div = 1;
    static int findPerfect(int number, int div) {
        {
            if(div<=number/2)
            {
                if(number%div==0)
                {
                    sum+=div;
                }
                div++;
                findPerfect(number,div);
            }
            return sum; 
        }
    }
    public static void main(String args[]) 
    {
        int result = findPerfect(number,div);
        if(result == number)
            System.out.println("It is Perfect Number");
        else System.out.println("It is not Perfect Number");
    }
}

Output

It is Perfect Number

That’s all about how to find Perfect Number in Java.

]]>
https://java2blog.com/perfect-number-java/feed/ 0
How to find Magic Number in Java https://java2blog.com/find-magic-number-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=find-magic-number-in-java https://java2blog.com/find-magic-number-in-java/#respond Sun, 27 Sep 2020 19:08:58 +0000 https://java2blog.com/?p=10695 In this article, we are going to learn to find Magic Number using Java.

Let’s first understand, what is Magic Number?

What is a Magic Number?

A number which leaves 1 as a result after a sequence of steps and in each step number is replaced by the sum of its digits. For example, if we check whether 163 is a Magic Number, then sequence of steps are

Step 1: 1+6+3 = 10 // Sum of square of each digit

Step 2: 1+0 = 1 (A Magic Number)

To calculate magic number, we have two approaches either using recursive approach or simple a shorthand logic. Let’s see the examples.

Algorithm for Magic Number

Step 1: Take two variables, sum for storing a sum of square and number for holding the value.

Step 2: Repeat till number greater than 0 or sum is greater than 9.

Step 3: If number is equal to 0, replace the number with the sum of the digits and set sum = 0.

Step 4: Calculate the sum of each digit present in the number and add it to the variable sum.

Step 5: If result sum is equal to 1, then the number is a Magic Number.

Step 6: Else the number is not Magic Number.

Example to find Magic Number

public class Main{

    public static void main(String[] args) { 
        int number = 1000;  // Number to check
        int sum = 0;
        while (number > 0 || sum > 9) 
        { 
            if (number == 0) 
            { 
                number = sum; 
                sum = 0; 
            } 
            sum += number % 10; 
            number /= 10; 
        } 

        // If sum = 1, it is magic number 
        if(sum == 1) {
            System.out.println("It is a magic number");
        }else {
            System.out.println("It is not a magic number");
        }
    }
}

Output:

It is a magic number

Another Example To find Magic Number

There is another approach to find Magic Number. In this approach, we can get Magic Number after dividing a number by 9. This is a shortcut method to verify Magic Number. If we get remainder 1 after dividing a number by 9 then the number is a magic number. It is based on the concept of divisibility rule of 9 which says that if a number is divisible by 9, then sum of its all digits are also divisible by 9. An addition of 1 in the original number will increase the ultimate value by 1, making it 10 and the ultimate sum will be 1, which makes a number a magic number. See the example below.

public class Main{

    public static void main(String[] args) { 
        int number = 10001;  // Number to check
        if(number % 9 == 1) {
            System.out.println("It is a magic number");
        }else {
            System.out.println("It is not a magic number");
        }
    }
}

Output

It is not a magic number

That’s all about magic number in java.

]]>
https://java2blog.com/find-magic-number-in-java/feed/ 0
Number guessing game in java https://java2blog.com/number-guessing-game-java/?utm_source=rss&utm_medium=rss&utm_campaign=number-guessing-game-java https://java2blog.com/number-guessing-game-java/#respond Sun, 27 Sep 2020 18:30:54 +0000 https://java2blog.com/?p=10719 In this article, we will implement Number guessing game in java.

The number guessing game is based on a concept where player guesses a number between a range. If player guesses the exact number then player wins else player looses the game. Since this game provides limited attempts, so, player must guess the number with the limited attempts, else will lose the game.

Let’s understand the game and its rules.

Number guessing game Rules

  1. You must enter only valid integer within the specified range.
  2. You will be provided limited attempts to guess the number.
  3. You cannot leave the game, once started.

If the entered number is less than or greater than the required number, then player gets the message (hint) to proceed further either in up or down range.

Algorithm for Number guessing game

Step 1: Create three variables attempt, userGuessNumber, secretNumber and initialize them.
Step 2: Generate a random number and assigned to secretNumber.
Step 3: Start a loop and take user input.
Step 4: Validate user input and match with the secretNumber.
Step 5: If userGuessNumber is greater than or less than the secretNumber then print a message to user.
Step 6: If userGuessNumber is equal to the secretNumber, then user wins and exit the game.
Step 7: If number of attempts exceeds the limit, exit the game.
Step 8:Repeat from Step 3.

package org.arpit.java2blog;
import java.util.Scanner;
public class Main
{
    public static void main(String args[]) 
    {
        int attempt = 1;
        int userGuessNumber = 0;
        int secretNumber = (int) (Math.random() * 99 + 1);           
        Scanner userInput = new Scanner(System.in);
        System.out.println("Welcome to Guess Number Game \nYou Will Be Asked To Guess A Number To Win The Game \nYou have Maximum 5 Attemp Limit");
        do {
            System.out.print("Enter a guess number between 1 to 100\n");
            if(userInput.hasNextInt()) {
                userGuessNumber = userInput.nextInt();
                if (userGuessNumber == secretNumber)
                {    
                    System.out.println("OOhhOO!, Your Number is Correct. You Win the Game!");
                    break;
                }
                else if (userGuessNumber < secretNumber)
                    System.out.println("Your Guess Number is Smaller.");
                else if (userGuessNumber > secretNumber)
                    System.out.println("Your Guess Number is Greater.");
                if(attempt == 5) {
                    System.out.println("You have exceeded the maximum attempt. Try Again");
                    break;
                }
                attempt++;
            }else {
                System.out.println("Enter a Valid Integer Number");
                break;
            }
        } while (userGuessNumber != secretNumber);
    }
}

Output

Welcome to Guess Number Game
You Will Be Asked To Guess A Number To Win The Game
You have Maximum 5 Attemp Limit
Enter a guess number between 1 to 100
75
Your Guess Number is Greater.
Enter a guess number between 1 to 100
45
Your Guess Number is Smaller.
Enter a guess number between 1 to 100
58
Your Guess Number is Smaller.
Enter a guess number between 1 to 100
67
Your Guess Number is Greater.
Enter a guess number between 1 to 100
62
OOhhOO!, Your Number is Correct. You Win the Game!

That’s all about Number guessing game in java.

]]>
https://java2blog.com/number-guessing-game-java/feed/ 0
Return second last digit of given number https://java2blog.com/return-second-last-digit-number-java/?utm_source=rss&utm_medium=rss&utm_campaign=return-second-last-digit-number-java https://java2blog.com/return-second-last-digit-number-java/#respond Fri, 18 Sep 2020 05:22:29 +0000 https://java2blog.com/?p=10560 In this topic, we will learn to get the second last digit of a number with the help of examples.
There can be several ways to get second last digit; here we are discussing some solutions.

Using modulo operator

Here, we are using modulo and divide operators to find the second last digit. The modulo operator gives remainder of a number while divide operator gives quotient as a result.

public class Main{
    public static void main(String[] args){
        int a = 120025;
        int secondLastDigit = (a % 100) / 10;
        System.out.println(secondLastDigit);
        secondLastDigit = (a / 10) % 10;
        System.out.println(secondLastDigit);
    }
}

Output

2

Using String’s chartAt() method

There is another example in which we can convert the number into a string and then using charAt() method we get second last value after that result convert back to number using Character class.

public class Main{
    public static void main(String[] args){
        int a = 120025;
        String number = Integer.toString(a);
        System.out.println(number);
        int secondLastDigit = Character.getNumericValue((number.charAt(number.length()-2)));
        System.out.println(secondLastDigit);
    }
}

Output

2

That’s all about how to return second last digit of given number.

]]>
https://java2blog.com/return-second-last-digit-number-java/feed/ 0
Java program to print table of number https://java2blog.com/java-program-print-table-number/?utm_source=rss&utm_medium=rss&utm_campaign=java-program-print-table-number https://java2blog.com/java-program-print-table-number/#respond Wed, 09 Oct 2019 18:31:26 +0000 https://java2blog.com/?p=5208 In this post we will see how to print table of number in java.

It is good program to practice for loop in java.

import java.util.Scanner;

public class TableOfNumber
{
    public static void main(String args[]){
        int number, i, table;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Number : ");
        number = scan.nextInt();

        System.out.print("Table of " + number + " is\n");
        for(i=1; i<=10; i++){
            table = number*i;
            System.out.print(number + " * " + i + " = " + table + "\n");
        }
    }
}

Output:

Enter a Number : 8
Table of 8 is
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

That’s all about how to print table of number in java.

]]>
https://java2blog.com/java-program-print-table-number/feed/ 0