java interview questions for freshers

java  interview questions

java programming questions that helped me during my interviews

how to generate a log file in java
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
import java.io.IOException;

class  Log
{
 public static void main(String[] args) {  

    Logger logger = Logger.getLogger("MyLog");  
    FileHandler fh;  

    try {  

        // This block configure the logger with handler and formatter  
        fh = new FileHandler("C:/Users/myworld/Desktop/MyLogFile.log");  
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        // the following statement is used to log any messages  
        logger.info("My first log");  

    } catch (SecurityException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  

    logger.info("Hi How r u?");  

}
}
how to check a email is valid or not 
import java.util.*;

class IsValidEmailAddress 
{
 public boolean isValidEmailAddress(String email) {
           String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
           java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
           java.util.regex.Matcher m = p.matcher(email);
           return m.matches();
    }
 public static void main(String[] args) 
 {
  IsValidEmailAddress valid = new IsValidEmailAddress();

  System.out.println(valid.isValidEmailAddress("abc@gmail.com"));
 }
}

how to generate a guid
import java.util.UUID;

public class UniqueIDTest {
 public static void main(String[] args) {
  UUID uniqueKey = UUID.randomUUID();
  System.out.println (uniqueKey);
}
}
how to validate a phone number
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import VerhoeffAlgorithm;

class ValidationRE 
{
 
     public Boolean phoneNumberValidation( String sPhoneNumber){
  
  //regular expression pattern for mobile number
      Pattern pattern = Pattern.compile("^[2-9]{2}[0-9]{8}$"); 

   Matcher matcher = pattern.matcher(sPhoneNumber);


   if (matcher.matches()) { return true;}
      else {return false; }

  }

how to validate aadhar number
  public static boolean validateAadharNumber(String aadharNumber){
        Pattern aadharPattern = Pattern.compile("\\d{12}");
        boolean isValidAadhar = aadharPattern.matcher(aadharNumber).matches();
        if(isValidAadhar){
            isValidAadhar = VerhoeffAlgorithm.validateVerhoeff(aadharNumber);
        }
        return isValidAadhar;
    }
}
how to generate 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++;
      }         
   }
} 
how to generate String Recursive Reversal 
public class StringRecursiveReversal {

    String reverse = "";
    
    public String reverseString(String str){
        
        if(str.length() == 1){
            return str;
        } else {
            reverse += str.charAt(str.length()-1)
                    +reverseString(str.substring(0,str.length()-1));
            return reverse;
        }
    }
    
    public static void main(String a[]){
        StringRecursiveReversal srr = new StringRecursiveReversal();
        System.out.println("Result: "+srr.reverseString("Javatospring"));
    }
}
how to generate gcd of two numbers 
import java.util.Scanner;
class GCD
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.print("enter a  :");
  int a = sc.nextInt();
  System.out.print("enter b :");
  int b = sc.nextInt();
      
     while (a != b)
     {
   if(a > b)
   { 
     a = a-b;
   }
     }
  System.out.println("GCD : " + a);
 }
}
how to generate chron job
import java.util.Timer;
import java.util.TimerTask;
class MyTask extends TimerTask{
   
   static int i =0;

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
    i++;
     System.out.println( i+" : Hi see you after 1 seconds");
   }

}

public class CronJob{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 1 seconds

     t.scheduleAtFixedRate(mTask, 0, 1000);
   }

}
how to generate random password generator 
import java.util.Random;

public class passGen{

    //Verison 1.0
    private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
    private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String sChar = "!@#$%^&*";
    private static final String intChar = "0123456789";
    private static Random r = new Random();
    private static String pass = "";

    public static void main (String[] args) {
        System.out.println ("Generating pass...");
        while (pass.length () != 6){
            int rPick = r.nextInt(4);
            if (rPick == 0){
                int spot = r.nextInt(25);
                pass += dCase.charAt(spot);
            } else if (rPick == 1) {
                int spot = r.nextInt (25);
                pass += uCase.charAt(spot);
            } else if (rPick == 2) {
                int spot = r.nextInt (7);
                pass += sChar.charAt(spot);
            } else if (rPick == 3){
                int spot = r.nextInt (9);
                pass += intChar.charAt (spot);
            }
        }
        System.out.println ("Generated Pass: " + pass);
    }
}
how to generate factorial 
import java.util.Scanner;

class  Factorial
{
 static int fact = 1;

  public static void main(String[] args) 
 {
  Scanner sc = new Scanner( System.in);

   System.out.print("\nenter the number to find factorial: " );
  {
    fact = fact *num;
  }

   System.out.println( fact);

  }
}