# Write a program in java to enter two numbers and check if they are twin prime numbers or not.

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19), (29, 31) ... etc.

In this program isPrime(int n) will return true if the number is prime and false if it is not prime. This method is called in the main() method which checks the numbers are prime or not and also the difference between two prime numbers is 2. And if it is then it called Twin prime number.

Solution
import java.io.*;
// Program to check twin prime
public class TwinPrimeNumber
{

public static boolean isPrime(int n)
{
// boolean value will return
boolean f = true;

for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
f = false;
break;
}
}

return f;
}

// main method begins
public static void main(String args[]) throws IOException
{

int number1, number2;
// InputStreamReader object
InputStreamReader in = new InputStreamReader(System.in);
// BufferedReader object
BufferedReader br = new BufferedReader(in);
System.out.print("Enter first number: ");
// First number
number1 = Integer.parseInt(br.readLine());
System.out.print("Enter second number: ");
// Second number
number2 = Integer.parseInt(br.readLine());

// Checking both the number is prime and the difference between two is 2
if (isPrime(number1) == true && isPrime(number2) == true && Math.abs(number2 - number1) == 2) {
System.out.println("Twin prime number");
} else {
System.out.println("Not twin prime numbers");
}

} // end method main
} // end class

Output
Enter first number: 11
Enter second number: 13
Twin prime number

Enter first number: 9
Enter second number: 11
Not twin prime numbers

In the above program, a method public static boolean isPrime(int n) is used to check prime numbers. This method return a boolean value. If the number is prime then it will send true otherwise false. In main() method isPrime called two times to check true or false.

### //Twin prime number without method

import java.util.*;
public class TwinPrime
{
public static void main(String args[])
{
int n1, n2, i, f1,f2;
f1=f2=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter First number:");
n1=sc.nextInt();
System.out.println("Enter Second number:");
n2=sc.nextInt();
for(i=2; i<n1; i++)
{
if(n1%i==0)
{
f1=0;
break;
}
}
for(i=2; i<n2; i++)
{
if(n2%i==0)
{
f2=0;
break;
}
}
if(f1==1 && f2==1 && Math.abs(n1-n2)==2)
{
System.out.println("Twin Prime Number");
}
else
{
System.out.println("Not a Twin Prime Number");
}
}
}

## Java program for Brun’s Constant and Twin Prime number

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19) ... etc. The sum of reciprocals of the twin primes up to a limit, converges to sum known as Brun’s Constant. Example :
Say for Inputted number 13 and its twin primes are (3, 5), (5, 7), (11, 13) and its sum of reciprocals is
(1/3 + 1/5) + (1/5 + 1/7) + (1/11 + 1/13) =  1.044022644022644
Write a program to create Primes which include methods:
Booleans isPrime(int n) Checks whether n is prime or not
Void twinPrimesBrunConstant – Which checks twinPrime and also calculate brun’s constant.

Solution
import java.util.Scanner;
/**
* class BrunsConstant
* @author (InspireSkills)
* Input 2 nos. and check whether they make up Brun’s Constant or not, Brun’s Constant is sum of
* reciprocal of Twin Prime Nos. e.g (1/3) + (1/5) is a Brun’s Constant
*/
public class BrunsConstant
{
static double sum=0.0;
static int i, f;
// Check the number prime or not
public static boolean isPrime(int n)
{
f=1;
for (i = 2 ; i < n ; i++)
{
if(n % i == 0)
{
f=0;
break;
}
}
if(f == 1)
return true;
else
return false;

}

// Here checked the two number twin prime or not
// and also calculate brun's constant.
public static void twinPrimesBrunConstant(int number )
{
System.out.println("Twin prime");
System.out.println("==========");
for (int i = 2; i < number ; i++)
{
int num1 = i;
int num2 = i + 2;
if (isPrime(num1) && isPrime(num2))
{
System.out.println(num1 + " " + num2);
sum = sum + (double)1/num1 + (double)1/num2;
}
}
}

public static void main(String[] args)
{
int no;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
no = scanner.nextInt();
twinPrimesBrunConstant(no);
System.out.println("Brun's Constant:" + sum);
}
}

# Advanced Java : Learn Java Advanced Features  Output
Enter a number: 13
Twin prime
==========
3 5
5 7
11 13
Brun's Constant:1.044022644022644
Enter a number: 50
Twin prime
==========
3 5
5 7
11 13
17 19
29 31
41 43
Brun's Constant:1.2698646333745234

More Program

## Palindrome Number

A Palindrome number or word which will read the same from either side, backward of forward.
For example 202 or madam read same from both forward and backward.

### Java Program for Palindrome Number

import java.io.*;
public class PalindromeNumber
{
public static void main(String args[])throws IOException
{
int n, rev, a ,m;
rev=0;
InputStreamReader ab = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ab);
System.out.print("Enter number to Palindrome:");
n = Integer.parseInt(br.readLine());
m = n;
// Reversing the number
while(n != 0)
{
a = n % 10;
rev = rev * 10 + a;
n = n / 10;
}
System.out.println("Reverse Number:" + rev);
// Checking Palindrome or not
if(m == rev)
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not Palindrome");
}
}
}

Output
Enter number to Palindrome:202
Reverse Number:202
Palindrome

Enter number to Palindrome:221
Reverse Number:122
Not Palindrome

### Java Program for Palindrome Word or String

For String Plaindrome
import java.util.Scanner;
/**
* class Palindrome Word here.
* Khurshid Md Anwar (InspireSkills)
*/
public class PalindromeWord
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String st; // Variable for Word taken
System.out.println("Enter a string or word ");
st=sc.nextLine();
int i,l;
char ch;
String revWord="";  // for reverse Word
l = st.length();    // Finding the length of word
for(i=0;i<l;i++)
{
ch = st.charAt(i);
revWord = ch + revWord;
}
// Checking Plaindrome or not
if(st.equals(revWord))
{
System.out.println("Palindrome Word");
}
else
{
System.out.println("Not a Palindrome Word");
}
}
}

Output
Enter a string or word
madam
Palindrome Word
Enter a string or word
hello

Not a Palindrome Word

Visit for More Program

## Addition of two matrices in Java

### Java matrix addition

In this program, we are performing the addition of two matrices. Here we define two matrix one is first[][]
and another is second[][] and another one defines for summation of two entered matrices. First, we take row and column and then enter the values in two matrices. After then we sum the two matrices.

import java.util.Scanner;
/**
* Java program for
* Addition Of Two Matrices
*/
public class AdditionOfTwoMatrices
{
public static void main(String args[])
{
int m, n, i, j;        // Local Variables
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");
m = sc.nextInt();
n  = sc.nextInt();
// Array definition
int first[][] = new int[m][n];       // First Array
int second[][] = new int[m][n]; // Second Array
int add[][] = new int[m][n];       // sum of two matrix array

System.out.println("Enter the elements of first matrix");

for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
first[i][j] = sc.nextInt();
}
}

System.out.println("Enter the elements of second matrix");

for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
second[i][j] = sc.nextInt();
}
}

// Display of First Matrix
System.out.println("Output of First Matrix");
for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(first[i][j] + " ");
}
System.out.println();
}

// Display of Second Matrix
System.out.println("Output of Second Matrix");
for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(second[i][j] + " ");
}
System.out.println();
}

// Addition of matrix
for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
add[i][j] = first[i][j] + second[i][j];
}
}
// Display of Matrix addition
System.out.println("Addition of Two Matrix");

for (  i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(add[i][j]+"\t");
}
System.out.println();
}
}
}

Output

Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
7
8
9
4
Enter the elements of second matrix
5
6
1
2
Output of First Matrix
7 8
9 4
Output of Second Matrix
5 6
1 2
Addition of Two Matrix
12 14
10 6

## Array in Java

### What is an Array?

The contiguous memory location is called Array. Actually, an array is a plural, so that we can simply read the variable and recognize that it is a collection of data. It is an object in Java that holds a fixed number of values of a single data type. Java Array is a data structure in java that can hold one or more values in a single variable. An array is declaring like a variable except that we are attaching the square brackets [], which can be used in two parts, either before the name of the variable or after the name of the variable.

#### Why do we need an array?

Suppose you want to store the name of 500 employees, so we need to define 500 variables but this could be a very big problem so we need a better solution for defining 500 names for employees, that is why need an array.

Java array index starts at 0.

#### Write down some points on Array.

• The array is a homogeneous data structure that stores elements of a similar type.
• All the elements of an array share the same name.
• Each element of an array treated separately and store in a different memory location.
• Each value stored, in an array, is known as an element and all elements are indexed. The first element added, by default, gets 0 indexes. That is, the 6th element added gets an index number of 5.
• Java checks the boundary array. If the index goes beyond, an exception will generate.
• Elements of an array can be retrieved by their index number.
• Java arrays are objects. With methods, the array elements can be manipulated.
• Memory allocation in Java arrays are dynamically by using the new operator.
• Arrays can be multidimensional.
• Once the size of an array defined, it cannot grow it or shrink it at run time.

#### Declaring an Array

Int number [];
The above statement just declares an array object, but it doesn’t have any elements. An array is a null object. It must be instantiated using the following statement:
Number=new int ;
In Java, every object is instantiated using the ‘new’ keyword.

#### Initialization of one dimensional array

Int arr[] = {5, 6, 1, 9, 3};
Array arr[] contains five elements in it.

#### Types of Array in java

There are two types of array.

1. Single Dimensional Array: Int arr[]=new int;
2. Multidimensional Array: Int arr[][]=new int;

#### Java Array Literals

Sometimes we need predefine values for the array, so Java gives us a better solution for that, so we can use an array literal. Here is how we cab defines an array literal:
int[] number = {5, 4, 8, 9, 12, 6};
or
int number[] = {1,2,3,4,5,7,8};
Here we don’t need a new operator for defining the array.
So here values which are store inside the curly brackets is called an array literal.
For defining String array we can do so as follows
String name[] = {“Alam”, “Binny”, Rakesh”, “Salim”, “Sachin”};

Some examples:

// Simple Array print
import java.io.*;
public class SimpleArrayPrint
{
public static void main(String args[])throws IOException
{
InputStreamReader ab=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader (ab);
int n[]=new int;
int i;
System.out.println ("Enter Five numbers:");
for (i=0;i<5;i++)
{
n[i]=Integer.parseInt(br.readLine());
}
System.out.println ("Out Put");
for (i=0;i<5;i++)
{
System.out.print (n[i]+" ");
}
}
}

Example
// Array Summation print
import java.io.*;
public class SumArrayPrint
{
public static void main(String args[])throws IOException
{
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
int n[]=new int;
int i,s=0;
System.out.println("Enter ten numbers:");
for(i=0;i<10;i++)
{
n[i]=Integer.parseInt(br.readLine());
}
System.out.println("Out Put");
for(i=0;i<10;i++)
{
s=s+n[i];
}
System.out.println("Sum="+s);
}
}

# Advanced Java : Learn Java Advanced Features  Output
Enter ten numbers:
2
3
65
66
5
8
12
4
54
5
Out Put
Sum=224

Example

#### // Array program of Odd and Even

import java.io.*;
public class ArrayOddEven
{
public static void main(String args[])throws IOException
{
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
int a[]=new int;
int ev[]=new int;
int od[]=new int;
int i,j,k;
j=k=0;
System.out.println("Enter Five elements:");
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<10;i++)
{
if(a[i]%2==0)
{
ev[j]=a[i];
j++;
}
else
{
od[k]=a[i];
k++;
}
}
System.out.println("Even Array");
for(i=0;i<j;i++)
{
System.out.println(ev[i]);
}
System.out.println("Odd Array");
for(i=0;i<k;i++)
{
System.out.println(od[i]);
}
}
}
Output
Enter Five elements:
4
5
6
3
2
1
7
8
9
2
Even Array
4 6 2 8 2
Odd Array
5 3 1 7 9

#### // Double Dimention Array Example

import java.io.*;
class DBLArray
{
public static void main(String arg[])throws IOException
{
int n[][]=new int;
int i,j;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
System.out.println("Enter Data :");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("OutPut Data");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(n[i][j]+" ");
}
System.out.println("");
}
}
}

#### Java Array Exception example

public class ArrayException
{
public static void main(String args[])
{
int n[]={5,6,7,8,9};
int i,m;
try
{
m=n;
System.out.println(m);
}
catch(Exception e)
{
System.out.println("O no not again");
}
finally
{
System.out.println("Must execute");
}
System.out.println("Thank you");
}
}

Some more program

### Binary Search in Java

Learn Java
Become An Awesome Java Professional ## ICSE 2016 and ISC 2016 Computer Application Q & A

Q. What is a class variable?
Ans: Static keyword in Instance variables is called a class variable. For every object there is just one copy of the variable made.
Ex.
class Summation
{
static  int a;
static  int b;

}

Q. What is significance of import java.io.* in your program?
Ans: The line imports all the classes of the java.io package into the program.

Q. State the two kinds of data types.
Ans: The two kinds of data types in Java are primitive and reference data types.

Q. Define impure function.
Ans: Impure Function: A function that brings about a change in the argument that it receives. Its arguments will always be reference types. It may or may not return value. In other words, an impure function brings about a change in the state of the function. This change in state is called the side effect of calling an impure function.
Example:
Static void count(Number num)
{
num.counter=num.counter+1;
}  Q. What are comments? Name the different types.
Ans: Comments are statements which enhances the readability and understanding of the program. They are not part of the program.
The different types are: single line (//….), multiple line (/* … */) and documenting comment (/**….*/).

Q. Define Encapsulation.
Ans: The wrapping of data and function together into a single unit is called Encapsulation.

Q. Name any three OOP’s principles
Ans: Inheritance,  Polymorphism and Encapsulation

Q. Define Object with example.
Ans:  Object: An instance of a class called Object. Table is an instance of class Furniture.
Class: Blue print of an object is called Class. Example, mango, apple and orange are members of the class fruit.

Q. What is wrapper class? Give example.
A wrapper class is a class which wraps a primitive data type. Example Double, Float, Integer

Q. What is meant by private visibility of a method?
Ans:  The visibility of private method restricted to class itself. It is not visible to anywhere outsite the class.

Q. What is a variable?
Ans: A variable is a named memory location whose value can change. Example int a,b;

Q. What is the use of return keyword?
Ans: A return keyword is used to return any value from a function. It denotes the end of a function.

Q. What is call by value?
Ans: In call by value arguments are passed by the value, which means that a copy of the arguments is passed to the method can make changes to the value of this copy but can not change the values of the original variables in the calling method.

Q. What is meant by an infinite loop? Give an example.
Ans: An infinite loop is a loop whose test condition is always true. This type of loop never ends by itself. For example:
for(i=1;i>0;i++)
{
System.out.println(“Hello”);
}

Q. State any two objectives of using Arrays.
Ans:  1. Use hold elements in contiguous memory location. 2. Arrays are used to group storage locations.

Become An Awesome Java Professional ## Java program matrix diagonal sum without mid value repetition

import java.util.*;
/**
*
* Double dimension array diagonal addition
* Each diagonal sum without repetition of mid value
* InspireSkills : Khurshid Md Anwar
*
*/
public class MatrixAddWithoutRepetingMidValue
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,j,s1,s2,r,c,a;
System.out.println("Enter Row or Col");
r=sc.nextInt();
int n[][]=new int[r][r];
s1=s2=0;
System.out.println("Enter values into Matrix");
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
n[i][j] = sc.nextInt();
}

}
System.out.println("Print Matrix");
for(i=0; i<r; i++)
{
for(j=0; j<r; j++)
{
System.out.print(n[i][j] + " ");
}
System.out.println();
}
for(i=0; i<r; i++)
{
s1 = s1 + n[i][i];
}
c = r-1;
for(i=0;i<r;i++)
{
s2 = s2 + n[i][c];
c--;
}
// Excluding the repeating mid value
s2 = s2 - n[r/2][r/2];
System.out.println("Mid Value="+n[r/2][r/2]);
System.out.println("First Diagonal sum=" + s1);
System.out.println("Second Diagonal sum=" + s2);
System.out.println("Sum of Two diagonal without repeating value is "+ (s1+s2));
}
}

Output
Enter Row or Col
3
Enter values into Matrix
9
8
7
6
5
4
3
2
1
Print Matrix
9 8 7
6 5 4
3 2 1
Mid Value=5
First Diagonal sum=15
Second Diagonal sum=10
Sum of Two diagonal without repeating value is 25

Few more program