# Java Basic Programs

## Fibonacci series in Java

In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.

```class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}

}}  ```

### Fibonacci Series using recursion in java

```class FibonacciExample2{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}  ```

## Prime Number Program in Java

Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can’t be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17…. are the prime numbers.

Note: 0 and 1 are not prime numbers. The 2 is the only even prime number because all the other even numbers can be divided by 2.

``````public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0)  { System.out.println(n+" is prime number"); }
}//end of else
}
}

Output:

3 is prime number``````

### Prime Number Program using Method in Java

``````public class PrimeExample2{
static void checkPrime(int n){
int i,m=0,flag=0;
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0)  { System.out.println(n+" is prime number"); }
}//end of else
}
public static void main(String args[]){
checkPrime(1);
checkPrime(3);
checkPrime(17);
checkPrime(20);
}
}   Output:

1 is not prime number
3 is prime number
17 is prime number
20 is not prime number``````

### Prime Number Program in Java (Another way)

You can also use a method where number is not predefined. Here, user has to put the number to check if the number is prime.

``````import java.util.Scanner;

import java.util.Scanner;

public class PrimeExample3 {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = s.nextInt();
if (isPrime(n)) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
}

public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Output:

Use image PrimeExample1``````

## Armstrong Number in Java

In this section, we will discuss what is Armstrong number and also create Java programs to check if the given number is an Armstrong number or not. The Armstrong number program frequently asked in Java coding interviews and academics.

### What Is Armstrong Number

An Armstrong number is a positive m-digit number that is equal to the sum of the mth powers of their digits. It is also known as pluperfect, or Plus Perfect, or Narcissistic number. It is an OEIS sequence A005188. Let’s understand it through an example.

### Armstrong Number Example

1: 11 = 1

2: 21 = 2

3: 31 = 3

153: 13 + 53 + 33 = 1 + 125+ 27 = 153

125: 13 + 23 + 53 = 1 + 8 + 125 = 134 (Not an Armstrong Number)

1634: 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1643

Similarly, we can check other number also.

The first few Armstrong numbers between 0 to 999 are 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407. Some other Armstrong numbers are 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050, 24678051, 88593477, 146511208, 472335975, 534494836, 912985153, 4679307774, 32164049650, 32164049651.

### Armstrong Number Java Program

The following Java program prints all the Armstrong numbers up to the specified limit.

ArmstrongNumberExample1.java

``````import java.util.Scanner;
import java.lang.Math;
public class ArmstsrongNumberExample
{
//function to check if the number is Armstrong or not
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;
//assigning n into a temp variable
temp=n;
//loop execute until the condition becomes false
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
//determines the last digit from the number
last = temp % 10;
//calculates the power of a number up to digit times and add the resultant to the sum variable
sum +=  (Math.pow(last, digits));
//removes the last digit
temp = temp/10;
}
//compares the sum with n
if(n==sum)
//returns if sum and n are equal
return true;
//returns false if sum and n are not equal
else return false;
}
//driver code
public static void main(String args[])
{
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
//reads the limit from the user
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");
for(int i=0; i<=num; i++)
//function calling
if(isArmstrong(i))
//prints the armstrong numbers
System.out.print(i+ ", ");
}
}

Output:

Enter the limit: 999
Armstrong Number up to 999 are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407``````

Let’s create another Java program that checks if the given number is an Armstrong number or not.

### ArmstrongNumberExample2.java

``````import java.util.Scanner;
import java.lang.Math;
public class ArmstsrongNumberExample2
{
//function to check if the number is Armstrong or not
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;
//assigning n into a temp variable
temp=n;
//loop execute until the condition becomes false
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
//determines the last digit from the number
last = temp % 10;
//calculates the power of a number up to digit times and add the resultant to the sum variable
sum +=  (Math.pow(last, digits));
//removes the last digit
temp = temp/10;
}
//compares the sum with n
if(n==sum)
//returns if sum and n are equal
return true;
//returns false if sum and n are not equal
else return false;
}
//driver code
public static void  main(String args[])
{
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the number: ");
//reads the limit from the user
num=sc.nextInt();
if(isArmstrong(num))
{
System.out.print("Armstrong ");
}
else
{
System.out.print("Not Armstrong ");
}
}
}

Output 1:

Enter the number: 2
Armstrong

Output 2:

Enter the number: 1675
Not Armstrong``````

## How to Generate Random Number in Java

In Java programming, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many applications use the OTP. The best example of random numbers is dice. Because when we throw it, we get a random number between 1 to 6.

In this section, we will learn what is a random number and how to generate random numbers in Java.

### Random Number

Random numbers are the numbers that use a large set of numbers and selects a number using the mathematical algorithm. It satisfies the following two conditions:

• The generated values uniformly distributed over a definite interval.
• It is impossible to guess the future value based on current and past values.

## Generating Random Number in Java

In Java, there is three-way to generate random numbers using the method and classes.

• Using the random() Method
• Using the Random Class
• Using the ThreadLocalRandom Class
• Using the ints() Method (in Java 8)

### Using the Math.random() Method

The Java Math class has many methods for different mathematical operations. One of them is the random() method. It is a static method of the Math class. We can invoke it directly. It generates only double type random number greater than or equal to 0.0 and less than 1.0. Before using the random() method, we must import the java.lang.Math class.

Syntax:

1. public static double random()

It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.

Let’s create a program that generates random numbers using the random() method.

RandomNumberExample1.java

``````import java.lang.Math;
public class RandomNumberExample1
{
public static void main(String args[])
{
// Generating random numbers
System.out.println("1st Random Number: " + Math.random());
System.out.println("2nd Random Number: " + Math.random());
System.out.println("3rd Random Number: " + Math.random());
System.out.println("4th Random Number: " + Math.random());
}
}

Output:

1st Random Number: 0.17434160924512265
2nd Random Number: 0.4297410090709448
3rd Random Number: 0.4828656381344487
4th Random Number: 0.13267917059488898``````

Remember: Every time we get a different output when we execute the program. Your output may differ from the output shown above.

We can also use the following formula if we want to a generate random number between a specified range.

Math.random() * (max – min + 1) + min

In the above formula, the min value is inclusive while the max value is exclusive.

Let’s create a program that generates random numbers between 200 to 400.

RandomNumberExample2.java

``````public class RandomNumberExample2
{
public static void main( String args[] )
{
int min = 200;
int max = 400;
//Generate random double value from 200 to 400
System.out.println("Random value of type double between "+min+" to "+max+ ":");
double a = Math.random()*(max-min+1)+min;
System.out.println(a);
//Generate random int value from 200 to 400
System.out.println("Random value of type int between "+min+" to "+max+ ":");
int b = (int)(Math.random()*(max-min+1)+min);
System.out.println(b);
}
}
Output 1:

Random value of type double between 200 to 400:
233.88329802655377
Random value of type int between 200 to 400:
329
Output 2:

Random value of type double between 200 to 400:
254.8419979875385
Random value of type int between 200 to 400:
284``````

## How to Compare Two Objects in Java

Java Object class is the super class of all the Java classes. All Java classes implements the Object class by default. The Java Object class provides the two important methods to compare two objects in Java, i.e. equals() and hashCode() method. In this section, we will learn how equals() and hashCode() method works. Along with this, we will also learn how to compare two objects in Java with proper examples.

Java provides the two methods of the Object class to compare the objects are as follows:

• Java equals() Method
• Java hashCode() Method

## Java equals() Method

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address.

Syntax:

1. public boolean equals(Object obj)

The method parses a reference object as a parameter. It returns true if the objects are equal, else returns false.

It is also possible that an object is equal to another given object, then the equals() method follow the equivalence relation to compare the objects.

• Reflexive: If x is a non-null reference, the calling of x.equals(x) must return true.
• Symmetric: If the two non-null references are x and y, x.equals(y) will return true if and only if y.equals(x) return true.
• Transitive: If the three non-null references are x, y, and z, x.equals(z) will also return true if x.equals(y) and y.equals(z) both returns true.
• Consistent: If the two non-null references are x and y, the multiple calling of x.equals(y) constantly returns either true or false. It does not provide any information used in the comparison.
• For any non-null reference x, x.equals(null) returns false.

In short, for any non-null reference say x and y, it returns true if and only if both references refer to the same object.

Remember: When we override the equals() method, it is necessary to override the hashCode() method. Overriding follow the convention for the hashCode() method that states, the equal object must have equal hash code.

### Example of equals() method

In the following example, we have created constructor of the Double and Long class and passes corresponding values, as an argument that stored in their objects, respectively.

After that, in the first println statement, we have invoked equals() method and parse an object y as a parameter that compares the object x and y. It returns false because x holds the double value and y holds the long value that is not equal.

Similarly, in the second println statement, we have invoked equals() method and parse the same value as in the constructor of the Double class. It returns true because the object of double class i.e. x holds the same value as we have passed in the equals() method.

ObjectComparisonExample.java

``````public class ObjectComparisonExample
{
public static void main(String[] args)
{
//creating constructor of the Double class
Double x = new Double(123.45555);
//creating constructor of the Long class
Long y = new Long(9887544);
//invoking the equals() method
System.out.println("Objects are not equal, hence it returns " + x.equals(y));
System.out.println("Objects are equal, hence it returns " + x.equals(123.45555));
}
}
Output:

Objects are not equal, hence it returns false
Objects are equal, hence it returns true``````

## Difference Between == Operator and equals() Method

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects.

Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

For example, the expression obj1==obj2 tests the identity, not equality. While the expression obj1.equals(obj2) compares equality.

## Java hashCode() Method

In Java, hash code is a 32-bit signed integer value. It is a unique id provided by JVM to Java object. Each Java object is associated with the hash code. The hash code is managed by a hash-based data structure, such as HashTable, HashSet, etc.

Remember: When we override the equals() method, it is necessary to override the hashCode() method, also.

Syntax:

1. public int hashCode()

It returns a randomly generated hash code value of the object that is unique for each instance. The randomly generated value might change during the several executions of the program.

The general contract for hashCode is:

• When it is invoked more than once during the execution of an application, the hashCode() method will consistently return the same hash code (integer value). Note that the object should not be modified.
• If the two objects are equal according to the equals() method, then invoking the hashCode() method on these two objects must produce the same integer value.
• It is not necessary that if the two objects are unequal according to equals() method, then invoking the hashCode() method on these two objects may produce distinct integer value. It means that it can produce the same hash code for both objects.

### Example of hashCode() method

In the following example, we have created two classes Employee.java and HashCodeExample.java.

In the Employee class, we have defined two fields regno of type int and name of type String. After that, we have created a constructor of the Employee class and passes these two fields as a parameter.

To perform the comparison of objects, we have created a separate class named HashCodeExample. In this class, we have created two instances of the Employee class i.e. emp1 and emp2. After that, we have invoked the hashCode() method using objects. We have stored the hash code value in the variable a and b, respectively.

Employee.java

``````public class Employee
{
private int regno;
private String name;
//constructor of Employee class
public Employee(int regno, String name)
{
this.name = name;
this.regno = regno;
}
public int getRegno()
{
return regno;
}
public void setRegno(int Regno)
{
this.regno = regno;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}  ``````
``````public class HashcodeExample
{
public static void main(String[] args)
{
//creating two instances of the Employee class
Employee emp1 = new Employee(918, "Maria");
Employee emp2 = new Employee(918, "Maria");
//invoking hashCode() method
int a=emp1.hashCode();
int b=emp2.hashCode();
System.out.println("hashcode of emp1 = " + a);
System.out.println("hashcode of emp2 = " + b);
System.out.println("Comparing objects emp1 and emp2 = " + emp1.equals(emp2));
}
}
Output:

hashcode of emp1 = 2398801145
hashcode of emp2 = 1852349007
Comparing objects emp1 and emp2 = false``````