Core Java BCA3

 

 Q. Explain JDK, JRE and JVM?


 

Q.Why is Java ‘write once and run anywhere’(WORA)?

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM.

How Java is WORA:

In traditional programming languages like C, C++ when programs were compiled, they used to be converted into the code understood by the particular underlying hardware, so If we try to run the same code at another machine with different hardware, which understands different code will cause an error, so you have to re-compile the code to be understood by the new hardware.

In Java, the program is not converted to code directly understood by Hardware, rather it is converted to  bytecode(.class file), which is interpreted by JVM, so once compiled it generates bytecode file, which can be run anywhere (any machine) which has JVM( Java Virtual Machine) and hence it gets the nature of Write Once and Run Anywhere.


 Conclusion:
To sum it up, Java, when compiled, creates a bytecode (.class file), which can be run in any machine which supports JVM. So once compiled it doesn’t require re-compilation at every machine it runs, JVM converts the bytecode to be understood by the underlying hardware.

This is how java becomes platform-independent programming language.


Q.Explain the JVM architecture?

Java Virtual Machine is the abstract machine or specification that provides a runtime environment to execute the bytecode. JVM supports Java and many other languages known as JVM languages, the program written in these languages is compiled into the bytecode and then executed by the JVM. It contains key components which are classloader, memory area, execution engine etc.

a) Classloader

It is a subsystem of JVM which load class files. Whenever a Java program is run, it is loaded by the classloader.

b) Class Area

Class Area holds class-level data of each class file such as metadata, constant run pool, and static variables.

c) Heap

It is the runtime data which is used for allocating objects.

d) Stack

The stack is used for storing temporary variable. This component has a stack frame which is allocated one frame to each thread and when the execution of the thread is completed then that frame is also gets destroyed.

e) Registers

This component contains the address of JVM instruction which currently being executed.

f) Native Method Stack

All the native method stack used in the application are stored in this.

g) Execution Engine

It contains:

  • A virtual processor
  • An interpreter that executes the instructions after reading the bytecode.
  • JIT compiler, used for improving the performance due to the slow execution. It compiles the similar part of the bytecode at the same time which reduces the total time needed for compilation.

h) Java Native Interface

It provides an interface which is needed for communicating with another application developed in another language like C, C++, C# etc.

Q. What is the use of Classloader in Java?

A Java program is made up of a different number of custom classes and pre-defined classes. When a program is executed, JVM is used to load all the content of that needed class and through the use of Classloader JVM, it finds that class.

There are three types of Classloaders:

  • System Class Loader

It loads all the classes from the classpath.

  • Extension ClassLoader

It loads all the classes from the extension directory.

  • Bootstrap Class Loader

It loads all the pre-defined java classes.

Q. Which class is a superclass of all classes?

Answer: Java.lang.The object is the root class for all the java classes and we don’t need to extend it. Every other java classes fall back under the object. All the different non-primitive types including arrays are inherited directly or indirectly from this class.

Q. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program:

class Main {
   public void printArray(int[] array){
       for(int i : array)
           System.out.println(i);
   }
   public static void main(String args[]) {
       int[] array = new int[10];
       printArray(array);
   }
}

For this java program. The stack and heap memory occupied by java is:-

  • main and printArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 
  • And the Object (new int[10], Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

 

Q. Explain public static void main(String args[]) in Java.

main() in Java is the entry point for any Java program. 

It is always written as public static void main(String[] args).

  • public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 
  • void: It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[]: It is the parameter passed to the main method.

Q. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Example:

class Athlete {
    public String athleteName;
    public double athleteSpeed;
    public int athleteAge;
}

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

Example:

public void athlete() {
    String athleteName;
    double athleteSpeed;
    int athleteAge;
}
 

Q. Explain method overloading and overriding with relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example gives a clear picture of it.

class OverloadingHelp {
   public int findArea (int l, int b) {
           int var1;
           var1 = l * b;
           return var1;
   }
   public int findArea (int l, int b, int h) {
           int var2;
           var2 = l * b * h;
           return var2;
   }
}

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding.
Let’s give a look at this example:

class HumanBeing {
       public int walk (int distance, int time) {
               int speed = distance / time;
               return speed;
       }
}
class Athlete extends HumanBeing {
       public int walk(int distance, int time) {
               int speed = distance / time;
               speed = speed * 2;
               return speed;
       }
}

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.


Q. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

public static void main(string[] args)

Consider the below code snippets: 

class Main {
    public static void main(String args[]) {
        System.out.println(" Main Method");
    }
    public static void main(int[] args){
        System.out.println("Overloaded Integer array Main Method");
    }
    public static void main(char[] args){
        System.out.println("Overloaded Character array Main Method");
    }
    public static int main(double[] args){
        System.out.println("Overloaded Double array Main Method");
    }
    public static void main(float args){
        System.out.println("Overloaded float Main Method");
    }
}


Q. Briefly explain the concept of constructor overloading.

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

class Hospital {
    int variable1, variable2;
    double variable3;
    public Hospital(int doctors, int nurses) {
         variable1 = doctors;
         variable2 = nurses;
    }
    public Hospital(int doctors) {
         variable1 = doctors;
    }
    public Hospital(double salaries) {
         variable3 = salaries
    }
}


Q. What are the differences between constructor and method?


















Q. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • final variable:
    • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
    • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • final method:
    • A method declared as final cannot be overridden by its children's classes.
    • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • final class:
    • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

Q. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Following are the cases when this keyword can be used:
    • Accessing data members of parent class when the member names of the class and its child subclasses are same.
    • To call the default and parameterized constructor of the parent class inside the child class.
    • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.
public class Parent{
       protected int num = 1;
       
       Parent(){
           System.out.println("Parent class default constructor.");
       }
       
       Parent(String x){
           System.out.println("Parent class parameterised constructor.");
       }
       
       public void print(){
           System.out.println("Parent class print!");
       }
   }
   
   public class Child extends Parent{
       private int num = 2;
       
       Child(){
           System.out.println("Child class default Constructor");
           super("Call Parent");    // to call parameterised constructor.
           super();    // to call default parent constructor
           
       }
       
       void printNum(){
           System.out.println(num);
           System.out.println(super.num); //prints the value of num of parent class
       }
       
       @Override
       public void print(){
           System.out.println("Parent class print!");
           super.print();    //Calls print method of Parent class inside the Overriden print method of Child class.
       }
   }



Comments

Popular posts from this blog

Advanced Java - JDBC

Java Threads