1. How to make class read-only explain briefly?

Java provides access modifiers such as private, public, protected, etc, The read-only class is where you can get the values of class members however you are not allowed to set values.

Simply, you are providing only the get method and not providing any set method

Example Code Snippet

//Read-only class in Java

 public class Fruit{

     private String fruitName= "Apple";

    

     public String getFruitName() {

         return fruitName;

     }

     public static void main(String[] args) {

        Fruit f = new Fruit();

         String result = f.getFruitName();

         System.out.println("Name of the Fruit:" + " " + result);

     }

 }

2. What is Object Class explain?

  • Object class is the parent of all classes by default, This is the root class.
  • Every class has Object as a superclass
  • Object class is part of java.lang package
  • You can assign Object of any type to Object class (Ex: Object obj = new Fruit();)

Some useful methods provided by Object Class

toString(): returns the string representation of this object.

getClass(): returns the Class class object of this object

equals(Object obj): compares the given object to this object.

finalize():  this is invoked by the garbage collector before the object is being garbage collected.

3. What is the difference between Mutable and Immutable Object? Explain String and StringBuilder in the same context

A mutable object can be changed after it's created. An immutable object can't change.

Mutable objects provide a method to change the content of the object. The immutable objects do not provide any method to change the values

Considering String and StringBuilder

When you alter the values of String new object is formed so String is immutable

If you alter the values in StringBuidler no new object is formed so StringBuilder is mutable   

Example Code Snippet : String is Immutable

public class ImmutableString{ 

 public static void main(String args[]){ 

   String s="Some text" ;

   s.concat("Another Text");

   System.out.println(s); 

 } 

Output:

Sometext

Example Code Snippet : StringBuilder is mutable

public class MutableString

{

    public static void main (String[] args)

    {

        StringBuffer str1 = new StringBuffer("Java");

        StringBuilder str2 = new StringBuilder("Demo");

       

        System.out.println("Value of str1 before change :" + str1);

        System.out.println("Value of str2 before change :" + str2);

       

        str1.append(" Some text");

        str2.append(" Another text");

       

        System.out.println("Value of str1 after change :" + str1);

        System.out.println("Value of str2 after change :" + str2);

    }

}


Output:

Value of str1 before change :Java

Value of str2 before change :Demo

Value of str1 after change :JavaSome text

Value of str2 after change :DemoAnother text

4. What are the different types of exceptions in java?

Java Exceptions are broadly categorized into Checked and Un Checked exceptions.

Checked exceptions are checked during compile time, Unchecked exceptions are thrown during run time.

Consider if you are using eclipse IDE, checked exceptions are shown instantly inside your IDE, however, Unchecked exceptions are thrown only when you execute the program

Example of Checked Exception: Eclipse IDE (For your Reference Only)

Example : Unchecked Exception

public class UnCheckedException

{

    public static void main (String[] args)

    {

      int a=10;

      int b = a/0;

    }

}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

   at UnCheckedException.main(UnCheckedException.java:6)

5. Can we have a Single Catch Block and Multiple Try block?

  • We can have single or multiple catch blocks associated with the try block
  • We cannot have multiple try blocks, there can be only one try block before catch/finally block
  • You can have try block inside try block followed by the catch block

Important!: Below code doesn’t Execute

Example : Multiple try block at the same level

//INVALID, this throws Error

public class TryCatchExample {

    public static void main(String[] args) {

          try {

                int a = 10;

                int b = a / 0;

          }

          try {

               

          }

          catch (ArithmeticException e) {

          }

    }

}

Example : try inside try block, Below code is correct example, Try inside try block is valid

//Completely Valid Example try insdie try block

public class TryCatchExample {

    public static void main(String[] args) {

          try {

                try { //nested try

                      int a = 10;

                      int b = a / 0;

                } catch (Exception e) {

                     

                }

          }

          catch (ArithmeticException e) {

          }

    }

}

6. Can we have try block without catch block? How do you handle multiple exception with single try block?

Yes, we can have try block without catch block, in that case we need to have finally block associated with try block.

Example Code Snippet : try without catch block and having finally block

//Completely Valid Example try without catch but with finally

public class TryCatchFinallyExample {

    public static void main(String[] args) {

          try {

                      int a = 10;

                      int b = a / 0;

          }

          finally {

                System.out.println("Finally Executed");

          }

    }

}

Example Code Snippet : Multiple Exception can be handled with multiple catch block, and single try block

public class MultipleExceptionHandling {

    public static void main(String[] args) {

          try {

                int a[] = new int[15];

                a[15] = 99 / 0;

          } catch (ArithmeticException e) {

                System.out.println("Arithmetic Exception");

          } catch (ArrayIndexOutOfBoundsException e) {

                System.out.println("ArrayIndexOutOfBounds Exception");

          } catch (Exception e) {

                System.out.println("Parent Exception");

          }

          System.out.println("Prints at the end");

    }

}

Output:

Arithmetic Exception

Prints at the end

7. Tell me the difference between == and .equals

== is operator and .equals is method

== is used for comparison for memory address. .equals is used for competition of value

Example Code Snippet

public class Demo{

    public static void main(String[] args)

    {

          String s1 = "Test";

          String s2 = "Test";

          String s3 = new String("Test");

          System.out.println(s1 == s2); // prints true

          System.out.println(s1 == s3); // prints false

          System.out.println(s1.equals(s2)); // prints true

          System.out.println(s1.equals(s3)); // prints true

    }

}

8. Tell me some helpful string methods in Java

  • charAt() : This method returns the character at the specified index (position)

Example Code Snippet

String string = "Academy";

char ch = string.charAt(1); // Returns c

  • concat(): Appends a string to the end of another string

Example Code Snippet

String string1 = "Rahul Shetty";

String string2 = " Academy";

String str = string1.concat(string2); //Returns Rahul Shetty Academy

  • contains(): Checks whether a string contains a sequence of characters

Example Code Snippet

String string2 = " Academy";

boolean bool = string2.contains("my"); //Returns true

  • equals(): Compares two strings. Returns true if the strings are equal, and false if not

Example Code Snippet

String string1 = "Tiger";

String string2 = "Tiger";

boolean bool = string1.equals(string2);//Returns true

Example Code Snippet

String string1 = "TiGer";

String string2 = "TigeR";

boolean bool = string1.equalsIgnoreCase(string2);//Returns true

  • indexOf(): Returns the position of the first found occurrence of specified characters in a string

Example Code Snippet

String string2 = "Academy";

int index = string2.indexOf("my"); //Returns 5

  • length(): Returns the length of a specified string

Example Code Snippet

String string = "Academy";

int l = string.length(); //Returns 7

  • isEmpty(): Checks whether a string is empty or not

Example Code Snippet

String string = "";

boolean isEmpty = string.isEmpty(); //Returns true

  • replace(): Searches a string for a specified value, and returns a new string where the specified values are replaced

Example Code Snippet

String string = "Academy";

String newString = string.replace("my","-replacetest"); //Returns Acade-replacetest

  • replaceAll(): Replaces each substring of this string that matches the given regular expression with the given replacement

Example Code Snippet

String string = "academy";

String newString = string.replace("a","O"); //Returns OcOdemy

  • replaceFirst(): Replaces the first occurrence of a substring that matches the given regular expression with the given replacement

Example Code Snippet

String string = "academy";

String newString = string.replaceFirst("a","O"); //Returns Ocademy

  • split(): Splits a string into an array of substrings

Example Code Snippet

String string = "Rahul Shetty Academy";

String[] newString = string.split(" ");

// newString will have values like [Rahul, Shetty, Academy]

  • substring(): Returns a new string which is the substring of a specified string

Example Code Snippet

String string = "Rahul Shetty Academy";

String newString = string.substring(0,3); // Returns Rah

  • toCharArray(): Converts this string to a new character array

Example Code Snippet

String string = "Academy";

char[] charArray = string.toCharArray();

//charArray will have values like ['A','c','a','d','e','m','y']    

  • toLowerCase() : Converts a string to lower case letters

Example Code Snippet

String string = "AcAdEmY";

String newString = string.toLowerCase(); // Returns academy

  • toUpperCase() : Converts a string to upper case letters

Example Code Snippet

String string = "AcAdEmY";

String newString = string.toUpperCase(); // Returns ACADEMY

  • trim(): Removes whitespace from both ends of a string

Example Code Snippet

String string = "           Academy       ";

String newString = string.trim(); // Returns Academy

9. Why should avoid static methods in Java? Explain

A static method can be choose based on the requirement, as static method comes with its pros and cons.

A static method belongs to class not to instance

A static method cannot be overridden

A non-static method cannot be called inside a static method

A static method cannot refer to “this” or “super” keywords in any way

Considering above, with the static method we cannot fully utilize the Object-Oriented Feature, so it is good practice to avoid static methods, however, there might be cases we might need to use the static method intentionally then we can go for the static method.

10. How can I use the thread concept in Java, Explain two types

Threads can be implemented using two ways in Java,

  • Extending Thread class
  • Implementing Runnable interface

Example Code Snippet: Extending Thread class

public class Multi extends Thread {

    public void run() {

          System.out.println("Started...");

    }

    public static void main(String args[]) {

          Multi t1 = new Multi();

          t1.start();

    }

}

Example Code Snippet: Implementing Runnable interface

public class MultiT implements Runnable {

    public void run() {

          System.out.println("Started...");

    }

    public static void main(String args[]) {

          MultiT m1 = new MultiT();

          Thread t1 = new Thread(m1);

          t1.start();

    }

}

Note: In the above example, we are implementing a Runnable interface so, Class object is not treated as a thread, we need to create the Thread class explicitly passing the class object as a parameter to the constructor.

Course Alert

If you are interested in landing a SDET or Sr. QA Automation Engineer role, check out our popular SDET course to learn the fundamental skills required an SDET needs to perform at work. Also, I have another popular course which covers Top 150+ Interview questions most commonly asked in SDET / Automation interviews.

A Quick Note

Please remember all these courses comes with 100% Lifetime access and free updates for Lifetime!!

Please click on the link Sr.QA and SDET Interview Questions in Java – Part 3 to continue to part-3 series of this article.


Tags


You may also like

Groups attribute in TestNG 

Groups attribute in TestNG 
Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}