Site icon SAP CX Expert

Java Interview Q&A

Advertisements

Q. What is a class?

Ans. A class is a blueprint or prototype from which objects are created. A class models the state and behaviour of real world object.

Q. What is an object?

Ans. Object is an instance of class that stores its state in fields(variables) and exposes its behaviour through methods(functions). Methods operate on an object’s internal state and serve as the primary mechanism for object-to-object communication.

Q. What is data encapsulation?

Ans. Data encapsulation is a fundamental principle of object-oriented programming. It is a mechanism to hide internal state and ensures that all interaction are performed through an object’s method.

Q. Explain different types of variable in Java.

Ans. In java field or variable is used to store state of an object. The Java programming language defines the following four kinds of variable.

Q. What is inheritance in java?

Ans. Inheritance is an important feature of Object-oriented programming which allows classes to inherit commonly used state and behaviour from other class called base class or superclass using the keyword extends.

In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

Q. What is interface?

Ans. An interface is an abstract type in Java that contains a collection of methods and constants. It is one of the core concepts in Java used to achieve abstraction, polymorphism, and multiple inheritance. An interface is defined using interface keyword.

Q. How to create and send zip file as attachment in HTTP Response without creating file physically in hard drive?

Ans. Suppose the data that needs to be sent in HTTP response is in StringBuffer, then we can use following code snippet.

final StringBuffer stringBuffer = new StringBuffer().append("response data ................");
try{
    // response is instance of HttpServletResponse
    final OutputStream stream = response.getOutputStream(); 
    ZipOutputStream zos = new ZipOutputStream(stream);
    String fileName = String.format("%s_%s.fileExtensionName", "fileName", 
                      System.currentTimeMillis());

    String zipFileName = String.format("%s_%s.zip", "fileName", 
                         System.currentTimeMillis());

     ZipEntry entry = new ZipEntry(fileName);
     zos.putNextEntry(entry);
     zos.write(buffer.toString().getBytes());
     zos.flush();
     zos.closeEntry();
     zos.close();
     response.setContentType("application/zip");
     response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);   
}catch (){
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
Exit mobile version