Practice questions of java
1. Write a program in Java to check if a number is even or odd in Java? (input 2 output true, input 3: output false)
A number is called even if it is completely divisible by two and odd if it's not entirely divisible by two. For example, number 4 is even number because when you do 4/2, the remainder is 0, which means 4 is completely divisible by 2. On the other hand, 5 is an odd number because 5/2 will result in the remainder as 1. See here to find
import java.util.Scanner;
public class EvenOddTest{
public class EvenOddTest{
public static void main(String args[]){
//scanner to get input from user
Scanner console = new Scanner(System.in);
System.out.printf("Enter any number : ");
//return the user input as integer
int number = console.nextInt();
//if remainder is zero than even number
if((number %2)==0){
System.out.printf("number %d is even number %n" , number); //%d -decimal %n new line
} else{
//number is odd in Java
System.out.printf("number %d is odd number %n", number);
}
//Finding Even and Odd number using Bitwise AND operator in Java.
System.out.printf("Finding number if it's even or odd using bitwise AND operator %n");
//For Even numbers
//XXX0
//0001 AND
//0000
if( (number&1) == 0){
System.out.printf("number %d is even number %n" , number);
}else{
System.out.printf("number %d is odd number %n", number);
}
}
}
Output:
Enter any number: 17
number 17 is an odd number
Finding number if its even or odd using bitwise AND operator
number 17 is an odd number
Enter any number: 12
number 12 is an even number
Finding number if its even or odd using bitwise AND operator
number 12 is an even number
Practice questions on Let's program
Level 1
1.
Write a program to print
*
**
***
****
on screen.
class Ans{
public static void main(String[] args){
System.out.println("*\n**\n***\n****");
}
}
2.
Print the following pattern on the screen
*****
***
*
***
*****
class Ans{
public static void main(String[] args){
System.out.println("*****\n *** \n * \n *** \n*****");
}
}
3.
Write a program to print the sum of the numbers 2, 4 and 5.
class Ans{
public static void main(String[] args){
System.out.println(2+4+5);
}
}
4.
Write a program to print the difference and product of the numbers 45 and 32.
class Ans{
public static void main(String[] args){
System.out.println(45-32);
System.out.println(45*32);
}
}
5.
Write a program to get the following output.
Hey there,
I am data!
class Ans{
public static void main(String[] args){
System.out.println("Hey there,\nI am data!");
}
}
Comments
Post a Comment