Java interview questions and answers


 1. Can a main() method of class be invoked in another class?
Ans: Yes it is possible only when main() class should be
declared as public and static.
here the example
  
     package r4r.co.in;
       class Newclass {                                    //this is main class called as Newclass
        public static void main(String args[])
       {
          System.out.println("this is mainclass");
      }
   }
        public class Invokedclass                    //this is subclass called as Invokedclass
    {
         public static void main(String args[]) {
             System.out.println("this is invokedclass which invoked Newclass");
                 Newclass.main(args);
             }
          }

     //save and compile the program by name of Invokedclass.java

     Result:
          this is invokedclass which invoked Newclass
          this is mainclass

 
2. What is the difference between java command line arguments and C command line arguments?
Ans: I
n C and C++, the system passes two arguments to a program: argc and argv. argc specifies the number of arguments stored in argv. argv is a pointer to an array of characters containing the actual arguments. In Java, the system passes a single value to a program: args. args is an array of Strings that contains the command-line arguments.

3. What is the difference between == & .equals().
Ans: The equals( ) method compares the characters inside a String object while the == operator compares two object references which refer to the same instance.
  Example
   
//Comparison of two Strings
    package r4r.co.in;

         class CompareStrings {

   
       public static void main(String args[]) {
       
       String s1 = new String("Hello");
       
      String s2 = new String("Hello");
       
  System.out.println(s1 + " equals " + s2 + " : "  + s1.equals(s2));
        
System.out.println(s1 + " == " + s2 + " : " + (s1 == s2));
   
   }
   }
 //save and compile the program by name of  CompareStrings.java

Result:
    
     Hello equals Hello : true
    
Hello == Hello : false
4. What is the difference between abstract class & Interface.
Ans: Any class that contains one or more abstract methods must be declared abstract by putting the abstract keyword in front of the class and at the beginning of the           class declaration, remember there is no objects of an abstract class. Abstract class method can't be overriding in a another class because an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined.
  Through the use of the interface keyword, Java allows to fully abstract the interface from its implementation. Interface is a concept work on sharing the data in superclass
 ( or Parent class) to subclass( or child class) ,but non of class define protected and abstract. The interface, itself, does not actually define any implementation.
5. What is singleton class & how you can implementation it?.
With the Singleton design pattern you can:
Ensure that only one instance of a class is created
Provide a global point of access to the object
Allow multiple instances in the future without affecting a singleton class's clients

//Sample Code
public class SingleInstance {
private static SingleInstance ourInstance = new SingleInstance();

public static SingleInstance getInstance() {
if(null==ourInstance){
ourInstance= new SingleInstance();
}
return ourInstance;
}
private SingleInstance() {
}


6. What is use of static, final variable?
Ans:  Any class which is declare to be static as use a keyword static. The example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist, while instance variables declared as static are used as global variables. Methods declared as static have several restrictions:
  •  They can only call other static methods.
  • They must only access static data not dynamic data.
  • They can't refer to this or super in any way.
  • As the program is compile static  member ,variable or class is loaded first than dynamic class.        
  A variable can be declared as final, class can't declare final means  a final variable must be initialize a final when it is declared. Final Variables don't occupy memory on
  per-instance basis. Hence, a final variable is must be constant.
7. Examples of final class.
Ans: Final class is only use for prevent a class from being inherited. By declaring a class as final as use final keyword in front of class implicitly declares all of its methods
 as final too. But, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and depend upon its subclasses to provide complete implementations.

  //Following example consider for final class
  package r4r.co.in;

   final class A {                  //following class should be declare to final can't be inheritance
      
int a = 5;                     //value which declare into int should be constant
   
  Float b = (float) 3.45
   }

  class B extends A {

   
public static void main(String[] args) {
   
}
  }
8. What is difference between Event propagation & Event delegation?
9. What is difference between Unicast & Multicast model?
UNICAST is 1-1.
MULTICAST is 1-M.
Unicast
Unicast is a one-to one connection between the client and the server. Unicast uses IP delivery methods such as Transmission Control Protocol (TCP) and User Datagram Protocol (UDP), which are session-based protocols. When a Windows Media Player client connects using unicast to a Windows Media server, that client has a direct relationship to the server. Each unicast client that connects to the server takes up additional bandwidth. For example, if you have 10 clients all playing 100-kilobits per second (Kbps) streams, those clients as a group are taking up 1,000 Kbps. If you have only one client playing the 100 Kbps stream, only 100 Kbps is being used.
Back to the top
Multicast
Multicast is a true broadcast. The multicast source relies on multicast-enabled routers to forward the packets to all client subnets that have clients listening. There is no direct relationship between the clients and Windows Media server. The Windows Media server generates an .nsc (NetShow channel) file when the multicast station is first created. Typically, the .nsc file is delivered to the client from a Web server. This file contains information that the Windows Media Player needs to listen for the multicast. This is similar to tuning into a station on a radio. Each client that listens to the multicast adds no additional overhead on the server. In fact, the server sends out only one stream per multicast station. The same load is experienced on the server whether only one client or 1,000 clients are listening

Important: Multicast on the Internet is generally not practical because only small sections of the Internet are multicast-enabled. Multicast in corporate environments where all routers are multicast-enabled can save quite a bit of bandwidth.

10. What is a java bean?
Ans:A Java Bean is a software component that is designed for the reusable in a variety of different environments and its architecture is totally based on a component which enables programmers to create software. Components are self-contained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. Also, a bean is use to perform a function like checking the spelling of a document, a complex function such as forecasting the performance of a stock portfolio. Beans expose properties so they can be customized at design time.
Customization is supported in two ways:
   -- by using property editors.
   -- by using more sophisticated bean customizers.
 


11. What is use of synchronized keyword?
Ans:The
synchronized keyword can be used for locking in program or utilize for lock/ free the resource for any thread/program. When two or more threads/program want
 to access a shared resource, they need someway to ensure that the resource will be use by only one thread at a time. The process by which this is achieved is called
synchronization.

   // Create multiple threads using synchronization method.
 package
r4r.co.in;

 class
MYThread implements Runnable {

   
String name;                                                            // name of thread
   
Thread t;                                                          

   
MYThread(String threadname) {
       
name = threadname;
       
t = new Thread(this, name);                                  
       
System.out.println("My thread: " + t);
       
t.start();                                                                // Thread Start for execution
   
}

    synchronized public void
run() {                                // Initialization of  thread.
        try
{
            for
(int i = 0; i < 10; i++) {
               
System.out.println(name + ": " + i);
             
Thread.sleep(100);                                      //thread sleep
           
}
       
} catch (Exception e) {
           
System.out.println(name + e);
       
}
       
System.out.println(name + " exiting.");
   
}
 }

 class
MultiThreadDemo {

    public static void
main(String args[]) {
        new
MYThread("One");                                              
        new
MYThread("Two");

        try
{

           
Thread.sleep(1000);                                                  // Thread sleep
       
} catch (InterruptedException e) {
           
System.out.println("Main thread Interrupted");
       
}
       
System.out.println("My thread exiting.");
   
}
}
  
12. What are the restrictions of an applet & how to make the applet access the local machines resources?
Ans:
Applet :
download from internet and then start execute. to avaid mis use of local machine resource many of access are restricted. for example

1. access event queue
2. access filesystem esp. for writing
3. create socket other host machine
4. create another process
5.etc

those can be relaxed by "policy" file which is located
JVM insallation directory

so, make entry to this policy file is only way now to allow applet access local file system
13. What is reflect package used for & the methods of it?
Ans: The java.lang.reflect.* package provides the ability to obtain information about the fields, constructors, methods, and modifiers of a class, also includes a class that    access arrays dynamically.

  //simple example consider for how reflection works,
  package r4r.co.in;

  import java.lang.reflect.*;

  public class Reflection {

    public static void main(String args[]) {
        try {
            Class c = Class.forName("java.lang.String");                    //
Here String is loaded class.


            Method m[] = c.getDeclaredMethods();                        // Here get method implemented
            System.out.println(m[0].toString());



            for (int i = 0; i < m.length; i++) {
                System.out.println(m[i].toString());
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
14. What is use of serialization?
Ans:The process of writing the state of an object to a byte stream is called serialization, also, it is used to save the program to persistent storage area, like a file and easily restore using Deserialization process.
15. Can methods be overloaded based on the return types ?
Ans: Java does not support return-type-based method overloading. Method can be overload either same name and same
signatures( argument/parameter).
16. Why do we need a finalize() method when Garbage Collection is there ?
Ans:
Before performing the garbage collection the JVM called the finalize() method to cleanup the resources such as closing the file or socket connection etc. The finalize() method is declared in the java.lang.Object class. When you implement the finalize method, you are actually overriding it from the Object class. Your finalize() method must be declared as follows: protected void finalize () throws throwable{ //some cleanup code here }
17. Difference between AWT and Swing components ?
Ans:AWT are heavy weight components while Swing are light weight components because AWT is platform dependent while Swing is not dependent any of the platform.
Alternate, AWT( heavyweight  component ) is one that is associated with its own  native screen resource (commonly known as a peer) while Swing( lightweight  component )
 is one that "borrows" the screen resource of an ancestor ( means it has no native resource of its own).
18. Is there any heavy weight component in Swings ?
Ans:
Yes, since all AWT components are heavyweight and all Swing  components are lightweight (except for the top-level ones: JWindow, JFrame,  JDialog, and JApplet), these differences apparent when start mixing Swing components with AWT components.
19. Can the Swing application if you upload in net, be compatible with your browser?
Ans: Yes. because Swing are platform independent independent
20. What should you do get your browser compatible with swing components?
Download Java Plugin for web browser. In Java SDK 1.3.1 onwards a plugin is automatically installed with web browser for supporting Swing components.


22. When is init(), start() called ?
Ans: Int() method is called by applet viewer or browser at the time of  load applet application into system while Start() method is called by the applet viewer or browser  at the time of when applet is complete loaded into system and start its execution.
23. When you navigate from one applet to another what are the methods called?
Ans:Applet can be navigate with other by appletcontext() method.
24. What is the difference between Trusted and Untrusted Applet ?
Ans: Java applets are typically executed by Web browsers with embedded Java Virtual Machines (VMs) and runtime class libraries. Applets are downloaded by the browser and then executed by the built-in VM on the machine running the browser. The security of the system depends upon the Java language itself, the runtime class libraries, and the Security Manager of the browser. Applets are of two types-
  • Trusted Applet:-Java virtual machines( JVM ) run applets under a different security regime( refers to a set of conditions) than applications. By default, applications are implicitly trusted. The designers of the JVM specification assumed that users start applications at their own initiative and can therefore take responsibility for the application's behavior on their machine. Such code is considered to be trusted.
     
  • Untrusted Applet-The applet which started automatically by the browser after it downloads and displays a page. Users can't be expected to know what applets a page might contain before they download it, and therefore cannot take responsibility for the applet's behavior on their machine. Applets, therefore, are considered by default to be untrusted.
25. What is Exception ?
Ans: An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error must be checked and handled manually. Exceptions can be generated by the
Java run-time system (or java virtual machine, JVM ), or they can be manually generated by your code.
   Exception is of two type-
      1. Check Exception or Compiletime Exception. An exception which generate by
programming error like user written  program or code and must be handle at time of compilation of program.
      1. Uncheck Exception or Runtime Exception. An exception which can generate at the runtime of program, the compiler doesn’t force the programmers to catch the exception.


26. What are the ways you can handle exception ?
Ans: When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Try block is used to  monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner. To manually throw an exception, use the keyword throw. Any code that must be executed before a method returns is put in a finally block.

   The following syntax represent exception handling
                  
        try  {                                                             
                          // block of code to monitor for errors         
         }

         catch (Exception exObject) {           
                          
// exception handler for ExceptionType1
              }
        
         finally {                      
                           
// block of code to be executed before try block ends
                  }
27. When is try, catch block used ?
Ans:Try block is used to  monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner.

The following syntax represent exception handling
                  
        try  {                                                             
                          // block of code to monitor for errors         
         }

         catch (Exception exObject) {           
                          
// exception handler for ExceptionType1
              }
        
 
28. What is finally method in Exceptions ?
Ans:  The finally method will be executed after a try or catch execution, and mainly used to free up resources. Any code that must be execute before a method returns is put in a finally block.
 
29. What are the types of access modifiers ?
Ans: In java four access modifier is used describe below-
Access Modifiers*
   Class
      Nested class
 Subclass
 Other packages

public
     Yes
        Yes
      Yes
    Yes
protected
     Yes
        Yes
       Yes
    No
private
     Yes
        No
       No
    No
package( default)
    Yes
         Yes
       Yes
    No
 * The following access modifiers apply to script and instance member like instance functions, script functions, instance variables, and script variables.
32. Is synchronized modifier ?
Ans: Yes, If more than one of your threads running at the same time and access shared objects, then a synchronized keyword is placed in front of Run method, so  synchronized should be modify according to the object that call run method.
33. What is meant by polymorphism ?
Ans: Generally, polymorphism is a concept in which a subclass( or child class) can be easily inherited the member (like method, parameter and signature) of superclass (or parent class) but not vice-versa.  Polymorphism may be of  two kind-
  • Method overloading
  • Method overriding
34. What is inheritance ?
 
35. What is method Overloading ? What is this in OOPS ?
Ans: when two methods and operator (within different class) have the same name and same arguments , but different signature, it is known as overloading in Object oriented    concepts.
       Two types of are:-
      1. Operator overloading is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of      their arguments.
      1. Function overloading or method overloading is allows to creation the several methods with the same name which differ from each other in terms of the type of the input     and the type of the output of the function. Method overloading is usually associated with statically-typed programming languages which enforce type checking in function calls.
 
36. What is method Overriding ? What is it in OOPS ?
Ans: In overriding, a method in a super class is overridden in the subclass. The method in the subclass will have the same signature as that of the superclass. Since the method in the subclass has the same signature & name as the method of its super class, it is termed as overriding.
   
// example for method overriding

package r4r.co.in;

class number {

    int i, j;

    number(int a, int b) {
        i = a;
        j = b;

        System.out.println("i and j: " + i + " " + j);
    }
}

class numbertest extends number {            // Create a subclass by extending class A.

    int k;

    numbertest(int a, int b, int c) {
        super(a, b);
        k = a + b + c;                       //airthmetic sum

        System.out.println("value of k:" + k);
    }
}

class Override {

    public static void main(String args[]) {
        numbertest b = new numbertest(1, 2, 3);       //initilization numbertest
       
    }
}
37. Does java support multi dimensional arrays ?
Ans: Yes, java supported multi dimension array.
   Example-

    //Syntax for defining multidimensional array

   var array = new Array(3);
     for (var i = 0; i < 3; i++) {  
array[i] = [' ', ' ', ' ']; }      //initialization of an array


   Result
    array[0][2] = 'x';
    array[1][1] = 'x';
    array[2][0] = 'x';
 
38. Is multiple inheritance used in Java ?
Ans: Java doesn't support multiple inheritance is direct form due to arise the problem of ambiguity( Doubtfulness or uncertainty as regards interpretation), but it support it in term of interface.
40. Does JavaScript support multidimensional arrays ?
Ans: Yes , JavaScript is support multidimensional array.
  Example---

  //Syntax for defining multidimensional array

   var array = new Array(3);
     for (var i = 0; i < 3; i++) {  
array[i] = [' ', ' ', ' ']; }        //initialization of an array


   Result
    array[0][2] = 'x';
    array[1][1] = 'x';
    array[2][0] = 'x';
41. Is there any tool in java that can create reports ?
Ans: Jesperreport.
43. What is meant by a class ?
Ans: A class is a specification (think of it as a blueprint or pattern and a set of instructions) of how to construct something.
44. What is meant by a method ?
Ans: A method declaration is the heading of a method containing the name of the method, its parameters, and its access level.
45. What are the OOPS concepts in Java ?
Ans: OOPs use three basic concepts as the fundamentals for the programming language: classes, objects and methods. Additionally, Inheritance, Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within object-oriented programming languages.
46. What is meant by encapsulation ? Explain with an example.
Ans:  Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
47. What is meant by inheritance ? Explain with an example.
Ans:Inheritance means to take something that is already made. It is one of the most important features of Object Oriented Programming. It is the concept that is used for reusability purpose. Inheritance is the mechanism through which we can derive classes from other classes. The derived class is called as childclass or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used.

 
50. What is meant by Java interpreter ?
Ans: A small program with interpret java byte code to machine languages.
51. What is meant by JVM ?
Ans: Java Virtual Machine( JVM) is the heart of Java programming language because Most programming languages compile source code directly into machine code while in java,  it uses bytecode - a special type of machine code which is easily executed by CPU, or The Java Virtual Machine ( JVM) provides a platform-independent way of executing code, by abstracting the differences between operating systems and CPU architectures.
52. What is a compilation unit ?
Ans: The source code for a Java class is called a compilation unit. A compilation unit normally contains a single class definition and is named for that class. The definition of a class named
MySimpledemo, for instance, should appear in a file named Mysimpledemo.java. or a compilation unit must have .java extension, and inside the compilation unit there can be a public class that must have the same name as the main file.
53. What is meant by identifiers ?
Ans:
Identifiers are the names of variables, methods, classes, packages and interfaces. In the simple HelloWorld program, HelloWorld, String, args, main and println() are identifiers. Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $.



No comments:

Post a Comment