# 20 Best Programming Practice in Java

## Introduction to Best Programming Practice in Java

Java is a fun language. But to know java better we need to practice java coding. Programming practice in java makes one more proficient.

From the basic level to advanced level almost all organizations ask java programming questions during the interview. Entry criteria for almost all hackathons is to know the java coding.

In this post I am trying to provide you a set of coding that you must know. This will also help you to clear java coding interview questions .

### How to take user Input in java

Most of the time when we start using little advanced coding we use to take values from the user.
in C it is simple.we can write

getchar(); and gets(); are like scanf()

1) getchar(); takes one symbol. IF i want 2 symbol, I should write getchar(); getchar();
2) gets(); takes a full string with spaces. For example: If I write “Ask QTP”. Scanf takes “Ask QTP”
3) scanf(); takes symbols before space. For example: If I write “Ask QTP”. Scanf takes only “ASK”

But in java what could be a solution??
In java, there are two ways to take input.

``````BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
}
catch (IOException ioe) {
System.exit(1);
}*/
``````

You can ask for the user input

``````
// prompt the user to enter their name
``````

The code will look like

``````
import java.io.*;
public static void main (String[] args)
{
// prompt the user to enter their name
// open up standard input
try
{
}
catch (IOException ioe)
{
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadLine class
``````

Code for dialogue box:

``````
import javax.swing.JOptionPane;
{
public static void main (String[] args)
{
// prompt the user to enter their name String
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadLine class
``````

### How to Determine A Vulgar Fraction In Java

#### A vulgar fraction:

A vulgar fraction is a fraction in which denominator is an integer other than 10,100,1000…..
like -3/4,4/5,5/7 etc.

### Logic to write a vulgar fraction determination

Well, the logic is…

• Take the fraction in x/y form from the user
• It will come as a string
• Split the String with “/”
• Find out the second number
• Check if that is any multiple of 10.While we modulo operation with 10, it should not give any remainder
• Determine the vulgar fraction.

### Lets code

• Take the fraction in x/y form from user—take the input the code is here
• It will come as a string
• Split the String with “/”
• Find out the second number
• Check if that is any multiple of 10.While we modulo operation with 10, it should not give any remainder
• Determine the vulgar fraction.

### The code:

``````public class Vulger {
public Vulger() {
int deno;
// this is where you take user input
String fraction = "3/1000";
String[] temp = null;
//Split it with "/"
temp = fraction.split("/");
//Change it integer from String
deno = Integer.parseInt(temp[1]);
//Here the main logic comes checking if it is divisible by 10 and making
// sure denominator is only  a subset of  multiplier of 10 like
// 10,100,1000.... not 20,30,40...etc
if (((deno % 10) == 0) && (checkval(deno))) {
System.out.println(fraction + " is not a vulger fraction");
} else
System.out.println(fraction + " is a vulger fraction");
}
public static void main(String[] Args) {
new Vulger();
}``````

#### Vulgar Fraction

``````
private boolean checkval(int deno) {
//making sure denominator is only a subset of multiplier of
//10 like 10,100,1000.... not 20,30,40...etc
int res = 1;
do {
res = deno % 10;
deno = deno / 10;
}
while (deno >= 1);
if (res == 1) {
return true;
} else
return false;
}
}
``````

### How to Create Singleton, Doubleton (n ton) Class in Java?

Here let me explain why this n-ton class is necessary and how to implement the same.

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

There is criticism of the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.-As per Wiki

Now let me tell you what is the necessity of a singleton class–

• ###### Window managers
• Print spoolers
• Filesystems etc

So if you are working on the above written areas, singleton is necessary. Again say in an application you want to restrict user to create an object for twice. Then doubleton class is necessary. This way you can create n-ton class as per your requirement.

```public class SingletonDemo {
private static volatile SingletonDemo instance = null;```

private SingletonDemo() { }

public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo .class){
if (instance == null) {
instance = new SingletonDemo ();
}
}
}
return instance;
}
}

This is as per wiki
But this approach only holds good for singleton class.If you need to implement doubleton then this code is invalid. I am going to show you some other approach by which you can create  single-double or n ton class in a single class…

```class SingletonClass
{
private static int count=0;
SingletonClass() throws Exception
{
if(count==0)
{
System.out.println("Object Created.");
count++;
}
else throw new Exception("Singleton Class cannot have more than one Object.");
}
public static void main(String args[])
{
try{
SingletonClass s1=new SingletonClass();
SingletonClass s2=new SingletonClass();
SingletonClass s3=new SingletonClass();
}catch(Exception e)
{
System.out.println("Exception: "+e.getMessage());
}
}
}```

In this approach if you want to create n-ton class then

```if(count==0)
{
System.out.println("Object Created.");
count++;
}```

This is code is the driver.
for singleton-count will be 0 but for double tone the code will be

```if(count<=1)
{
System.out.println("Object Created.");
count++;
}```

and so on …
so for an n-ton class, the code will be–

```if(count<=n)
{
System.out.println("Object Created.");
count++;
}```

### How To Check Credit Card Or Debit Card Number In Java?

The following checksum formula is widely used by banks and credit card companies to validate legal account numbers:
d0 + f(d1) + d2 + f(d3) + d4 + f(d5) + d6 + … = 0 (mod 10) The di are the decimal digits of the account number and f(d) is the sum of the decimal digits of 2d (for example, f(7) = 5 because 2 * 7 = 14 and 1 + 4 = 5).

For example, 17327 is valid because 1 + 5 + 3 + 4 + 7 = 20, which is a multiple of 10. Implement the function f and write a program to take a 10-digit integer as a command-line argument and print a valid 11-digit number with the given integer as its first
10 digits and the checksum as the last digit.

``````public class AccountNumberchecker {
/**
* @param args
*/
public static void main(String[] args) {
String acc_no="17327";
//take the card number
int sum=0;
//initialize sum as zero
int a=acc_no.length();
//check out the length
for(int j=0;j<a;j++ )
{
if(j%2!=0)
// this is just to build the logic as only alternate postion's element will be processed f(d1),f(d3)....
{
sum=sum calculatesum((acc_no.charAt(j)));
}
else
{
//alternate numbers will be added as it is
sum=sum (int)(acc_no.charAt(j)-48);
}
}
//Checking the card status
System.out.println("The card no is " Checksum(sum));
}
private static int calculatesum(char a)
{
int b1=a-48;
//Convert the character to integer
int b=b1*2;
//Multiplied by 2 as per logic
if (b>10)
{
//if greater than zero then add two digit
return implfunc(b);
}
else
{
//if it is not greater than zero then return as it is
return b;
}
}

private static int implfunc(int b) {
//Add the two digits of a two digit number
return ((b%10)+ (b/10));
}
private static String Checksum(int a)
{
//As per logic the mod operator will be implemented on
//the summation
if (a%10==0)
return "Valid";
else
return "invalid";

}

}``````

### How To Permute String in Java Using Recursion?

 Permute String in Java Using Recursion

#### Permute String in Java Using Recursion:

In this area, My objective is to show the permutation of String in different manner using recursion.
This is helpful while designing testcases and creating testdata for the same. By using this technique we can create several testdata.

``````
public static void main(String[] args) {
System.out.println(StringPermutation.getPermutation("abcd"));
}``````

Now let us write the original code or the function that will go recursively…

``````
public static List<String> getPermutation(String input)
{
List<String> collection = null;
if (input.length() == 1) {
collection = new ArrayList<String>();
return collection;
} else {
collection = getPermutation(input.substring(1));
Character first = input.charAt(0);
List<String> result = new ArrayList<String>();
for (String str : collection) {
for (int i = 0; i < str.length(); i++ ) {
String item = str.substring(0, i) + first
+ str.substring(i);
}
String item = str.concat(first.toString());
}
return result;
}
``````

The program goes like:

``````
import java.util.ArrayList;
import java.util.List;
public class StringPermutation {
public static List<String> getPermutation(String input) {
List<String> collection = null;
if (input.length() == 1) {
collection = new ArrayList<String>();
return collection;
} else {
collection = getPermutation(input.substring(1));
Character first = input.charAt(0);
List<String> result = new ArrayList<String>();
for (String str : collection) {
for (int i = 0; i < str.length(); i++ ) {
String item = str.substring(0, i) +first
+str.substring(i);
}
String item = str.concat(first.toString());
}
return result;
}
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(StringPermutation.getPermutation("abcd"));
}
}
``````

The output will be..

#### How To Test A Valid Combination For Right Angle Triangle Using Java

Right angle triangle is those triangle whose One angle is 90 degree. Again one more important property  is Addition of squire of  two sides is equal to the squire of of the third side.

As per the picture either <ACB,<CAB,<ABC should be 90 degree here <ACB is 90 degree
.
The second property is AC*AC+BC*BC=AB*AB
So if you get length of 3 sides then we can check if that is a right angle triangle.

here is a simple java class to test if the given side can form a right angle triangle.

#### Pythagorean theorem

A visual proof of the Pythagorean theorem

Since the fourth century AD, Pythagoras has commonly been given credit for discovering the Pythagorean theorem, a theorem in geometry that states that in a right-angled triangle the area of the square on the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares of the other two sides—that is, $a^2 + b^2 = c^2$.

While the theorem that now bears his name was known and previously utilized by the Babylonians and Indians, he, or his students, are often said to have constructed the first proof.

It must, however, be stressed that the way in which the Babylonians handled Pythagorean numbers implies that they knew that the principle was generally applicable, and knew some kind of proof, which has not yet been found in the (still largely unpublished) cuneiform sources.

Because of the secretive nature of his school and the custom of its students to attribute everything to their teacher, there is no evidence that Pythagoras himself worked on or proved this theorem.

For that matter, there is no evidence that he worked on any mathematical or meta-mathematical problems. Some attribute it as a carefully constructed myth by followers of Plato over two centuries after the death of Pythagoras, mainly to bolster the case for Platonic meta-physics, which resonate well with the ideas they attributed to Pythagoras.

This attribution has stuck down the centuries up to modern times.The earliest known mention of Pythagoras’s name in connection with the theorem occurred five centuries after his death, in the writings of Cicero and Plutarch.–As per Wiki

``````public class TrangleTest {
/**
* @param args
*/
public static void main(String[] args) {
// take your inputyou can use some other way to get user input also
int a=3;
int b=4;
int c=5;
System.out.print(checkTrangle(a,b,c));

}
public static String checkTrangle(int a,int b,int c)
{
if((squ(a)==squ(b)+ squ(c))||(squ(b)==squ(a)+ squ(c))||(squ(c)==squ(a) +squ(b)))
{
//checking if AC*AC+BC*BC=AB*AB in terms of length
return "This can be a valid right angle triangle";
}
else
{
return "This can not be a valid right angle triangle";
}
}
public static double squ(int a)
{
// this method will squire the given length
return a*a;
}

}
``````

#### How To Calculate Armstrong Number In Java Using Recursion

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.

My objective is to find out all the Armstrong numbers between 1-999.
The main method goes like this-

```public static void main(String[] args)
{
// TODO Auto-generated method stub
ArmstrongNumber a=new ArmstrongNumber();
for(int i=0;i<999;i++)
{
if(isarmstrong(i,(a.getNumber(i,0))))
{
//getNumber method will take the number and pass the initial result as 0
//to the called function
System.out.println("The Armstrong number" +i);
//printing the armstrong number
}
}
}```

This method will check if the number is really Armstrong Number

```public static boolean isarmstrong(int mainnumber,int calculatedval)
{
// this method will check if the input number and calculated value according
//to armstrong number are same.
if(mainnumber==calculatedval)
return true;
// return true if both are same
else
return false;
//return false if both are unequal
}```

This method will return the cube of a given number

```public int cube(int a)
{
// taking a number and returning the cube of it
return a*a*a;
}```

This is a method which will do the main job for us. This method will be called over and over to get the corresponding digits and their cube

```public int getNumber(int a,int result1)
//this method will take a number and some result as parameter
{
int result = result1;
int b;
b=a/10;
//diving the number by 10
int c=a%10;
//getting the remainder
if(b>0)
// checking if the remaining part is greater than 0
{
result=result+ cube(c);
//getting the cube of the remainder
if(b>=10)
// checking if the remaining part is greater than 10
{
result=getNumber(b,result);
//calling the same function with the remaining part of
//the number after division by 10 and result
}
else
{
//if the result after divided by 10 is less than 10 then making cube of the
//last digit
result= result +cube(b);
}
}
else
{
result=result+ cube(c);
//getting the cube of the remainder
}
return result;
// returning the result
}```

The entire code goes like this-

``````public class ArmstrongNumber {
int result=0;
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
ArmstrongNumber a=new ArmstrongNumber();
for(int i=0;i<999;i++)
{
if(isarmstrong(i,(a.getNumber(i,0))))
{
//getNumber method will take the number and pass the
//initial result as 0 to the called function
System.out.println("The Armstrong number" +i);
//printing the armstrong number
}
}
}
public static boolean isarmstrong(int mainnumber,int calculatedval)
{
// this method will check if the input number and calculated
//value according to armstrong number are same.
if(mainnumber==calculatedval)
return true;
// return true if both are same
else
return false;
//return false if both are unequal
}
public int cube(int a)
{
// taking a number and returning the cube of it
return a*a*a;
}
public int getNumber(int a,int result1)
//this method will take a number and some result as parameter
{
int result = result1;
int b;
b=a/10;
//diving the number by 10
int c=a%10;
//getting the remainder
if(b>0)
// checking if the remaining part is greater than 0
{
result=result cube(c);
//getting the cube of the remainder
if(b>=10)
// checking if the remaining part is greater than 10
{
result=getNumber(b,result);
//calling the same function with the remaining part of the number
//after division by 10 and result
}
else
{
//if the result after divided by 10 is less than 10 then making
// cube of the last digit
result= result +cube(b);
}
}
else
{
result=result +cube(c);
//getting the cube of the remainder
}
return result;
// returning the result
}
}``````

We are done…

The output??

```The Armstrong number0
The Armstrong number1
The Armstrong number153
The Armstrong number370
The Armstrong number371
The Armstrong number407```

#### How To Calculate Armstrong Number In Java Without Using Recursion

 Armstrong Number In Java Without Using Recursion

This is done not using the recursion Technique. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.My objective is to find out all the Armstrong Number between 1-999
The main function is pretty similar

``````
public static void main(String[] args) {
// TODO Auto-generated method stub
arms ab=new arms();
//I have given the class name as arms
for(int i=0;i<999;i++ )
{
if(isarmstrong(i,(ab.getNumber(i))))
//getNumber is the function which will get a number and calculate the value as
//per Armstrong principal
{
System.out.println("The Armstrong number is" +i);
}
}
``````

The supporting functions are …

• Armstrong
• cube

The isarmstromg method looks like-

``````
public static boolean isarmstrong(int mainnumber,int calculatedval)
// this method will take the main number and the calculated value obtained from
//getNumber and will determine if they are same.
{
if(mainnumber==calculatedval)
return true;
else
return false;
}

``````

The cube method will look like this-

``````
public int cube(int a)
//takes some integer value
{
return a*a*a;
// returns the cube value for that number
}
``````

Now, let’s look at the get number function this is the heart of this method.

``````
public int getNumber(int a)
{
result=0;
int b;
while(a>0)
{ b=a%10;
//get the remainder
result=result +cube(b);
//add the cube of the remainder to result
a=a/10;
//divide the number by 10
}
return result;
}
``````

Let us look at the total class implementation:

``````
public class arms {
static int result=0;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
arms ab=new arms();
for(int i=0;i<3000;i ++ )
{
if(isarmstrong(i,(ab.getNumber(i))))
{
System.out.println("The Armstrong number is"+ i);
}
}
}
public static boolean isarmstrong(int mainnumber,int calculatedval)
{
if(mainnumber==calculatedval)
return true;
else
return false;
}
public int cube(int a)
{
return a*a*a;
}
public int getNumber(int a)
{
result=0;
int b;
while(a>0)
{ b=a%10;
result=result +cube(b);
a=a/10;
}
return result;
}
}``````

Let me know if you like this concept.
The output??

The Armstrong number0
The Armstrong number1
The Armstrong number153
The Armstrong number370
The Armstrong number371
The Armstrong number407

### How To Calculate Prime Numbers In Java?

 image credit:www.brooksdesign-ps.net

As per wiki here a prime no is–” A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime because only 1 and 5 evenly divide it, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6. The fundamental theorem of arithmetic establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up to ordering. The uniqueness in this theorem requires excluding 1 as a prime because one can include arbitrarily many copies of 1 in any factorization, e.g., 3, 1 × 3, 1 × 1 × 3, etc. are all valid factorizations of 3.”

So the logic we will follow is “check if the remainder for the number with the other number excluding 1,and the number should always have some value. else it is not a valid Prime number.

How the main method will be

``````
public static void main(String[] args) {
//if you are going to check with a upper limit
int num=100;
for(int i=2;i<num;i++  )
{
calculatePrimi(i);
}
//One more way to get no from user...
calculatePrimi(getNumber());
}
``````

The function will look like-

``````
public static void calculatePrimi(int i)
{
//this will take some integer value
boolean isPrime=false;
//making it false initially
for(int j=2;j<i;j++  )
{
//our counter will run from 2 to number-1
if(i%j==0)
{
isPrime=false;
break;
}
else{
isPrime=true;
}
}
if (isPrime==true)
{
System.out.println("The number " +i " is a prime Number");
}
else
{
System.out.println("The number " +i "is a Not prime Number");
}
}
``````

Let us get the number from user to test if that is a valid prime no

``````
public static int getNumber()
{
int st=0;
try{
//take some number from user
st=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a valid Number here"));
System.out.println(st);
}
catch(Exception e)
{
System.out.println(e);
getNumber();
}
return st;
}
``````

Optimization: The above logic works well for a small range or if the number is small enough. if we deal with a very big prime number then the above code will keep evaluating from 2 to that big number.

This put burden on the processor. The below logic is applied to the prime number calculation to reduce the complexity and increase efficiency.
Logic the for loop must not go till the number. It should go to the square root of that number. So for any number the possible divisor can be found between 2 to the square root of that number. for square root we can use Math.sqrt(int a) function. This function returns double so we need to cast it to int.

``````
public class CalculatePrime{
public static void main(String args[])
{
System.out.println(isPrime(1000));
}
public static boolean isPrime(int n) {
for (int i = 2; i <= (int)Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
``````

The output of the code:
\$javac CalculatePrime.java
\$java -Xmx128M -Xms16M CalculatePrime
false

### How to Calculate Factorial of a Number in Java?

This section will talk about the implementation of factorial programming.Mathematically ,if i need to calculate the factorial value it is something like- n!=n*(n-1)*(n-2)*……*1

well, let me take the value of n from the user.

### The Function is

``````
private String getData() {
System.out.println("Thanks for the Number, " + userName);
}
``````

When you get the number we need to calculate the factorial

### The Factorial Function in Simple form

``````
private int fact(int  strval) {
//strval is the value provided by the user
int j;
/I am initializing j=1 and val=1 as my output factorial can not be zero.
j = 1;
int val;
val = 1;
for (j=1;j<=strval;j++)
{
val=val*j;
}
return val;
}
``````

``````
//definition of  a static variable
//I am initializing val=1 as my output factorial can not be zero.
static int val=1;
private int recfact(int j) {
//here the input no will multiplied by val(which is 1 at starting)
val=val*j;
//after multiplication decrease the number by 1(by this way we can get (n-1),(n-2) and so on
j--;
// This is the condition till how many time it should run. for this case it should run till
//the time j 's value is 1 or greater than 1
if(j>=1)
recfact(j);
return val ;
}
``````

### The Factorial Function using recursion function

``````
private int recfact_withoutstatic(int j) {
//Here also initialize j as value to h(h is a local variable)
int h=j;
//This out is defined to avoid (rule-1)
int out=1;
if(j>=1)
{
//this is recursive function which is calling the same function again with (n-1),(n-2),(n-3) and so on
out=h*recfact_withoutstatic(j-1);
}
return out;
}
``````

### The Factorial Function using all functions

``````import java.io.*;
import javax.swing.JOptionPane;
public class factorial {
static int val=1;
public static void main (String[] args) {
//  prompt the user to enter their name
factorial f=new factorial();
int i=Integer.parseInt(f.getData());
System.out.println(f.fact(Integer.parseInt(f.getData())));
System.out.println(f.recfact(Integer.parseInt(f.getData())));
System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
}
private String getData() {
JOptionPane.QUESTION_MESSAGE);
System.out.println("Thanks for the Number, " + userName);
}
private int fact(int strval) {
int j;
j = 1;
int val;
val = 1;
for (j=1;j<=strval;j++)
{
val=val*j;
}
return val;
}
private int recfact(int j) {
val=val*j;
j--;
if(j>=1)
recfact(j);
return val ;
}
private int recfact_withoutstatic(int j) {
int h=j;
int out=1;
if(j>=1)
{
out=h*recfact_withoutstatic(j-1);
}
return out;
}
} // end of factorial class``````
##### The Factorial Rule validations:
###### Rule-1 talks about factorial of 0 and its value will be 1

So let us update the function

``````
private int recfact_withoutstatic(int j) {
int h=j;
int out=1;
if (j==0) {
return out;
}
else
{
if(j>=1)
{
out=h*recfact_withoutstatic(j-1);
}
return out;
}
}``````

User needs to give integer value only.

##### we will try to implement this on top of our function. How??
``````
try{
System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
}
catch(Exception e)
{
System.out.println("wrong input");
}
``````

This will exclude the string and noninteger values

So the final code for factorial goes as::

``````
package component;
import java.io.*;
import javax.swing.JOptionPane;
public class factorial {
static int val=1;
public static void main (String[] args) {
// prompt the user to enter their name
factorial f=new factorial();
try{
System.out.println(f.fact(Integer.parseInt(f.getData())));
}
catch(Exception e) {
System.out.println("wrong input");
}
try
{
System.out.println(f.recfact(Integer.parseInt(f.getData())));
}
catch(Exception e) {
System.out.println("wrong input");
}
try{
System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
}
catch(Exception e) {
System.out.println("wrong input");
}
}
private String getData() {
System.out.println("Thanks for the Number, " + userName);
}
private int fact(int strval) {
int j;
j = 1;
int val;
val = 1;
if (strval==0) {
return val;
}
else
{
for (j=1;j<=strval;j++)
{
val=val*j;
}
return val;
}
}
private int recfact(int j) {
if (j==0) {
return val;
}
else
{
val=val*j;
j--;
if(j>=1)
recfact(j);
return val ;
}
}
private int recfact_withoutstatic(int j) {
int h=j;
int out=1;
if (j==0) {
return out;
}
else
{
if(j>=1)
{
out=h*recfact_withoutstatic(j-1);
}
return out;
}
}
} // end of ReadString class
``````

### Find all numbers which are equal to the sum of the factorial of their digits

Now let me find out some numbers in such a way that the sum of the factorial of each digit of that number is equal to that number.
like-145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145
So the logic is —
1.Get the number
2. Find out each digit of that number
3. Find out factorial of that number
4. Sum of the factorials
5. Check if the original input is equal to the sum
6. if they match print the result.

How to code:

##### 2. Now I need to create a logic that will give me the digits from a number.
``````private void getDigit(int number)
{

int tmp = 1;
while(number > 0)
{
tmp = number % 10;
number /= 10;
System.out.println(tmp );
}
}``````

So now we have the numbers of each digit.

### 3.Find out factorial of that number

#### 4. Sum of the factorials

so after getting factorials for each digit we need to sum these. let me write a function for it which will call the factorial method and sum them up.

``````
long result = 0;
int tmp = 1;
while(number > 0) {
tmp = number % 10;
//recursive factorial method more details on here
result += recfact_withoutstatic(tmp);
number /= 10;
}
return (int)result;
}
}
``````

#### 5. Check if the original input is equal to the sum

``````
//i is the number we are passing to our function addfactOfDigits
System.out.println(i);``````

### How to Convert Decimal to Binary to Hex to Octal System in Java?

Decimal to Binary to hex to octal system converter in Java
The code for Decimal to Binary to Hex to Octal System conversion:

``````
public class DataConversion {
public static void main(String[] args) {
String userNumber = null;
int in = Integer.parseInt(userNumber );

System.out.println("Integer: " + in );
//integer to binary
String by = Integer.toBinaryString( in );
System.out.println("Byte: " + by);
String hex = Integer.toHexString( in );
System.out.println("Hexa decimal: " + hex);
//integer to octal
String oct = Integer.toOctalString( in );
System.out.println("Octal: " + oct);
}
}``````

### How to calculate Factors of a number in java

#### What is a factor in Math

A number may be made by multiplying two or more other numbers together. The numbers that are multiplied together are called factors of the final number.

All numbers have a factor of one since one multiplied by any number equals that number. All numbers can be divided by themselves to produce the number one. Therefore, we normally ignore one and the number itself as useful factors.

The number fifteen can be divided into two factors which are three and five.
The number twelve could be divided into two factors which are 6 and 2.
Six could be divided into two further factors of 2 and 3.
Therefore the factors of twelve are 2, 2, and 3.
If twelve was first divided into factors 3 and 4, the four could be divided into factors of 2 and 2. Therefore the factors of twelve are still 2, 2, and 3.
There are several clues to help determine factors.
Any even number has a factor of two Any number ending in 5 has a factor of five
Any number above 0 that ends with 0 (such as 10, 30, 1200) has factors of two and five.
To determine factors see if one of the above rules applies (ends in 5, 0 or an even number).
If none of the rules applies, there still may be factors of 3 or 7 or some other number.

Now let us derive a logic to determine the factors of a number.
1. Take the number from the user.
2. As the factors are non-fractional so the factor range will be 1 to that number.(mathematically minus that number to plus that number say 20- the positive factors are  1->2->4->5->10->20
and negative factors are  -20->-10->-5->-4->-2->-1)
3. So get a factor the main logic is to get a number that will divide the given number and keep the remainder as 0.

Now after parsing the input string to integer pass to your factor calculation code. The code will look something like the below:

``````
public void factorial(int a) {
//pos and negs are two string to catch the factors. a is the value given by the user. You need to Handle positive and negative values.
String pos="";
String negs="";
//Handling positive value like 20
if(a>0)
{
for (int i=-a;i<=a;i++) {
if((i!=0) && (a%i)==0) {
if(i>0)
{
pos=pos+"->"+i;
}
else
negs=negs+"->"+i;
System.out.println("Thanks for the Number, " +i);
}
}
System.out.println("Thanks for the Number, " + pos);
System.out.println("Thanks for the Number, " + negs);
}
else {
//handling negative values like -20
for (int i=a;i<=-a;i++) {
if((i!=0) && (a%i)==0) {
if(i>0)
{
pos=pos+"->"+i;
}
else
negs=negs+"->"+i;
System.out.println("Thanks for the Number, " +i);
}
}
System.out.println("Thanks for the Number, " + pos);
System.out.println("Thanks for the Number, " + negs);
}
}``````

### How to calculate an Abundant and Deficient Number in java?

An Abundant number is defined as a number if the sum of all its positive divisor except itself is more than the number itself.
A deficient number is defined as a number if the sum of all its positive divisor except itself is less than the number itself. Example-12.
The factors of 12 are-1,2,3,4,6,12.
To be an abundant number we need to add the divisors except for that number so the sum is-1+2+3+4+6=16 which is greater than 12.
So it is an abundant number.
Again take the example of 16
The factors are-1,2,4,8,16
To be an abundant number we need to add the divisors except for that number so the sum is-1+2+4+8=15 which is less than 16.
So it is not an abundant number rather it is a deficient no.

Let us think the logic– 1. Get the range from the user.
2. Get the number inside the range starting from start range(I will use 1)
3. Find out the positive divisors of the number
4. Add all the positive divisors except itself
5. Check if the sum of the divisors is greater than that number.
6. If the checking is passed to become an abundant number …save it
7. Increment a number
8. If it is inside the range perform Step 9 or else perform Step-10
10. Exit
So I can write a function for step no 3 to 10 because that is repetitive.

Let us code:
For logic no-1 -take user input

For logic 2–

//I am assuming the lower range as 1 or else please replace 1 with your lower range

``````
for (int i=1 ;i<=your_positive_range ;i++)
{
checkAbundant(i);
}
``````

Now how the checkAbundant code will look like-

//a is the number coming from your previous function for which we need to check if it is an abundant number or not.

``````
public void checkAbundant(int a)
{
//pos is a temporary variable to store the sum of the divisors(positive)
int pos=0;
// Same logic by which we derived the factors of a given number
//As per the rule we need to exclude the number itself so the loop goes to number-1 )
{
System.out.println("this is  a abundant no"+a);
}

else
{
System.out.println("this is  a deficient no"+a);
}
}``````

### How to Convert Decimal to Binary in Java Without Using Library Function?

#### The math logic:

To convert decimal to binary is also very simple, you simply divide the decimal value by 2 and then write down the remainder, repeat this process until you cannot divide by 2 anymore, for example, let’s take the decimal value 157:

157 ÷ 2 = 78– with a remainder of 1
78 ÷ 2 = 39—with a remainder of 0
39 ÷ 2 = 19–with a remainder of 1
19 ÷ 2 = 9—with a remainder of 1
9 ÷ 2 = 4—with a remainder of 1
4 ÷ 2 = 2—with a remainder of 0
2 ÷ 2 = 1–with a remainder of 0
1 ÷ 2 = 0 -with a remainder of 1   <- to convert write this remainder first.

Next write down the value of the remainders from bottom to top (in other words write down the bottom remainder first and work your way up the list) which gives:

10011101 = 157

So I am going to implement this rule–

I will write a function that will take the input as a number and provide the output as a binary code.

``````
public String deciToBinary(int num)
{
}
``````

#### The actual Decimal to Binary Conversion Code:

``````
public String deciToBinary(int t) {
t is the input variable...how to get dynamically ? ? ? Check here
//This will be my return string
String j = "";
//This c  is reminder variable
int c = 0;
int h;
//I will operate this operation until the number( given ) becomes 0
//see the last line of the above example
while (t > 0) {
// h is the temporary variable to hold the initial value of the number.
h = t;
//Divide the number by 2
t = (h / 2);
// Check the remainder
c = h % 2;
//this is my exit criteria
if (t != 0) {
//as need to read from behind refer the above example i am creating the
//output by adding the current remainder (first)+the previous remainder.
//This will create a stack of the remainder list.
j = Integer.toString(c) + j;
} else {
j = Integer.toString(h) + j;
}
}
System.out.println("val of j final--" + j);
}
``````

There is one more way to do it. Let me write the code for this..

``````
public class decToBin {
public static void main(String[] args) {
//y is your input variable. how to get dynamically??? Check here
int y = 9;
// set x to the largest power of two that is <= y
int x = 1;
String output = "";
while (x <= y / 2) {
x = x * 2;
}
// check for presence of powers of 2 in y, from largest to smallest
while (x > 0) {
// x is not present in y
if (y < x) {
//save this to the output variable
output = output + "0";
}
// x is present in y, so remove x from y
else {
//save this to the output variable
y = y - x;
output = output + "1";
}
// Next smallest power of 2
x = x / 2;
}
System.out.println(output);
}
}
``````

### Power calculation in java without using pow function

The logic is something–
1. get the number from user
2. Check out how much is the power to be calculated
3. multiply the given number in 1 for these many times (given in step-2)

Say I have a number called 2  (getting in logic no-1)
I need to calculate the 2 to the power 4 value(getting 4 at logic no-2)
So the output of that is 2*2*2*2=16

Let us implement that in code.

``````public  void calcpow(int val,int powr) {
//this function takes two input ...the number and the power value
int res=1;
//res is the integer type temp variable  This is initialized to 1 to handle the condition where power=0. x to the power 0=1
for(int i=1;i<=powr;i++) {
res=res*val;

}
System.out.println(res);
}``````

### Binary to Decimal Calculation in java

Get a detailed description here.
Let’s create the logic:
1. Get the Binary String.
2. Find out the length.
3. Remember when we read a string from first it is actually the last element of the binary number system.
4. Convert the binary string into an Array.
5. We will only take care of the 1s, not the zeros. As Zero is actually adding Zero.
6. So we will set a pointer(please don’t worry…this a variable only…not C’s pointer) to initial position and scan through the string.
7. Whenever we will get one (1) we will check the position with respect to a string starting from last.
8. We will multiply 2 that many numbers of times i.e. 2 to the power of position.
9. Remember if the last position is 0 it is ok but if it is 1 ..we need to add one.two to the power 0 is one.
Lets code1. For user input
2. For length calculation

``````
int len=input.length();
``````

3. For  rest of the things

``````
public  void binToDec(String input) {
int len=input.length();
//res is the output decimal number
int res=0;
for(int i=0;i<len;i++) {
//consider only those cases where the 1 is present
if (output.charAt(i)=='1') {
//checking 9th condition
if(i==(len-1))
{
res+= 1;
}
else
{
//power calculation function
res+= calcpowerof2(2,len-(i+1));
}

}

}
System.out.println("res-"+res);
}``````

### How to Calculate an Evil No in java?

 How to Calculate an Evil No in java

### Evil No-Definition

A number N will be evil number if it has an even number of 1’s in it’s binary expansion.

#### Logic

1. Get the number from the user.
2. Find a binary form of the number
3. The binary stream will be a String of 1s and 0s.
4. Now create a counter and initialize it to 0(to satisfy the input for 0. binary of decimal 0 is also zero).
5. Convert the String to the array.
6. Check the array element one by one for 1.
7. if 1 found increment the counter by one
8. check the number of 1s is even or odd.
9. If it is found even….you are done that is the Evil number.

### Lets code

for

1. Get the number from the user.

2. Find a binary form of the number.
3. The code looks like-

``````
public class HelloWorld{
public static void main(String []args){
checkEvil("13");
}
public static void checkEvil(String input)
{
//declare the counter and initialize it to 0
int counter=0;
int len=input.length();
//Scan through the binary stream for 1
for(int i=0;i<len;i++)
{
if (input.charAt(i)=='1')
{
//if an one found increment counter by 1
counter++;
}
}
// Check the odd even logic
if((counter%2)==1) {
System.out.println("not evil");
}
else
System.out.println("evil");
}
}
``````

The output of the code:
\$javac HelloWorld.java
\$java -Xmx128M -Xms16M HelloWorld
not evil

### How to calculate the perfect number in java

#### What is a Perfect Number:

a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum).

Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

Logic
The logic is pretty much the same.
The condition is to add up the factors and check if that is equal to the given number.
Now check the abundant number code and change the last part of the code…

``````
if(pos==a)
{
System.out.println("this is  a perfect Number no"+a);
}
``````

So the final code will look like this-

``````
public class HelloWorld{
public static void main(String []args){
new Abundant();
}
}
class Abundant {
public Abundant() {
for (int i=1 ;i<=100;i++)
{
factorcal(i);
}
}
public void factorcal(int a) {
int pos=0;
for (int i=1;i<a;i++) {
if((i!=0) && (a%i)==0) {
if(i>0)
{
pos=pos+i;
}
}
}
if(pos==a)
{
System.out.println("this is a perfect Number no"+a);
}
}
}
``````

The output of the code:
\$javac HelloWorld.java
\$java -Xmx128M -Xms16M HelloWorld
this is a perfect Number no6
this is a perfect Number no28

### How To Generate Random Numbers in Java?

Random numbers are run-time constants and are very important in coding. We use Random numbers for the Security of the application, Gaming(gambling), Maths etc.
Below are two packages and classes that support the generation of Random numbers.

1. java.util.Random
2. java.Math.Random

Using java.util.Random Class:

``````
import java.util.Random
public class myRandomNumber{
public static void main(String[] Args)
{
Random rand=new Random();
for(int i=0;i<10;i++)
{
int randomNumber=rand.nextInt(100);
System.out.println(randomNumber);
}
}
``````

Using java.Math.Random Class: This is useful when we need to generate in a range

``````
public class myRandomNumber{
public static void main(String[] Args)
{
for(int i=0;i<10;i++)
{
int randomNumber=Math.random();
System.out.println(randomNumber);
}
}
``````

### Find Repeated Character From An Array of String In Java

You have a array of strings e.g [“abcd”,”aabcd”,xyz”, “ccbc”] find the strings in which characters are repeated.Output would be [“aabcd”,”ccbc”].

Logic:: Need to check if the current position and the next position are having the same character or not. If they have the same character they are repetitive characters.

``````//You have a array of strings e.g ["abcd","aabcd",xyz", "ccbc"] find the strings in
//which characters are repeated.Output would be ["aabcd","ccbc"].
//Author:Animesh
public class RepeatString {
static String[] names={"abcd","aabcd","xyz", "cdbbc"};
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<names.length;i++)
{
if(repeatCalulator(names[i]))
{
System.out.println(names[i]);
}
}
}
public static boolean repeatCalulator(String name)
{
boolean flag=false;
int sizeoftheString=name.length();
for(int j=1;j<sizeoftheString;j++)
{
if(name.charAt(j-1)==name.charAt(j))
{
flag=true;
break;
}
}
return flag;
}
}``````