Java program to Obtain the sum of first and last digit of four digit number

 In this post, we are going to write a java program to obtain the sum of first and last digit of four digit number in four different ways.

1. Java program to Obtain the sum of first and last digit using Scanner class:

Program:

import java.util.*;
import java.io.*;
class FirstLast
{
public static void main(String args[])
{
int sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Four Digit number");
int n=sc.nextInt();
int n1=n/1000;
int n2=n%10;
sum=n1+n2;
System.out.println("sum of first and last digit number is "+sum);
}
}

Output:

Enter Four Digit number
1234
sum of first and last digit number is 5

2. Java program to Obtain the sum of first and last digit using Buffered Reader class:

Program:

import java.util.*;
import java.lang.*;
import java.io.*;
class FirstAndLast
{
public static void main(String args[]) throws Exception
{
	int sum=0;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any number");
int n= Integer.parseInt(br.readLine());
int n1=n/1000;
int n2=n%10;
sum=n1+n2;
System.out.println("sum of first and last digit number is "+sum);
}
}

Output:

Enter any number
1001
sum of first and last digit number is 2

3. Java program to Obtain the sum of first and last digit of using Command Line Argument:

Program:

import java.util.*;
class FirstAndLast
{
public static void main(String args[])
{
	int sum=0;
int n= Integer.parseInt(args[0]);
System.out.println(n);
int n1=n/1000;
int n2=n%10;
sum=n1+n2;
System.out.println("sum of first and last digit number is "+sum);
}
}

Compile:

javac FirstAndLast.java

Run:

java FirstAndLast 1055
1005
sum of first and last digit number is 6

4. Java program to Obtain the sum of first and last digit of four digit number using Constructor:

Program:

import java.util.*;
import java.io.*;
import java.lang.*;
class FirstNumber
{
	FirstNumber(int n)
	{
	 int n1=n/1000;
int n2=n%10;
int sum=0;
 sum=n1+n2;
System.out.println("sum of first and last digit number is "+sum);
    }
 }

class FirstAndLast
{
   public static void main(String args[]) throws Exception
    {   
      BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any number");
int num1= Integer.parseInt(br.readLine());      
      FirstNumber obj =new FirstNumber(num1);
	}
 }
 

Output:

Enter any number
1001
sum of first and last digit number is 2

Data Structures and Algorithm Handwritten Free Notes PDF

Leave a Comment