Header Ads Widget

Basic Programs Of Java For Interviews | Top 10 Interview Based Java Programs For Freshers

 

Top 10 Interview Based  Java Programs  For Freshers

1.Java program to check whether the Number is Even or Odd.

Answer: import java.util.Scanner;

public class EvenOdd {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = reader.nextInt();

        if(num % 2 == 0)
            System.out.println(num + " is even");
        else
            System.out.println(num + " is odd");
    }
}


Output: Enter a Number (12)
 12 is even
   Enter a Number (13)
  13 is odd

In the above program, a Scanner object, reader is created to read a number from the user's keyboard. The entered number is then stored in a variable num.

Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is divisible by 2 or not.

For this, we use if...else statement in Java. If num is divisible by 2, we print num is even. Else, we print num is odd.



2. Java Program to check whether the Number is prime or not.

Answer: // Time Complexity : O(N)
// Space Complexity : O(1)
public class Main
{
    public static void main (String[]args)
    {
        int n = 23;
        checkPrime(n);
    }

    private static void checkPrime(int n) {
        int count = 0;

        // negative numbers, 0 and 1 are not prime
        if (n < 2)
            System.out.println ("The given is number " + n + " is not prime");

        // checking the number of divisors b/w [1, n]
        for (int i = 1; i <= n; i++) 
        { 
            if (n % i == 0)


In the above mentioned we’ll divide the whole loop situation into two parts, we’ll check if the number is lesser than 2, it’s not a prime. It also mustn’t have factors between range [2, num-1]

For an integer input, we check the following,

If the number is lesser than 2.
If the number has any factors other than 1 and itself.
If either of the above two conditions are satisfied, the number is not a Prime. 
                count += 1; 
        } 

        // if count of divisors greater than 2 then its not prime 
        if (count > 2)
            System.out.println ("The given is number " + n + " is not prime");

        else
            System.out.println ("The given is number " + n + " is prime");
    }
}


Output: 
23 is prime



3. Java program to print reverse of a string.

Answer: Import Java.util.scanner
                public class main {
                public static void main (string [ ] args) {
           string s= "Java";
           string rev = "";
      for (int i = s.length ()-1; i>=0;i--) {
                rev = rev +s.char AT (i);
                }
                system.out.println(rev);
                }
                }

Output:
String is Java
Reversed string is avaJ



4. Java program to check if the string is palindrome or not.

Answer: Impport Java.util.scanner;
            public class string is a palindrome or not {
            public static void main(string [ ] args) {
        string s ="arora";
        string rev ="" ;
          for(int i=s.length()-1;i>=0;i--)
        rev =rev + s.char At(i);
          if(s. equal s(rev)
        system .out.println("string is palindrome");
else
       system.out.println("string is palindrome");
}
}


output:  string is palindrome 


In this java program, we’re going to check string input by the user will be palindrome or not. Take a String input from the user and store it in a variable called “s”. A palindrome string is one that will be the same if we read from forward and from backward also. Strings like ‘madam’, ‘lol’, ‘pop’, ‘arora’ are examples of palindrome string . We’re storing a reversed string in ‘rev’ variable after that we will compare that original string and the reversed string are same or not using equals() method



5. Java program to find missing Number in array.

Answer: import java.util.Arrays;


class Main

{

// Find the missing number in a given array

public static int getMissingNumber(int[] arr)

{

// get the array's length

int n = arr.length;


// the actual size is `n+1` since a number is missing from the array

int m = n + 1;


// get a sum of integers between 1 and `n+1`

int total = m * (m + 1) / 2;


// get an actual sum of integers in the array

int sum = Arrays.stream(arr).sum();


// the missing number is the difference between the expected sum

// and the actual sum

return total - sum;

}


public static void main(String[] args)

{

int[] arr = { 1, 2, 3, 4, 5, 7, 8, 9, 10 };


System.out.println("The missing number is " + getMissingNumber(arr));

}

}



output: The missing Number is 6



6. Java program to check duplicate character in the String.

Answer: public class DuplStr {
 public static void main(String argu[]) {
  String str = "w3schools";
  int cnt = 0;
  char[] inp = str.toCharArray();
  System.out.println("Duplicate Characters are:");
  for (int i = 0; i < str.length(); i++) {
   for (int j = i + 1; j < str.length(); j++) {
    if (inp[i] == inp[j]) {
     System.out.println(inp[j]);
     cnt++;
     break;
    }
   }
  }
 }
}


Output: Duplicate Characters are: s o

Explanation: 

Here in this program, a Java class name DuplStr is declared which is having the main() method. All Java program needs one main() function from where it starts executing program.  Inside the main(), the String type variable name str is declared and initialized with string w3schools. Next an integer type variable cnt is declared and initialized with value 0. This cnt will count the number of character-duplication found in the given string.

The statement: char [] inp = str.toCharArray(); is used to convert the given string to character array with the name inp using the predefined method toCharArray(). The System.out.println is used to display the message "Duplicate Characters are as given below:". Now the for loop is implemented which will iterate from zero till string length. Another nested for loop has to be implemented which will count from i+1 till length of string.

Inside this two nested structure for loops, you have to use an if condition which will check whether inp[i] is equal to inp[j] or not. If the condition becomes true prints inp[j] using System.out.println() with s single incrementation of variable cnt and then break statement will be encountered which will move the execution out of the loop.


7.Java program to find number of words in a string.

Answer:  import java.util.Scanner;

class WordsInaString 

    public static void main(String arg[])

    { 

Scanner sc= new Scanner(System.in);

              System.out.println("enter a string :");

String a = sc.nextLine();

//char ch[]=new char[s.length()];

int count=Length(a);

             System.out.println("number of words in a given string is :"+count);

   }

static int Length(String s)

{

int c=0;

for (int i = 0;i<=(s.length()-1);i++)

    {

      if(  ( (i>0)&& (s.charAt(i)!=' ') &&(s.charAt(i-1)==' ')) || ((s.charAt(i)!=' ')&&(i==0)) )

            c++;    

    }

return c; 

}

}


Output:enter a string :

NEVER GIVE UP

number of words in a given string is :3



8.Java program to find Factorial of a Number.

Answer: public class Factorial {

    public static void main(String[] args) {

        int num = 10;
        long factorial = 1;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}


Output: Factorial of 10 = 3628800


In this program, we've used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.

We've used long instead of int to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable declared in java.math library.


9. Java program to print fibonacci series.

Answer: class Main {
  public static void main(String[] args) {
    int n = 10, firstTerm = 0, secondTerm = 1;
    System.out.println("Fibonacci Series till " + n + " terms:");
    for (int i = 1; i <= n; ++i) {
      System.out.print(firstTerm + ", ");
      // compute the next term
      int nextTerm = firstTerm + secondTerm;
      firstTerm = secondTerm;
      secondTerm = nextTerm;
    }
  }
}


Output: Fibonacci series till 10 terms.
              
                0,1,1,2,3,5,8,13,21,34

In the above program, firstTerm and secondTerm are initialized with 0 and 1 respectively (first two digits of Fibonacci series).

Here, we have used the for loop toprint the firstTerm of the series

  • compute nextTerm by adding firstTerm and secondTerm
  • assign value of secondTerm to firstTerm and nextTerm to secondTerm


10. Java program to sort an Array elements in ascending order.

Answer: import java.util.Scanner;
public class SortArray 
{
  public static void main(String[] args) 
  {
   int n, temp;
   Scanner s = new Scanner(System.in);
   System.out.print("Enter no. of elements you want in array:");
   n = s.nextInt();
   int a[] = new int[n];
   System.out.println("Enter all the elements:");
   for (int i=0; i<n; i++) 
    {
    a[i]=s.nextInt();
    }
    for (int i =0; i<n; i++) 
    {
    for (int j=i+1; j<n; j++) 
    {
    if (a[i]>a[j])  // compare numbers
    {
     temp=a[i];
     a[i]=a[j];
     a[j]=temp;
    }
   }
  }
  System.out.print("Elements in Ascending Order:");
  for (int i=0; i<n-1; i++) 
  {
  System.out.print(a[i]+ ", "); // print in same line and separate with comma
 }
  System.out.print(a[n-1]);
 }
}











Post a Comment

0 Comments