Showing posts with label QA jobs. Show all posts
Showing posts with label QA jobs. Show all posts

QA Interview: Top 40: TestNG Interview Questions for QA

Other Useful Links:


1. What is TestNG?

  • NG stands for Next Generation, and TestNG is an automation testing framework.
  • Junit, which makes use of annotations, inspired TestNG.
  • TestNG is aimed to make end-to-end testing simple and addresses the shortcomings of Junit.


2. What are the advantages of TestNG?
  • It is simple to set up because it is an open-source framework.
  • It can generate the report in proper format, including the number of test cases run, pass, failed, skipped.
  • We may develop test cases in a methodical way using TestNG.
  • There is no need for a static main() method as the sequence is regulated by annotations that do not require the method to be static.
  • It gives lots of annotations which are easy to understand and use.
  • Priorities and execution sequences for tests can be established using TestNG.
  • Multiple test cases can be grouped easily.
  • Using the keyword 'invocation count,' the same test case can be run numerous times without loops.
  • Data parameterization is possible using TestNG.
  • You may easily link the TestNG framework with other technologies like Maven, Jenkins, and others.
  • TestNG makes it possible for test methods to rely on one another. It's also called Test Dependency in TestNG.
  • TestNG has a feature that allows you to run several test methods on different browsers to see if your website is cross-browser compatible. 
  • For more efficient testing, TestNG includes a number of assertion methods.
  • Uncaught exceptions are handled by TestNG.

3. How is TestNG different from Selenium WebDriver?
  • Selenium is a web automation tool that allows us to automate online applications.
  • Selenium is combined with TestNG to offer testing capabilities to Test Automation suites. With TestNG, we can include capabilities such as different types of assertions, reporting, parallel execution, and parameterization in our automation suite.
  • In short, Selenium assists with 'automation' and TestNG assists with 'testing' skills while performing Automation Testing.

4. What are some advantages of TestNG over JUnit?

  1. TestNG creates easily understandable HTML test reports.
  2. In contrast to JUnit, test methods can be simply grouped and prioritized.
  3. For developing test cases, TestNG annotations are simple to grasp.
  4. We can run many test cases in parallel with TestNG to reduce execution time.
  5. We can define how one test method is dependent on another using TestNG.
  6. TestNG doesn’t need to extend any class.
  7. @Before/After Suite, @Before/After Test, and @Before/After Group are three new annotations supported by TestNG.


5. What annotations are utilised in TestNG?
  • Precondition annotations: Annotations that are executed before test methods are executed are known as precondition annotations. @BeforeSuite, @BeforeClass, @BeforeTest, and @BeforeMethod are the precondition annotations.
  • Test annotation: The test annotation is supplied before the test method is defined. It is specified as @Test.
  • postcondition annotations: @AfterSuite, @AfterClass, @AfterTest, and @AfterMethod are examples of postcondition annotations.

6. What is the sequence of execution of the annotations in TestNG?

The following is the order in which the annotations are executed:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@Aftertest
@AfterSuite

             

7. How to set priorities in TestNG?

In every class, there are multiple tests or methods. If these tests or methods are not prioritized, they are selected alphabetically and executed during execution.

We must set the priority along with the @Test annotation if we want the tests to execute in the order we wish.

Example:
@Test (priority=2)
public void getText(){
driver.findElement(By.id(“id”)).getText();
}

@Test(priority=1)
public void clickelement(){
driver.findElement(By.id(“id”)).click();
}

Because the priority is set to 1, clickelement() will be run first in the previous example. Because the priority of getText() is set to 2, it will be executed after clickelement().

8. What happens if we don't give the TestNG method priority?

  • Then, they will execute in alphabetical order.


9. What will happen if two methods have the same priority?

  • Then, they will execute in alphabetical order.


10. Can we assign negative priority?

  • Yes, priority can be negative, zero or positive.


11. Can one method have multiple priorities?

  • No. One method can have only one priority.


12. Can priority pass through XML files?

  • No. We cannot pass priority through XML files?


13. In TestNG, what is the default priority of test cases?

  • When a test's priority is not provided, it defaults to the numeric value 0.
  • So, if we have one test case with priority 1 and another with no priority, the test with no priority value will run first. (default priority=0)


14. What is a dependency on TestNG?
  • Many methods are dependent on certain methods.
  • For example, if we want to test an application and the login page is down, we won't be able to test the other scenarios. Many tests rely on LoginTest.
  • Hence, we will write as follows:
        @Test(dependsOnMethods=”LoginTest”)
            Public void homePageLaunched(){
                // code 
            }

The given code demonstrates that the LoginTest() method is fully reliant on the homePageLaunched() method.

15. What is @Test Annotation in TestNG?
  • The @Test annotation in TestNG is a simple annotation that designates a method as a test method.
  • The @Test annotation on the test method informs TestNG that it is a "test" that should be run when the user runs the class.

16. What are the attributes supported by @Test annotation in TestNG?
  • alwaysRun, dataProvider, dataProviderClass, dependsOnGroups, dependsOnMethods, enabled, priority, timeOut, and others are some of the significant attributes provided by Test annotation.

17. Which attribute is used to run test method always?
  • The @Test annotation's "alwaysRun" feature is used to always run test methods. It accepts a true or false value. If true is set, this function will always run, even if the method it depends on fails.
  • Syntax: @Test(alwaysRun = true)

18. How can we run a Test method multiple times without using for loop?
  • The test method is made to run n times in a loop by using the invocationCount parameter and setting its value to an integer value.
        @Test(invocationCount = 10)
            public void invocationCountTest(){
               //Test logic
            }

19. How will you define grouping in TestNG?
  • The groups attribute in TestNG can be used to specify grouping as illustrated below:
        @Test(groups=”title”)

20. What is timeOut in TestNG?

We can use "timeout" in TestNG to terminate any method in the script that takes a long time to execute.

@Test(timeout = 3000)
The method will be ended at 3000 milliseconds (3 seconds) in this scenario, and the test case will be reported as "Failed."

        


Next: Top 40: TestNG Interview Questions for QA (21-40)


Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyush23agr@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - Youtube

Happy to Help You !!





QA Interview: Top 40: Most Frequently Asked API Testing Interview Questions

Other Useful Links:

      


1. What is API?

  • API stands for Application Programming Interface. 
  • API serves as a bridge between two software applications, allowing them to connect with one another.
  • API refers to a set of software functions that can be used by another program.
  • Google Maps API, Amazon Advertising API, Twitter API, and YouTube API are other examples.


2. How do APIs work?
  • An API's general workflow is to take a request, process it (which may include data validation, database interaction, and data processing), and then return the output to the source.
  • Because APIs are not exposed to the outside world, they provide an abstraction for internal business logic.

3. What is API Testing?
  • API testing is a sort of software testing in which APIs are directly tested.
  • It's part of integration testing to see if the API fits the application's requirements for functionality, stability, performance, and security.
  • Our main focus in API testing will be on the software architecture's business logic layer.
  • Any software system with various APIs can be subjected to API testing.

4. What are the advantages of API Testing?
  • Test for Core Functionality:
    • API testing allows you to access the application without having to use the user interface.
    • Before the GUI tests, the application's core and code-level functionality will be tested and reviewed.
    • This will aid in the detection of minor flaws that could become more serious during the GUI testing.
  • Time Effective:
    • Testing APIs takes far less time than testing functional GUIs.
    • In GUI testing, web items must be polled, which slows down the process.
    • API test automation, in particular, needs less code and hence provides better and faster test coverage than GUI test automation. As a result, the testing project will be less expensive.
  • Language-Independent:
    • Data is transmitted using XML or JSON during API testing. These transfer modalities are totally language-independent, allowing customers to use any programming language when using automated testing services.
  • Easy Integration with GUI:
    • API tests allow for highly integrable tests, which is especially beneficial if you wish to run functional GUI tests following API testing.
    • Simple integration, for example, would allow for the creation of new user accounts within the programme prior to the commencement of a GUI test.

5. What are the most commonly used tools for API testing?
  • PostMan is the most widely utilised tool on the market. This tool helps to create manual and automated test cases for testing the APIs in a well-designed manner.
  • Aside from that, there are several tools such as JMeter, Parasoft SOAtest, SoapUI, Apigee, API Fortress, JUnit, and so on.

6. What should be validated during API testing?
  • We'll double-check the data's accuracy.
  • Will see the HTTP status code.
  • We will see the response time.
  • Error codes if API returns any errors.
  • Authorization would be checked.
  • Non-Functional testing like performance testing, security testing.

7. What are the API testing protocols?
Protocols used in API testing are:
  • HTTP
  • REST
  • SOAP
  • JMS
  • UDDI

8. What components make up an HTTP request?

An HTTP request has five components. These are:
  • HTTP method like GET, PUT, POST, DELETE.
  • Uniform Resource Identifier (URI): URI is the identifier for the resource on the server.
  • HTTP version: Give the HTTP version, such as HTTP V1.1.
  • Request Header: The HTTP request message's metadata is carried in the Request Header. A client's type, supported formats, message content format, cache setting, and so on are all examples of metadata.
  • Request Body: The message body or resource representation is indicated by the resource body.

9. What is the HTTP protocol supported by REST?
  • GET: The GET method is used to request data from a given resource. It is saved in the browser history and is limited in length. GET requests should not be utilised when dealing with sensitive data.
  • POST:POST is a method of sending data to a server for the purpose of creating or updating resources. POST requests are never cached or bookmarked.
  • PUT: PUT updates the target resource's current representation with the request payload.
  • DELETE: DELETE removes the specified resource.
  • OPTIONS: The communication option for the target resources is described by the term OPTION.
  • HEAD: HEAD requests the same response as GET requests, but without the response body.


10. What are the major challenges faced during API testing?
  • Parameter Selection
  • Parameter Combination
  • Call sequencing
  • Output verification and validation
  • Providing input values, which is difficult because there is no GUI, is a huge challenge.

11. Why is API testing considered as the most suitable form for Automation testing?

API testing is now preferable over GUI testing because:
  • It effectively verifies all of the functional routes of the system under test.
  • It provides the most stable interface.
  • It's simpler to manage and gives immediate response.

12. List a few authentication techniques used in API testing.
  • Session / Cookies based Authentication
  • Basic Authentication
  • Digest Authentication
  • OAuth

13. State the common status code you encounter in API testing
  • 200 OK: Success
  • 201 Created: In the database, the value associated with the request has been created.
  • 204 No Content: This status code indicates that the request was received correctly, but that the server has no response to deliver to the client.
  • 400 Bad Request: A bad request has inappropriate syntax. If you supplied the improper parameters with the request URL or in the body of the request, this can happen.
  • 401 Authorized: When you are not authorised to access the server or have entered incorrect credentials, we may receive this status code.
  • 403 Forbidden: Because the client does not have access to the content and is therefore unauthorised, the server refuses to provide the requested resource.
  • 404 Not Found: A 404 response code indicates that the server was connected but was unable to locate the information requested.
  • 422 Unprocessable Entity: Due to semantic issues, the request could not be followed.
  • 500 Internal Server Error: A response code of 500 indicates that the server encountered an error while processing the request.
  • 501 Not Implemented: The server does not support the request method and cannot process it.
  • 502 Bad Gateway: In attempting to complete the request, the server received an incorrect answer from the upstream server it accessed.
  • 503 Service Unavailable: Due to temporary overloading or server maintenance, the server is currently unable to handle the request.
  • 504 Gateway Timeout: The server failed to receive a timely response from the upstream server specified by the URI while functioning as a gateway or proxy.

14. How do API testing and UI testing differ?
  • The testing of the graphical user interface is known as UI (User Interface) testing. The look and feel of the application is the focus of UI testing. The main focus of user interface testing is on how people interact with app features such as graphics, typefaces, and layout.
  • API testing allows two software systems to communicate with each other. API testing, often known as backend testing, is performed on the backend.

15. What is SOAP?
  • It's an XML-based protocol for data transfer between computers.

16. What is the REST API?
  • REST API is a set of functions that helps the developers perform requests when the response is received. In the REST API, interactions are made using the HTTP protocol. REST is defined as Representational state transfer. It is a useful standard for developing APIs.

17. What is the most popular way to represent a resource in REST?
  • To define a resource, REST uses several forms such as text, JSON, and XML.
  • The most prevalent resource representations are XML and JSON.

18. Can we create a resource using GET requests instead of PUT?
  • To build a resource, use the PUT or POST method.
  • The GET technique is solely for resource requests.

19. Which purpose does the OPTIONS method serve for the RESTful Web services?
  • The OPTIONS method returns a list of all the operations that a web service can perform.


20.What is Payload?
  • In the case of REST APIs, the most commonly used term is payload. It is the actual data delivered to the server in the API request in various formats such as JSON, XML, and so on.

Next: Top 40: Most Frequently Asked API Testing Interview Questions (21-40)


Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyushagrawal.automation@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - Youtube

Happy to Help You !!

QA Interview: Top 100: Java Interview Questions for QA

Other useful Links:
         


1. What is Java and explain features of java.

  • Java is high-level, object-oriented, secure, platform independent, robust, high performance and portable programming language.
  • James Gosling - 1991.
  • It is also known as Platform as it provides its own JRE and API.

Simple:

  • Java is a straightforward, clean, and easy-to-understand language. It is simple because:
  • Java syntax is based on C++, so it is easier for programmers to learn it after C++.
  • Explicit pointers and operator overloading, among other features, have been removed from Java.
  • Automatic Garbage Collection in Java.

Object-oriented:

  • Java is an object-oriented programming language. Everything in Java is an object. 
  • Object-oriented software is made up of a variety of distinct types of objects that include both data and behavior.

Platform Independent:

  • Java comes with its own platform for executing its code.
  • Java doesn't depend upon any operating system to be executed.

Portable:

  • Java is Write Once and Run Anywhere.
  • Java program (.java) converted into byte code(.class) which can easily run on any machine.

Secured:

  • Because it does not use explicit pointers, Java is safe.
  • Java also provides the concept of bytecode and exception handling which make it more secured.

Robust:

  • Java is a powerful programming language because it makes extensive use of memory management.
  • The concepts like automatic garbage collection, exception handling make it more robust.

Architecture-neutral:

  • Java is architecture neutral because it has no implementation-dependent features, such as the size of primitive types.
  • The int data type occupies two bytes in 32-bit architecture and four bytes in 64-bit architecture in C programming. In Java, however, it takes up 4 bytes of memory on both 32 and 64-bit platforms.

Interpreted:

  • Java uses a JIT interpreter along with the compiler for program execution.

High-performance:

  • Java bytecode is faster than other traditional interpreted programming languages since it is "near" native code.

Multi-threaded:

  • The primary advantage of multi-threading is that each thread consumes no memory. It shares a common memory area.

Dynamic:

  • Java is a dynamic language. It supports the dynamic loading of classes. This means that classes are loaded as needed.

Distributed:

  • Java is distributed because it makes it easy for users to construct distributed Java applications. Distributed applications are built using RMI and EJB.
  • This Java feature allows us to access files from any system connected to the internet by calling methods.


2. Is java pure object oriented?

  • Java is not a pure Object Oriented Language because it supports primitive data types such as byte, boolean, char, double, float, int, long, short.
  • These primitive data types are not object oriented. This is the reason why Java is not a 100% object-oriented language.


3. Can class be declared as protected?
  • No, only methods can be declared as protected.

4. Can source file contain more than one class declaration?
  • Yes. Source file can contain any number of class declarations but only one class can be declared as public.

5. What is JRE and why do I need it?

  • JRE stands for “Java Runtime Environment”. The Java Virtual Machine (JVM), Java platform classes, and support libraries are all part of it.
  • Only previously written apps can be run with JRE. We are unable to create new apps or make changes to existing ones.
  • As the name suggests, JRE only provides a Runtime Environment.


6. What is JDK and why does it need to be installed?

  • JDK stands for Java Development Kit. It's a JRE superset.
  • We can use JDK to create, compile, and execute (run) new programmes as well as modify old ones.
  • JDK contains JRE as well as development tools (environment to develop, debug and monitor Java programs).


7. What is the JVM and why is it necessary?

  • JVM stands for Java Virtual Machine. JVM drives the java code.
  • We can run Java byte code by translating it to the current OS machine language using JVM.
  • It turns Java into a portable language (write once, run anywhere)


8. Explain public static void main (String[] args)

  • The main() is where every Java program begins. JVM always looks for this method signature to start running an application.
  • public static void main(string[] args) can also be written as public static void main(String args[]). Don’t get confused.
public:
  • public is an access modifier. The scope of public access modifiers is everywhere.
  • It has no restrictions. Declared public data members, methods, and classes can be accessible from anywhere.
  • If you make a main() method public then it is allowed to be executed by any program globally.
  • If you make a main() method non-public then it is not allowed to be executed by any program.
static:
  • To access the main method, the JVM cannot build a class object at runtime. By declaring the main() method as static, JVM can invoke it without instantiating the class.
  • JVM will not be able to call the main method to run the program if it is not declared as static.
void:
  • The term "void" refers to a method that returns no value.
  • Every method in Java specifies the return type.
  • In Java, the main method does not return anything.
  • Java program starts with the main method and terminates once the main method is finished executing.
  • If we make the main method return a value, JVM will be unable to do anything with it. As a result, no value must be returned.
main:
  • main is the name of Java main method. When you compile and run a Java program, it is the first thing that runs.
  • JVM looks for the main method to start the execution of a Java program.
String[] args:
  • String[] args is a parameter that accepts inputs. The name of the String array is ‘args‘ but it can be of anything based on users choice.
  • The type of args is always String[] because Java's main method accepts only a single argument of the type String array.
  • We can change the array name to whatever and it will still work. i.e. String[] xyz or String[] abc


9. How many types of memory are allocated by JVM?

  • Heap - whenever an object is created.
  • Class area
  • Static
  • Native method stack.
  • Program counter register

10. What is a platform?

  • Platform is a set of hardware and software environments on which pieces of software are executed.
  • Java is a software based platform.



11. JIT compiler


At compile Time                    At Runtime

Source code . java → compiler → Bytecode → JIT compiler → Native Machine Code

  • The Java Runtime Environment (JRE) is responsible for executing source code and it contains a JIT compiler that does the performance optimization.
  • It converts the bytecode into native machine code at runtime.


12. What gives Java its ‘Write Once Run Anywhere’ nature?

  • The bytecode - Java compiler converts java source code file into byte code which is intermediate language between source code and machine code. 
  • The bytecode is not platform specific and can be executed on any machine.


13. Is the empty .java file name valid?

  • Yes.

        Class A {

             // code

        }


To compile: javac .java

To run: java A


14. Which OOPs Concepts you used in your current project?

1. Inheritance

We establish a Base Class in a standard Page Object Model to initialise the WebDriver interface, Data Source, Excel Reader, Property File or Config File, WebDriver waits, and so on. We extend the Base Class in our Test Class and Utility Class.We do it by using the extends keyword and achieve the Inheritance. This makes the class more reusable, as we won't have to repeat the startup code.

2. Encapsulation

We know that in a POM Project, we construct a distinct class for each page. All of these classes are excellent examples of encapsulation, in which the data of one class is kept separate from that of another. We declare the data members using @FindBy and initialise them using a constructor with initElement() to utilize them in the test methods.

3. Polymorphism

Polymorphism is based on the idea of a single interface that supports numerous methods. WebDriver is a browser interface that supports several methods such as ChromeDriver(), IEDriver(), SafariDriver(), and FirefoxDriver().

Method Overloading In Selenium

  • Methods Overloading is the process of employing two methods with the same name but different parameters in the same class.
  • We now use Implicit Wait in Selenium to have the page wait for a set amount of time.
  • Because we may supply different Timestamps or TimeUnits like SECONDS, MINUTES, and so on, this is the ideal example of Method Overloading.

Method Overriding In Selenium

  • In the WebDriver interface, we use two different methods for navigating or accessing any website i.e. driver.get() and driver.navigate().to().
  • These two methods are examples of Method Overriding.

15. Abstraction vs Encapsulation

Abstraction

Encapsulation

Abstraction solves the problem at design level.

Encapsulation solves the problem at implementation level.

Abstraction is used to hide unnecessary material while presenting relevant information.

To secure data from the outside world, encapsulation involves combining code and data into a single unit.

Abstraction allows you to focus on the object's function rather than how it functions.

Encapsulation refers to the process of hiding the internal details or mechanics of how an object works.

For instance, the appearance of a television, which has a display screen and channel buttons for changing channels, explains Abstraction

However, the inner implementation detail of a television explains Encapsulation by showing how the CRT and Display Screen are connected using separate circuits.


16. Compile-time Polymorphism vs Runtime Polymorphism


Compile-time Polymorphism

Runtime Polymorphism

Compile-time Polymorphism means binding is done at compile time.

Runtime Polymorphism means binding is done at Runtime.

Inheritance is not involved.

Inheritance is involved.

Method Overloading.

Method Overriding.

It provides fast execution.

It provides slower execution as compared to CTP.

Less flexible because all things are resolved at compile time.

More Flexible as all things are resolved at runtime.

17. Method Overloading vs Method Overriding

Method Overloading

Method Overriding

Method Overloading relates to Compile-time Polymorphism. 

Method Overriding relates to Runtime Polymorphism.

It helps to increase readability of the program.

It helps to grant the specific implementation of a method which is already provided by the parent class.

It can occur within the class.

It is divided into two classes, each of which has an inheritance relationship.

Method Overloading might or might not need inheritance.

Method Overriding always needs inheritance.

Methods must share the same name but have distinct signatures.

The names and signatures of methods must be the same.

The return type can be the same or distinct.

Return type must be the same.


18. What is the default value of the local variable?

  • Local variables are not initialized to any value, not primitive or object references.


19. What is the initial value of Object reference which is defined as an instance variable?

  • All object references are initialized to null.


20. What are different access specifiers in java?
  • Private: If a variable is designated private, it can only be accessed by other members of the class. Outside of the class, this variable will be unavailable. As a result, outside members are unable to access private members.
  • Public: Methods/variables with public modifiers can be accessed by all the other classes in the project.
  • Default: If a variable/method is defined without any access modifier keyword, then that will have a default modifier access.
  • Protected: If a variable is declared as protected, then it can be accessed within the same package classes and subclass of any other packages.


21. When to use interfaces and when to use abstract classes?


Abstract classes:

  • The abstract class is a good choice if you want common base class implementation to all derived classes.
  • It is a good choice if you want to use non-public members because in an interface all members must be public.
  • If we want to add a new method in future then abstract class is a good choice because if we add a new method to the interface then all the classes that implemented this interface need to implement a new method.
  • Abstract classes have an advantage of better forward compatibility. Once a client uses the interface, we can still add new behavior without breaking existing code.

Interfaces: 

  • Interfaces are a good choice when we think API’s will not change for a while.
  • If we are using a small concise bit of functionality, use interfaces. If we are designing large functional units, use abstract classes. 
  • We want to use things similar to multiple inheritance.


22. Abstract Class vs Interface

Abstract Class 

Interface

Both abstract and non-abstract methods are possible in abstract classes.

Interfaces can only have abstract methods.

Abstract classes can have static, non-static, final, non-final variables.

Interfaces can have only static and final variables.

“abstract” keyword is used to declare abstract classes.

The keyword "interface" defines an interface.

Abstract class doesn’t support multiple inheritance.

Interface supports multiple inheritance.

Abstract class provides implementation of interface.

Interface can’t provide implementation of abstract class

An abstract class can inherit from another abstract class and implement interfaces.

Interface can extend another java interface only.

'extends' keyword can be used to extend an abstract class.

Interface can be implemented using ‘implements’ keyword.

Members of abstract classes can be public, private and protected.

Members of interfaces are by default public.

Example:

public abstract class Shape{

public abstract void draw();

} 

Example:

public interface Drawable{

void draw();

}


23. What is the purpose of static methods and variables in Java?

  • The methods or variables that are defined as static are shared among all the objects of the class.
  • The static is a part of a class and not the objects.
  • The static variables are defined in the class area and we don't need to create an object of the class to access such variables.


24. What are the advantages of packages in Java?
  • Packages avoid name clashes.
  • Packages provide easier access control.
  • We can have classes accessed only within the package.

25. What is a Constructor?

  • Constructor is a special type of method that has the same name as the class name and is used to initialize the state of an object.
  • Every time an object is created using a new keyword, default constructor is called.
  • It must not return any explicit value.


26. How many types of constructor are used in java?

  • Default Constructor and parameterized constructor.


27. What is the purpose of the default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.


class Student{

int id;

String name;

Student_Info(){

            System.out.println(id+” ”+name);

}


Public static void main(String[] args){

Student s1 = new Student();

Student s2 = new Student();

s1.Student_Info();

     s2.Student_Info();

}

}


Output:

0 null

0 null


28. Does the constructor return any value?

  • Instance of a class


29. Can constructor be inherited?

  • No


30. Can constructor be overridden?

  • No



31. Can you make the constructor final?

  • No, constructor can never be declared as final because it is never inherited.
  • If you try to do so it will throw a compile-time error.


32. Can constructor be overloaded?


Yes, by changing the number of arguments or by changing data types of arguments.

class Test{
int i;
public Test(int k){
    i=k;
    System.out.println(i);
        }

        public Test(int k,int m){
    i=k+1;
    m=k+2;
    System.out.println(i);
    System.out.println(m);
        }
}

class Main{
public static void main(String[] args){
    Test t1 = new Test(10);
    Test t2 = new Test(10,20);
        }
}

Output:
10
11
12

33. Can we use this and super in a constructor?
  • No

34. Constructor vs Method

Constructor

Method

Constructor is a block of code that sets up a newly created object.

Method is a collection of statements which returns value upon execution.

Constructors are used to initialize the object.

Method contains java code to be executed.

Constructor name must match the class name.

Method names can be anything.

Constructor doesn’t not have a return type.

Method must have a return type.

Constructor cannot be inherited by subclasses.

Methods can be inherited by subclasses.

Constructor is initialized when an object is created.

Methods need to be called explicitly.


35. Static Variables and Static Methods

  • The term "static variable" refers to the property that all objects share.
  • Static methods belong to class rather than objects.
  • It can be called using class names. Static variables can be accessed and changed by static methods.


36. What are the restrictions applied to java static methods

  • Static methods cannot use non-static variables or call non-static methods directly.
  • Because this and super are non-static, they can't be utilised in a static context.


37. Why is the main method static?

  • Because objects are not required to call the static method.
  • If we make java main method non-static then JVM will have to create an object first and then call main method which will lead to extra memory allocation.


38. Can we override the static method?

  • No


39. Can we overload the static method?

  • Yes.

class Test1 {

    static void display(int a){

        System.out.println(a);

    }

}


class Test2{

    static void display(int a,int b){

        System.out.println(a+" "+b);

}

    

public static void main(String[] args){

        Test1.display(10);

        Test2.display(10,20);

    }

}


Output:

10

10 20


40. Can we make the constructor static?

  • Constructor is invoked when an object is created. If we try to make the constructor static, it will throw a compiler error.


41. Can we override the overloaded methods?

  • Yes


42. Can we override the private methods?

  • No. Because the scope of private methods is limited to the class and we cannot access them outside of scope.


43. Can we change the scope of the overridden method in subclass?

Yes, We can change the scope of a method in a subclass. But, we cannot decrease the accessibility.

  • Private: Private can be changed to public, private, protected.
  • default: default can be changed to public.
  • protected: Protected can be changed to public and default.
  • public: public will remain public.


44. Can we execute a java program without the main() method?

  • It is possible before JDK 1.7. Since JDK 1.7 it is not possible.


45. Can we make abstract methods static?

  • No.
  • In Java, if we declare an abstract method as static then it will become part of a class and we can call it directly which is unnecessary.
  • Calling undefined method is completely useless therefore it is not allowed.


46. Can we declare static methods and variables inside abstract class?

  • Yes


47. this vs super

this

super

The current instance of a class is represented by ‘this’ keyword.

The 'super' keyword represents the current instance of the parent class.

In order to call the default constructor of the current class, we can use the ‘this’ keyword.

In order to call the constructor of the parent class, we can use the ‘super’ keyword.

It can be invoked from a static context.

It can’t be invoked from the static context.

We can use it to access current class data members and member functions.

We can use it to access data members and member functions of parent class.


48. Which class is the superclass of all classes in java?

  • Object class


49. Why are pointers not used in Java?
  • Because pointers are unsafe and complex to understand.

50. Use of final variable
  • Stop value change.
  • Stop method overriding.
  • Stop inheritance.

        


Next: Java Interview Questions for QA (51-100)


Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyushagrawal.automation@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - Youtube

Happy to Help You !!