Java Practice
Java Practice
Array
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
We will see two programs to find the average of numbers using array. First
Program finds the average of specified array elements. The second programs
takes the value of n (number of elements) and the numbers provided by user
and finds the average of them using array.
import java.util.Scanner;
public class JavaExample {
package com.beginnersbook;
import java.util.Scanner;
public class JavaExample {
static int fact(int num) {
int factorial;
System.out.println("Pascal Triangle:");
for(i = 0; i < rows; i++) {
for(j = 0; j < rows-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+ncr(i, j));
}
System.out.println();
}
}
}
Output:
Java Program to Find square root of a
Number without sqrt
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
package com.beginnersbook;
import java.util.Scanner;
class JavaExample {
double sr = number / 2;
do {
temp = sr;
sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);
return sr;
}
In the user defined method we are using two methods of the Math
class, sqrt() method and floor() method. The Math.sqrt() method finds the square
root of the given number and the floor() method finds the closest integer of the
square root value returned by sqrt() method. Later we have calculated the
difference between these two to check whether the difference is zero or non-
zero. For a perfect square number this difference should be zero as the
square root of perfect square number is integer itself.
package com.beginnersbook;
import java.util.Scanner;
class JavaExample {
if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
}
}
Output:
Related Java Examples
In this tutorial, we will write a java program to break an input integer number
into digits. For example if the input number is 912 then the program should
display digits 2, 1, 9 along with their position in the output.
package com.beginnersbook;
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int num, temp, digit, count = 0;
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
This program uses linear search algorithm to find out a number among all
other numbers entered by user.
Example Program:
This program will prompt user for number of rows and based on the input, it
would print the Floyd’s triangle having the same number of rows.
import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
Random Numbers:
***************
135
173
5
17
15
The output of above program would not be same everytime. It would generate
any 5 random numbers between 0 and 200 whenever you run this code. For
e.g. When I ran it second time, it gave me the below output, which is entirely
different from the above one.
Output 2:
Random Numbers:
***************
46
99
191
7
134
import java.util.Scanner;
class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
//The entered value is stored in the var n
n = scanner.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are:");
//2 is a known prime number
System.out.println(2);
}
class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
System.out.println("First 100 prime numbers are:");
System.out.println(2);
for ( int i = 2 ; i <=100 ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
Output:
Once we have all the strings stored in the string array, we are comparing the
first alphabet of each string to get them sorted in the alphabetical order.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);
This program reverses every word of a string and display the reversed string
as an output. For example, if we input a string as “Reverse the word of this
string” then the output of the program would be: “esrever eht drow fo siht
gnirts”.
Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP
import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
We will see two programs to reverse a string. First program reverses the given
string using recursion and the second program reads the string entered by
user and then reverses it.
Here we will see how to calculate area of triangle. We will see two following
programs to do this:
1) Program 1: Prompt user for base-width and height of triangle.
2) Program 2: No user interaction: Width and height are specified in the
program itself.
Program 1:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate area of Triangle in Java
* with user interaction. Program will prompt user to enter the
* base width and height of the triangle.
*/
import java.util.Scanner;
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
//Area = (width*height)/2
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
Output:
/**
* @author: BeginnersBook.com
* @description: Program to Calculate area of Triangle
* with no user interaction.
*/
class AreaTriangleDemo2 {
public static void main(String args[]) {
double base = 20.0;
double height = 110.5;
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
Output:
In this example we are gonna see how to get IP address of a System. The
steps are as follows:
import java.net.InetAddress;
class GetMyIPAddress
{
public static void main(String args[]) throws Exception
{
/* public static InetAddress getLocalHost()
* throws UnknownHostException: Returns the address
* of the local host. This is achieved by retrieving
* the name of the host from the system, then resolving
* that name into an InetAddress. Note: The resolved
* address may be cached for a short period of time.
*/
InetAddress myIP=InetAddress.getLocalHost();
My IP Address is:
115.242.7.243
Reference:
InetAddress javadoc
Once we have all the strings stored in the string array, we are comparing the
first alphabet of each string to get them sorted in the alphabetical order.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);
Related Ja
The number which is only divisible by itself and 1 is known as prime number.
For example 2, 3, 5, 7…are prime numbers. Here we will see two programs:
1) First program will print the prime numbers between 1 and 100 2) Second
program takes the value of n (entered by user) and prints the prime numbers
between 1 and n. If you are looking for a program that checks whether the
entered number is prime or not then see: Java Program to check prime
number.
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
Output:
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
Output:
In this post, we will write two java programs, first java programs checks
whether the specified number is positive or negative. The second program
takes the input number (entered by user) and checks whether it is positive or
negative and displays the result.
→ If a number is greater than zero then it is a positive number
→ If a number is less than zero then it is a negative number
→ If a number is equal to zero then it is neither negative nor positive.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
number = scan.nextInt();
scan.close();
if(number > 0)
{
System.out.println(number+" is positive number");
}
else if(number < 0)
{
System.out.println(number+" is negative number");
}
else
{
System.out.println(number+" is neither positive nor negative");
}
}
}
Output:
Here we will see two programs to add two numbers, In the first program we
specify the value of both the numbers in the program itself. The second
programs takes both the numbers (entered by user) and prints the sum.
import java.util.Scanner;
public class AddTwoNumbers2 {
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140
There are two ways to convert a char array (char[]) to String in Java:
1) Creating String object by passing array name to the constructor
2) Using valueOf() method of String class.
Example:
This example demonstrates both the above mentioned ways of converting a
char array to String. Here we have a char array ch and we have created two
strings str and str1 using the char array.
class CharArrayToString
{
public static void main(String args[])
{
// Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
String str = new String(ch);
System.out.println(str);
good morning
good morning
Here we will write a java program that checks whether the given number is
Armstrong number or not. We will see the two variation of the same program.
In the first program we will assign the number in the program itself and in
second program user would input the number and the program will check
whether the input number is Armstrong or not.
xy..z = xn + yn+.....+ zn
where n denotes the number of digits in the number
370 = 33 + 73 + o3
= 27 + 343 + 0
= 370
Let’s write this in a program:
To understand this Program you should have the knowledge of following Java
Programming topics:
number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}
if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:
if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output:
import java.util.Scanner;
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter any number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Output:
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
with this:
int i=2;
while(i<= num/2)
{
if(num % i == 0)
{
isPrime = false;
break;
}
i++;
}
We will write three java programs to find factorial of a number. 1) using for
loop 2) using while loop 3) finding factorial of a number entered by user.
Before going through the program, lets understand what is factorial: Factorial
of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n
import java.util.Scanner;
public class JavaExample {
Program 1:
Program will prompt user for the input number. Once user provide the input,
the program will calculate the factorial for the provided input number.
/**
* @author: BeginnersBook.com
* @description: User would enter the 10 elements
* and the program will store them into an array and
* will display the sum of them.
*/
import java.util.Scanner;
class FactorialDemo{
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
Output:
class FactorialDemo2{
public static void main(String args[]){
int factorial = fact(4);
System.out.println("Factorial of 4 is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
Output:
Factorial of 4 is: 24
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
When you start learning java programming, you get these type of problems in
your assignment. Here we will see two Java programs, first program takes two
integer numbers (entered by user) and displays the product of these numbers.
The second program takes any two numbers (can be integer or floating point)
and displays the result.
import java.util.Scanner;
Here we are using data type double for numbers so that you can enter integer
as well as floating point numbers.
import java.util.Scanner;
Here we will write a java program to check whether the input year is a leap
year or not. Before we see the program, lets see how to determine whether a
year is a leap year mathematically:
To determine whether a year is a leap year, follow these steps:
1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days). Source of these steps.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}
if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
Output:
while(num>0)
{
rem=num%16;
str2=hex[rem]+str2;
num=num/16;
}
System.out.println("Method 2: Decimal to hexadecimal: "+str2);
}
}
Output:
In this tutorial we are gonna see how to do sorting in ascending & descending
order using Bubble sort algorithm.
class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
import java.util.Scanner;
class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
This program finds the largest of three numbers using ternary operator. Before
going through the program, lets understand what is a ternary Operator:
Ternary operator evaluates a boolean expression and assign the value
based on the result.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int num1, num2, num3, result, temp;
/* Scanner is used for getting user input.
* The nextInt() method of scanner reads the
* integer entered by user.
*/
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();
In this program we will see how to read an integer number entered by user.
Scanner class is in java.util package. It is used for capturing the input of the
primitive types like int, double etc. and strings.
import java.util.Scanner;
We will write three java programs to find factorial of a number. 1) using for loop 2) using
while loop 3) finding factorial of a number entered by user. Before going through the
program, lets understand what is factorial: Factorial of a number n is denoted as n! and the
value of n! is: 1 * 2 * 3 * … (n-1) * n
The same logic we have implemented in our programs using loops. To understand these
programs you should have a basic knowledge of following topics of java tutorials:
import java.util.Scanner;
public class JavaExample {
1) With user interaction: Program will prompt user to enter the radius of the
circle
2) Without user interaction: The radius value would be specified in the
program itself.
Program 1:
/**
* @author: BeginnersBook.com
* @description: Program to calculate area and circumference of circle
* with user interaction. User will be prompt to enter the radius and
* the result will be calculated based on the provided radius value.
*/
import java.util.Scanner;
class CircleDemo
{
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
System.out.print("Enter the radius: ");
/*We are storing the entered radius in double
* because a user can enter radius in decimals
*/
double radius = sc.nextDouble();
//Area = PI*radius*radius
double area = Math.PI * (radius * radius);
System.out.println("The area of circle is: " + area);
//Circumference = 2*PI*radius
double circumference= Math.PI * 2*radius;
System.out.println( "The circumference of the circle is:"+circumference) ;
}
}
Output:
/**
* @author: BeginnersBook.com
* @description: Program to calculate area and circumference of circle
* without user interaction. You need to specify the radius value in
* program itself.
*/
class CircleDemo2
{
public static void main(String args[])
{
int radius = 3;
double area = Math.PI * (radius * radius);
System.out.println("The area of circle is: " + area);
double circumference= Math.PI * 2*radius;
System.out.println( "The circumference of the circle is:"+circumference) ;
}
}
Output:
Here we will write two java programs to find the largest among three numbers.
1) Using if-else..if 2) Using nested If
else
System.out.println(num3+" is the largest Number");
}
}
Output:
If you are new to java, refer this Java Tutorial to start learning from basics
import java.util.Scanner;
class JavaExample
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}
Output 1:
Enter a character :
A
A is a Vowel
Output 2:
Enter a character :
P
P is a Consonant
Output 3:
Enter a character :
9
Input is not an alphabet
We are running a for loop from 1 to the smaller number and inside loop we are
dividing both the numbers with the loop counter “i” which ranges from 1 to the
smaller number value. If the value of i divides both numbers with no remainder
then we are assigning that value to the variable “gcd”. At the end of the loop,
the variable “gcd” will have the largest number that divides both the numbers
without remainder.
//Lets take two numbers 55 and 121 and find their GCD
int num1 = 55, num2 = 121, gcd = 1;
}
Output:
}
Output:
import java.util.Scanner;
public class GCDExample3 {
If you are new to java, refer this java programming tutorial to start learning
from basics.
int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}
}
Output:
import java.util.Scanner;
public class JavaExample {
int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}
}
Output:
We will write three java programs to find factorial of a number. 1) using for
loop 2) using while loop 3) finding factorial of a number entered by user.
Before going through the program, lets understand what is factorial: Factorial
of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n
import java.util.Scanner;
public class JavaExample {