Where we learn technology

Category: Java Interview

Java Program to Find ASCII Value of a character

For each character we have predefined ASCII numbers: 

ASCII Table

Find ASCII Value of a character in Java

package JavaQuestions;
/**
 * 
 * @author NaveenKhunteta
 *
 */
public class AsciiChar {
public static void main(String[] args) {
char c = ‘a’; // 97
int ascii = c;
int asciiNumber = (int) c;
System.out.println(“ASCII value of “ + c + “:”+ ascii);
System.out.println(“ASCII value of “ + c + “:”+ asciiNumber);

}

}

Output is:

ASCII value of a:97

ASCII value of a:97

Java Program to Add Two Integers

This is very simple, just define two integer variables and use + operator to add them.

package JavaQuestions;

/**
 * 
 * @author NaveenKhunteta
 *
 */
public class AddNumbers {

	public static void main(String[] args) {

		int a = 10;
		int b = 20;

		int sum = a + b;

		System.out.println("sum of a and b is: " + sum);

	}

}

Output:

sum of a and b is: 30

Java Program to Print an Integer (Entered by the User)

Print an Integer – entered by user from console/command line

package JavaQuestions;

import java.util.Scanner;

/**
 * 
 * @author NaveenKhunteta
 *
 */
public class PRintImnteger {

	public static void main(String[] args) {

		Scanner reader = new Scanner(System.in);
		System.out.println("plz enter a number: ");

		int num = reader.nextInt();

		System.out.println("you entered: " + num);

	}

}

Scanner class is a default class which is coming from java.util package. It is used to take the user input from the console.

Example:

plz enter a number: 

10

you entered: 10

How to find Armstrong Number

How to find Armstrong Number

Learn:
1. check the given number is Armstrong or not.
2. write different test cases for Armstrong Number

Code:

package Questions;
public class ArmstrongNumber {
//153
//1*1*1 = 1
//5*5*5 = 125
//3*3*3 = 27
//1+125+27 = 153
//407 == 4*4*4 + 0 + 7*7*7 = 407
//0
//1 == 1*1*1 = 1
//370, 371
public static void isArmstrongNumber(int num){
//153 ==  1*1*1    5*5*5      3*3*3
System.out.println(“given number is “+ num );
int cube = 0;
int r;
int t;
t=num;
while(num>0){
r = num%10; 
num = num/10;
cube = cube+(r*r*r);
}
if(t==cube){
System.out.println(“this is an armstrong number”);
}else{
System.out.println(“this is not an armstrong number”);
}
}
public static void main(String[] args) {
isArmstrongNumber(153);
isArmstrongNumber(370);
isArmstrongNumber(0);
isArmstrongNumber(1);
isArmstrongNumber(455);
}
}