Java Programs:-
Table_Program.java
package java_programs;
import java.util.Scanner;
public class Table_Program {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int no = 0;
System.out.println("Enter the number : ");
no = sc.nextInt();
for (int i = 0; i < 10; i++) {
System.out.println(no + " * " + (i + 1) + " = " + (no * (i + 1)));
}
}
}
o/p:-
Enter the number :
3
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Simple_Interest.java
package java_programs;
import java.util.Scanner;
public class Simple_Interest {
public static void main(String args[])
{
float p, r, t;
Scanner
s = new Scanner(System.in);
System.out.print("Enter the
Principal : ");
p
= s.nextFloat();
System.out.print("Enter the
Rate of interest : ");
r
= s.nextFloat();
System.out.print("Enter the
Time period : ");
t
= s.nextFloat();
float si;
si
= (r * t * p) / 100;
System.out.print("The Simple
Interest is : " + si);
}
}
o/p:-
Enter the Principal : 5000
Enter the Rate of interest : 2
Enter the Time period : 12
The Simple Interest is : 1200.0
MultiplicationTable.java
package java_programs;
import java.util.Scanner;
public class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out
.println("Enter an
integer to print it's multiplication table");
Scanner
in = new Scanner(System.in);
n
= in.nextInt();
System.out.println("Multiplication
table of " + n + " is : ");
for (c = 1; c <= 10;
c++)
System.out.println(n + "*" + c + " = " + (n * c));
}// main()
}
o/p:-
Enter an integer to print it's
multiplication table
2
Multiplication table of 2 is :
2*1 = 2
2*2 = 4
2*3 = 6
2*4 = 8
2*5 = 10
2*6 = 12
2*7 = 14
2*8 = 16
2*9 = 18
2*10 = 20
MilliSec.java
package java_programs;
import java.util.Date;
public class MilliSec {
public static void main(String[] args)
{
long millis = System.currentTimeMillis();
Date
date = new Date(millis);
System.out.println(date);
}
}
o/p:-
Sat Dec 08 15:04:17 IST 2018
GetMyIPAddress.java
package java_programs;
import
java.net.InetAddress;
public 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();
/*
* public String getHostAddress(): Returns the
IP address string in
* textual presentation.
*/
System.out.println("My IP Address
is:");
System.out.println(myIP.getHostAddress());
}
}
o/p:-
My IP Address is:
192.168.136.1
EMI.java
package java_programs;
public class EMI {
// Function to
calculate EMI
static float emi_calculator(float p, float r, float t) {
float emi;
r
= r / (12 * 100); // one month interest
t
= t * 12; //
one month period
emi
= (p * r * (float) Math.pow(1 + r, t))
/
(float) (Math.pow(1
+ r, t) - 1);
return (emi);
}
// Driver Program
static public void main(String[] args)
{
float principal, rate,
time, emi;
principal
= 10000;
rate
= 10;
time
= 2;
emi
= emi_calculator(principal, rate, time);
System.out.println("Monthly EMI
is = " + emi);
}
}
o/p:-
Monthly EMI is = 461.44965
Dicount.java
package java_programs;
import java.util.Scanner;
public class Dicount {
static void print(String line) {
System.out.println(line);
}
public static void main(String[] args)
{
int price;
int discount;
Scanner
sc = new Scanner(System.in);
print("Enter price
of the product :");
price
= sc.nextInt();
print("Enter
Discount of the product :");
discount
= sc.nextInt();
int finalPrice = (price
* discount) / 100;
print("Final price
is "
+ finalPrice);
}
}// class
o/p:-
Enter price of the product :
10000
Enter Discount of the product :
1000
Final price is 100000
Demo.java
package java_programs;
import java.util.Scanner;
//sum of first 10 natural num's:-
public class Demo {
public static void main(String[] args)
{
int num, count, total =
0;
System.out.println("Enter the value of n:");
//Scanner
is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt()
method reads integer entered by user
num = scan.nextInt();
//closing
scanner after use
scan.close();
for(count = 1; count
<= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}
o/p:-
Enter the value of n:
3
Sum of first 3 natural numbers is: 6
DateExample.java
package java_programs;
import java.util.Date;
public class DateExample {
public static void main(String[] args)
{
Date
date = new Date();
System.out.println(date);
}
}
o/p:-
Sat Dec 08 15:09:42 IST 2018
Arrays:-
ArrayListDemo.java
package Arrays;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args)
{
// create an empty
array list with an initial capacity
ArrayList<String>
arrlist = new ArrayList<String>(5);
// use add() method
to add values in the list
arrlist.add("G");
arrlist.add("E");
arrlist.add("F");
arrlist.add("M");
System.out.println("Size of list:
" +
arrlist.size());
// let us print all
the values available in list
for (String value :
arrlist) {
System.out.println("Value =
" +
value);
}
// retrieving the
index of element "E"
int retval =
arrlist.indexOf("E");
System.out.println("The element E
is at index " + retval);
}
}
o/p:-
Size of list: 4
Value = G
Value = E
Value = F
Value = M
The element E is at index 1
findPairClosestToZero.java
apackage Arrays;
import java.util.Arrays;
public class
findPairClosestToZero {
public static void main(String[] args)
{
int array[] = { 1, 30,
-5, 70, -8, 20, -40, 60 };
findPairWithMinSumBruteForce(array);
findPairWithMinSum(array);
}
public static void
findPairWithMinSumBruteForce(int arr[]) {
if (arr.length < 2)
return;
// Suppose 1st two
element has minimum sum
int minimumSum = arr[0]
+ arr[1];
int pair1stIndex = 0;
int pair2ndIndex = 1;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j <
arr.length; j++) {
int tempSum = arr[i] +
arr[j];
if (Math.abs(tempSum)
< Math.abs(minimumSum)) {
pair1stIndex
= i;
pair2ndIndex
= j;
minimumSum
= tempSum;
}
}
}
System.out
.println(" The pair
whose sum is closest to zero using brute force method: "
+
arr[pair1stIndex] + " " + arr[pair2ndIndex]);
}//
findPairWithMinSumBruteForce
public static void findPairWithMinSum(int arr[]) {
// Sort the array,
you can use any sorting algorithm to sort it
Arrays.sort(arr);
int sum = 0;
int minimumSum =
Integer.MAX_VALUE;
int n = arr.length;
if (n < 0)
return;
// left and right
index variables
int l = 0, r = n - 1;
// variables to
keep track of the left and right index pair for
// minimumSum
int minLeft = l,
minRight = n - 1;
while (l < r) {
sum
= arr[l] + arr[r];
/* If abs(sum)
is less than min sum, we need to update sum and pair */
if (Math.abs(sum)
< Math.abs(minimumSum)) {
minimumSum
= sum;
minLeft
= l;
minRight
= r;
}
if (sum < 0)
l++;
else
r--;
}
System.out.println(" The pair
whose sum is minimun : " + arr[minLeft]
+
"
" +
arr[minRight]);
}//
findPairWithMinSum
}
o/p:-
The pair whose sum is closest to zero
using brute force method: 1 -5
The pair whose sum is minimun : -5 1
Java Program to check Even or Odd number
Java program to swap two numbers
Swapping
using temporary or third variable:
Swapping
without temporary variable
Java Program to Calculate Area of Rectangle
Java program to calculate area of Square
Java program to calculate area of Triangle
Java
Program to calculate area and circumference of circle
Java program to generate random number
Java Program to display
first n or first 100 prime numbers
Java program to sum the elements of an array
Java Program to check Leap Year
Java Program to read integer value from the
Standard Input
Program to convert char to
String
Converting String to Char
Program to find sum of
first n (entered by user) natural numbers
Find
Largest Number in Array using Collections
Find
Smallest Number in Array using Collections
Smallest: 1
Smallest: 22
using loop
using recursion
Binary Search Example in Java using Arrays.binarySearch()
Element is found at index:
2
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
Scanner input = new Scanner(System.in);
num = input.nextInt();
/* If number is divisible by 2 then it's an even number
* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
Scanner input = new Scanner(System.in);
num = input.nextInt();
/* If number is divisible by 2 then it's an even number
* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output 1:
Enter an Integer number:
78
Entered number is even
78
Entered number is even
Java program to swap two numbers
●
Java program to swap two
numbers using a temporary variable.
●
To swap numbers without
using extra variable
Swapping
using temporary or third variable:
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}
}
class SwapNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}
}
Swap
numbers program class file.
Output
of program:
Swapping
without temporary variable
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int x, y;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}
}
class SwapNumbers
{
public static void main(String args[])
{
int x, y;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}
}
Java Program to Calculate Area of Rectangle
import java.util.Scanner;
class AreaOfRectangle {
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of Rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of Rectangle:");
double width = scanner.nextDouble();
//Area = length*width;
double area = length*width;
System.out.println("Area of Rectangle is:"+area);
}
}
class AreaOfRectangle {
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of Rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of Rectangle:");
double width = scanner.nextDouble();
//Area = length*width;
double area = length*width;
System.out.println("Area of Rectangle is:"+area);
}
}
Output:
Enter the length of Rectangle:
2
Enter the width of Rectangle:
8
Area of Rectangle is:16.0
2
Enter the width of Rectangle:
8
Area of Rectangle is:16.0
Java program to calculate area of Square
import java.util.Scanner;
class SquareAreaDemo {
public static void main (String[] args)
{
System.out.println("Enter Side of Square:");
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
double side = scanner.nextDouble();
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
class SquareAreaDemo {
public static void main (String[] args)
{
System.out.println("Enter Side of Square:");
//Capture the user's input
Scanner scanner = new Scanner(System.in);
//Storing the captured value in a variable
double side = scanner.nextDouble();
//Area of Square = side*side
double area = side*side;
System.out.println("Area of Square is: "+area);
}
}
Output:
Enter Side of Square:
2.5
Area of Square is: 6.25
2.5
Area of Square is: 6.25
Java program to calculate area of Triangle
import java.util.Scanner;
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the width of the Triangle:");
double base = scanner.nextDouble();
System.out.println("Enter the height of the Triangle:");
double height = scanner.nextDouble();
//Area = (width*height)/2
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the width of the Triangle:");
double base = scanner.nextDouble();
System.out.println("Enter the height of the Triangle:");
double height = scanner.nextDouble();
//Area = (width*height)/2
double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
}
Output:
Enter the width of the Triangle:
2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0
2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0
Java
Program to calculate area and circumference of circle
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) ;
}
}
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:
Enter the radius: 1
The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586
The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586
Java program to generate random number
In
the below program, we are using the nextInt() method of Random class to serve our
purpose.
import java.util.*;
class GenerateRandomNumber {
public static void main(String[] args) {
int counter;
Random rnum = new Random();
/* Below code would generate 5 random numbers
* between 0 and 200.
*/
System.out.println("Random Numbers:");
System.out.println("***************");
for (counter = 1; counter <= 5; counter++) {
System.out.println(rnum.nextInt(200));
}
}
}
class GenerateRandomNumber {
public static void main(String[] args) {
int counter;
Random rnum = new Random();
/* Below code would generate 5 random numbers
* between 0 and 200.
*/
System.out.println("Random Numbers:");
System.out.println("***************");
for (counter = 1; counter <= 5; counter++) {
System.out.println(rnum.nextInt(200));
}
}
}
Output:
Random Numbers:
***************
135
173
5
17
15
***************
135
173
5
17
15
Java Program to display
first n or first 100 prime numbers
Program to display
first n prime numbers
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);
}
for ( int i = 2 ; i <=n ; )
{
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++;
}
}
}
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);
}
for ( int i = 2 ; i <=n ; )
{
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:
Enter the value of n:
15
First 15 prime numbers are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
15
First 15 prime numbers are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
Java program to sum the elements of an array
Program:
User enters the array’s elements
/**
* @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 SumDemo{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
int sum = 0;
System.out.println("Enter the elements:");
for (int i=0; i<10; i++)
{
array[i] = scanner.nextInt();
}
for( int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
}
* @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 SumDemo{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
int sum = 0;
System.out.println("Enter the elements:");
for (int i=0; i<10; i++)
{
array[i] = scanner.nextInt();
}
for( int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
}
Output:
Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55
Java Program to check Leap Year
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.");
}
}
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:
Enter any Year:
2001
2001 is not a Leap Year.
2001
2001 is not a Leap Year.
Java Program to read integer value from the
Standard Input
We
have imported the package java.util.Scanner to use the Scanner.
In order to read the input provided by user, we first create the object of
Scanner by passing System.in as parameter. Then we
are using nextInt() method of Scanner class to read the integer.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
/* This reads the input provided by user
* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
scan.close();
// Displaying the number
System.out.println("The number entered by user: "+num);
}
}
public class Demo {
public static void main(String[] args) {
/* This reads the input provided by user
* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
scan.close();
// Displaying the number
System.out.println("The number entered by user: "+num);
}
}
Output:
Enter any number: 101
The number entered by user: 101
The number entered by user: 101
Program to convert char to
String
We have following two
ways for char to String conversion.
Method 1: Using
toString() method
class CharToStringDemo
{
public static void main(String args[])
{
// Method 1: Using toString() method
char ch = 'a';
String str = Character.toString(ch);
System.out.println("String is: "+str);
// Method 2: Using valueOf() method
String str2 = String.valueOf(ch);
System.out.println("String is: "+str2);
}
}
{
public static void main(String args[])
{
// Method 1: Using toString() method
char ch = 'a';
String str = Character.toString(ch);
System.out.println("String is: "+str);
// Method 2: Using valueOf() method
String str2 = String.valueOf(ch);
System.out.println("String is: "+str2);
}
}
Output:
String is: a
String is: a
String is: a
Converting String to Char
class StringToCharDemo
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch);
}
}
}
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch);
}
}
}
Output:
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o
Program to find sum of
first n (entered by user) natural numbers
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num, count, total = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}
public class Demo {
public static void main(String[] args) {
int num, count, total = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}
Output:
Enter the value of n:
20
Sum of first 20 natural numbers is: 210
20
Sum of first 20 natural numbers is: 210
Find
Largest Number in Array using Collections
1.
import java.util.*;
2.
public class
LargestInArrayExample2{
3.
public static int getLargest(Integer[] a, int total){
4.
List<Integer> list=Arrays.asList(a);
5.
Collections.sort(list);
6.
int element=list.get(total-1);
7.
return element;
8.
}
9.
public static void main(String args[]){
10. Integer
a[]={1,2,5,6,3,2};
11. Integer
b[]={44,66,99,77,33,22,55};
12. System.out.println("Largest: "+getLargest(a,6));
13. System.out.println("Largest: "+getLargest(b,7));
14. }}
Largest:
6
Largest: 99
Largest: 99
Find
Smallest Number in Array using Collections
1. import java.util.*;
2. public class
SmallestInArrayExample2{
3. public static
int getSmallest(Integer[] a, int total){
4. List<Integer>
list=Arrays.asList(a);
5. Collections.sort(list);
6. int element=list.get(0);
7. return element;
8. }
9. public static
void main(String args[]){
10. Integer a[]={1,2,5,6,3,2};
11. Integer b[]={44,66,99,77,33,22,55};
12. System.out.println("Smallest: "+getSmallest(a,6));
13. System.out.println("Smallest: "+getSmallest(b,7));
14. }}
Smallest: 22
Q)Palindrome number
Palindrome number in java: A palindrome
number is a number that is
same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the
palindrome numbers. It can also be a string like LOL, MADAM etc.
1.
import
java.util.*;
2.
class
PalindromeExample2
3.
{
4.
public static void main(String args[])
5.
{
6.
String original, reverse = ""; // Objects
of String class
7.
Scanner in = new Scanner(System.in);
8.
System.out.println("Enter a string/number to check if it is a
palindrome");
9.
original = in.nextLine();
10.
int length = original.length();
11.
for ( int i = length - 1;
i >= 0; i-- )
12.
reverse = reverse +
original.charAt(i);
13.
if (original.equals(reverse))
14.
System.out.println("Entered string/number is a palindrome.");
15.
else
16.
System.out.println("Entered string/number isn't a palindrome.");
17.
}
18.
}
Q)Factorial
Factorial Program in Java:
Factorial of n is the product of all
positive descending integers. Factorial of n is denoted by n!. For example:
1.
4! = 4*3*2*1 = 24
2.
5! = 5*4*3*2*1 = 120
The
factorial is normally used in Combinations and Permutations (mathematics).
There
are many ways to write the factorial program in java language.
●
Factorial Program using loop
●
Factorial Program using recursion
using loop
1.
class FactorialExample{
2.
public static void main(String args[]){
3.
int i,fact=1;
4.
int number=5;//It is the number to calculate factorial
5.
for(i=1;i<=number;i++){
6.
fact=fact*i;
7.
}
8.
System.out.println("Factorial
of "+number+" is: "+fact);
9.
}
10. }
using recursion
1.
class FactorialExample2{
2.
static int
factorial(int n){
3.
if (n == 0)
4.
return 1;
5.
else
6.
return(n * factorial(n-1));
7.
}
8.
public static void main(String args[]){
9.
int i,fact=1;
10. int
number=4;//It is
the number to calculate factorial
11. fact = factorial(number);
12. System.out.println("Factorial
of "+number+" is: "+fact);
13. }
14. }
Q)BubbleSort
We can create a java program to sort array elements using
bubble sort. Bubble sort algorithm is known as the simplest sorting algorithm.
In bubble sort algorithm, array is traversed from first
element to last element. Here, current element is compared with the next
element. If current element is greater than the next element, it is swapped.
1.
public class
BubbleSortExample {
2.
static void
bubbleSort(int[] arr) {
3.
int n = arr.length;
4.
int temp = 0;
5.
for(int i=0; i < n; i++){
6.
for(int j=1; j < (n-i); j++){
7.
if(arr[j-1]
> arr[j]){
8.
//swap elements
9.
temp = arr[j-1];
10. arr[j-1] = arr[j];
11. arr[j] =
temp;
12. }
13.
14. }
15. }
16.
17. }
18. public static void
main(String[] args) {
19. int
arr[] ={3,60,35,2,45,320,5};
20.
21. System.out.println("Array Before Bubble Sort");
22. for(int i=0; i <
arr.length; i++){
23. System.out.print(arr[i]
+ " ");
24. }
25. System.out.println();
26.
27. bubbleSort(arr);//sorting array elements using bubble sort
28.
29. System.out.println("Array After Bubble Sort");
30. for(int i=0; i <
arr.length; i++){
31. System.out.print(arr[i]
+ " ");
32. }
33.
34. }
35. }
Output:
Array
Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
Linear search is used to search a key element from
multiple elements. Linear search is less used today because it is slower than
binary search and hashing.
You can also use a method where array is not predefined.
Here, user has to put the elements as input and select one element to check its
location.
1.
import java.util.Scanner;
2.
3.
class LinearSearchExample2
4.
{
5.
public static void main(String args[])
6.
{
7.
int c, n, search, array[];
8.
9.
Scanner in = new Scanner(System.in);
10. System.out.println("Enter
number of elements");
11. n = in.nextInt();
12. array = new
int[n];
13.
14. System.out.println("Enter
those " + n + " elements");
15.
16. for (c =
0; c < n; c++)
17. array[c] = in.nextInt();
18.
19. System.out.println("Enter
value to find");
20. search = in.nextInt();
21.
22. for (c =
0; c < n; c++)
23. {
24. if
(array[c] == search) /* Searching element is present */
25. {
26. System.out.println(search + " is present at location " + (c + 1) + ".");
27. break;
28. }
29. }
30. if (c ==
n) /*
Element to search isn't present */
31. System.out.println(search + " isn't present in array.");
32. }
33. }
34.
Binary search is used to search a key element from
multiple elements. Binary search is faster than linear search.
In case of binary search, array elements must be in
ascending order. If you have unsorted array, you can sort the array using Arrays.sort(arr) method.
Let's see an example of binary search in java.
1.
class BinarySearchExample{
2.
public static void binarySearch(int
arr[], int first, int
last, int key){
3.
int mid = (first + last)/2;
4.
while( first <= last ){
5.
if ( arr[mid] < key ){
6.
first = mid
+ 1;
7.
}else if (
arr[mid] == key ){
8.
System.out.println("Element is found at index: " + mid);
9.
break;
10. }else{
11. last = mid - 1;
12. }
13. mid = (first + last)/2;
14. }
15. if (
first > last ){
16. System.out.println("Element is not found!");
17. }
18. }
19. public static void
main(String args[]){
20. int
arr[] = {10,20,30,40,50};
21. int
key = 30;
22. int
last=arr.length-1;
23. binarySearch(arr,0,last,key);
24. }
25. }
Binary Search Example in Java using Arrays.binarySearch()
1.
import java.util.Arrays;
2.
class BinarySearchExample2{
3.
public static void main(String args[]){
4.
int arr[] = {10,20,30,40,50};
5.
int key = 30;
6.
int result = Arrays.binarySearch(arr,key);
7.
if (result < 0)
8.
System.out.println("Element is not found!");
9.
else
10. System.out.println("Element is found at index: "+result);
11. }
12. }
No comments:
Post a Comment