HomeAutomation

Java for Testers Interview Questions And Answers – Part 3

Java for Testers Interview Questions And Answers – Part 3

Java for Testers – Interview Questions and Answers Part-3

1) Write a Java program to demonstrate the creation of Interface?

// A simple interface 
interface A 
{  
    final int a = 10; 
    void display(); 
} 
// A class that implements the interface. 
class TestClass implements A 
{  
    public void display() 
    { 
        System.out.println("this is an interface"); 
    }  
    public static void main (String[] args) 
    { 
        TestClass t = new TestClass(); 
        t.display(); 
        System.out.println(a); 
    } 
}

2) Write a Java program to print date and time?

public class CurrentDateTime {    
  public static void main(String[] args) {    
   DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");  
   LocalDateTime now = LocalDateTime.now();  
   System.out.println(df.format(now));  
  }    
}

3) Write a Java program to demonstrate SQL Date?

public class SQLDate {  
    public static void main(String[] args) {  
        long millis=System.currentTimeMillis();  
        java.sql.Date date=new java.sql.Date(millis);  
        System.out.println(date);  
    }  
}

4) Write a Java program to demonstrate Date format?

public class GetCurrentDateTime {
    private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(sdf.format(date));
        Calendar cal = Calendar.getInstance();
        System.out.println(sdf.format(cal.getTime()));
        LocalDateTime now = LocalDateTime.now();
        System.out.println(dtf.format(now));
        LocalDate localDate = LocalDate.now();
        System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
    }
}

 

5) Write a Java program to demonstrate generating a random number?

public class GenerateRandomNumber {
    public static void main(String[] args){
        Random rand = new Random();
        int r1 = rand.nextInt(1000);
        System.out.println("Random numbers: "+ r1);
    }
}

 

6) Write a Java program to demonstrate garbage collection?

public class GarbageCollector {
    public static void main(String[] args) throws InterruptedException{
        GarbageCollector t1 = new GarbageCollector();
        GarbageCollector t2 = new GarbageCollector();
        // Nullifying the reference variable
        t1 = null;
        // requesting JVM for running Garbage Collector
        System.gc();
        // Nullifying the reference variable
        t2 = null;
        // Requesting JVM for running Garbage Collector
        Runtime.getRuntime().gc();
    }
    @Override
    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected: " + this);
    }
}

 

7) Write a Java program to get the IP Address of own machine?

public class FindIPAddress {
    public static void main(String[] args) throws Exception{
        // Returns the instance of InetAddress containing local host name and address
        InetAddress localhost = InetAddress.getLocalHost();
        System.out.println("System IP Address : " + (localhost.getHostAddress()).trim());
        // Find public IP address
        String systemipaddress = "";
        try
        {
            URL url_name = new URL("http://bot.whatismyipaddress.com");
            BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
            // reads system IPAddress
            systemipaddress = sc.readLine().trim();
        }
        catch (Exception e)
        {
            systemipaddress = "Cannot Execute Properly";
        }
        System.out.println("Public IP Address: " + systemipaddress +"\n");
    }
}

 

8) Write a Java program to open a notepad?

public class OpenNotepad {
    public static void main(String[] args){
        Runtime rs = Runtime.getRuntime();
        try{
            rs.exec("notepad");
        }
        catch (IOException e){
            System.out.println(e);
        }
    }
}

 

9) Write a Java program to demonstrate Linear Search?

public class LinearSearch {
    static int search(int arr[], int n, int x){
        for(int i = 0;i<n;i++){
            if(arr[i] == x)
                return i;
        }
        return -1;
    }
    public static void main(String[] args){
        int[] arr = {5,1,9,4,3,8};
        int n = arr.length;
        int x = 4;
        int index = search(arr,n,x);
        if(index == -1){
            System.out.println("Element is not present in the array");
        }
        else
            System.out.println("Element found at position " + index);
    }
}

 

10) Write a Java program to demonstrate Binary Search?

class BinarySearch {
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
            // If the element is present at the middle itself
            if (arr[mid] == x)
                return mid;
            // If element is smaller than mid, then it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
            // Else the element can only be present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
        // If element is not present in array
        return -1;
    }
    public static void main(String args[])
    {
        BinarySearch bs = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = bs.binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " + result);
    }
}

 

11) Write a Java program to demonstrate Bubble sort?

class BubbleSort
{
    void bubbleSort(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }
    void printArray(int arr[]) {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
    public static void main(String args[]) {
        BubbleSort bs = new BubbleSort();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        bs.bubbleSort(arr);
        System.out.println("Sorted array");
        bs.printArray(arr);
    }
}

 

12) Write a Java program to demonstrate connecting to a Database?

public class ConnectMSSQLServer
{
   public void dbConnect(String db_connect_string,String db_userid,String db_password)
   {
      try {
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection conn = DriverManager.getConnection(db_connect_string,db_userid, db_password);
         System.out.println("connected");
         Statement statement = conn.createStatement();
         String queryString = "select * from Employees where lastName='Smith'";
         ResultSet rs = statement.executeQuery(queryString);
         while (rs.next()) {
            System.out.println(rs.getString(1));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args)
   {
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>","<password>");
   }
}

 

13) Write a Java program to demonstrate inserting data into a table using JDBC?

public class InsertIntoDB {
    public static void main(String[] args) {
        Connection connection = null;
        Statement stmt = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
            stmt = connection.createStatement();
            stmt.execute("INSERT INTO EMPLOYEE (ID,FIRST_NAME,LAST_NAME,STAT_CD) "
                                + "VALUES (1,'John','Smith',5)");
        } 
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stmt.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

14) Write a Java program to demonstrate executing a Procedure in JDBC?

public class StoredProcedureCallExample1 {
    public static void main(String[] args) {
        String dbURL = "jdbc:mysql://localhost:3306/booksdb";
        String user = "root";
        String password = "[email protected]";
        try (
            Connection conn = DriverManager.getConnection(dbURL, user, password);
            CallableStatement statement = conn.prepareCall("{call create_author(?, ?)}");
        ) {
            statement.setString(1, "Bill Gates");
            statement.setString(2, "[email protected]");
            statement.execute();
            statement.close();
            System.out.println("Stored procedure called successfully!");
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

 

15) Write a Java program to check Regular Expressions?

class CheckRegularExpression{
    public static void main(String []args){
      Pattern pattern = Pattern.compile("auto*");
        Matcher m = pattern.matcher("automation");
        while (m.find())
            System.out.println("Pattern found from " + m.start() + " to " + (m.end()-1));
    }
}

 

16) Write a Java program to create Multi-threading?

class Multithreading extends Thread 
{ 
    public void run() 
    { 
        try
        { 
            // Displaying the thread that is running 
            System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); 
  
        } 
        catch (Exception e) 
        { 
            System.out.println ("Exception is caught"); 
        } 
    } 
} 
public class Multithread 
{ 
    public static void main(String[] args) 
    { 
        int n = 8; // Number of threads 
        for (int i=0; i<8; i++) 
        { 
            Multithreading object = new Multithreading(); 
            object.start(); 
        } 
    } 
}

 

17) Write a Java program to demonstrate joining thread?

public class JoinThreads {
    public static void main(String args[]) throws InterruptedException{
        System.out.println(Thread.currentThread().getName() + " is Started");
        Thread exampleThread = new Thread(){
            public void run(){
                try {
                    System.out.println(Thread.currentThread().getName() + " is Started");
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName() + " is Completed");
                } catch (InterruptedException ex) {
                    Logger.getLogger(Join.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        exampleThread.start();
        exampleThread.join();
        System.out.println(Thread.currentThread().getName() + " is Completed");
    }
}

 

18) Write a Java program to write data into the text files?

public static void WriteTextFile() throws IOException 
{
    String fileContent = "This is Java interview questions";
    BufferedWriter writer = new BufferedWriter(new FileWriter("c:/temp/samplefile.txt"));
    writer.write(fileContent);
    writer.close();
}

 

19) Write a Java program to read data from the text files?

public class ReadTextAsString 
{ 
  public static String readFileAsString(String fileName)throws Exception 
  { 
    String data = ""; 
    data = new String(Files.readAllBytes(Paths.get(fileName))); 
    return data; 
  } 
  public static void main(String[] args) throws Exception 
  { 
    String data = readFileAsString("C:\\temp\\test.java"); 
    System.out.println(data); 
  } 
}

 

20) Write a Java program to convert string to integer?

public class ConvertStringToInteger{
    public static void main(String[] args){
    String number = "10";
    int result = Integer.parseInt(number);
    System.out.println(result);
    }
}

21) Write a Java program to convert integer to string?

public class ConvertIntegerToString{
    public static void main(String[] args){
    int a = 100
    String str = Integer.toString(a);
    System.out.println(str);
    }
}

 

22) Write a Java program to convert string to long?

public class ConvertStringToLong{
    public static void main(String[] args){
    String s = "10";
    long result = Long.parseLong(s);
    System.out.println(result);
    }
}

 

23) Write a Java program to convert string to float?

public class ConvertStringToLong{
    public static void main(String[] args){
    String s = "13.6";
    float result = Float.parseFloat(s);
    System.out.println(result);
    }
}

 

24) Write a Java program to convert string to double?

public class ConvertStringToDouble{
    public static void main(String[] args){
    String s = "6.54";
    double result = Double.parseDouble(s);
    System.out.println(result);
    }
}

 

25) Write a Java program to convert string to date?

public class StringToDate {  
public static void main(String[] args)throws Exception {  
    String sDate="01/01/2020";  
    Date date=new SimpleDateFormat("dd/MM/yyyy").parse(sDate);  
    System.out.println(sDate+"\t"+date);  
  }  
}

Next Steps:

> More interview questions and answers on Selenium Java, continue to the next post (Click on Next Post link below)

> Check complete Selenium Java interview questions and answers here (Click here)

Please leave your questions/comments/feedback below.

Happy Learning ?

About Me > Bijan Patel

Connect to me on Linked In (Click here)

On a mission to contribute to the Software Testing Community in all possible ways.

 

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *