Java Interview Questions

By YuwebDesign

Continue Reading >>>

Memory Allocation in Java: Stack Memory vs Heap Space

By YuwebDesign

Memory Allocation in Java: Stack Memory vs Heap Space

JVM divides memory into stack and heap memory.

Whenever we declare a new variable/ object, or call a new method,
JVM allocates memory to these operations either from Heap Space or from Stack Memory.

Stack Memory in Java

Stack Memory in Java is used for static memory allocation and the execution of a thread.

  1. Stack is automatically allocated when a new method is called.
  2. Access to this memory is in Last-In-First-Out (LIFO) order.
  3. Stack contains method specific values
    A new block on top of the stack stores values for this method: local primitive variables and reference variables to objects in heap space.
  4. Method specific values are short-lived.
    Variables inside stack exist only as long as the method that created them is running.
  5. Stack is automatically deallocated when method finishes execution
    After method execution is finished, it’s stack frame is flushed, the flow goes back to the calling method
    and space becomes available for the next method.
  6. If stack memory is full, Java throws java.lang.StackOverFlowError
  7. Stack memory is threadsafe as each thread operates in its own stack
Heap Space in Java

Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime.

Whenever a new object is created, it’s always stored in the Heap space and stack memory contains the reference to it.
Any object created in the heap space has global access and can be referenced from anywhere of the application.

Heap Space memory model is further broken into smaller parts called generations:

  1. Young Generation
    where all new objects are allocated and aged.
    When objects are stored in the Young Generation, a threshold for the object’s age is set and when that threshold is reached, the object is moved to the old generation.
    A minor Garbage Collection runs when this fills up to free the heap memory used by objects that don’t have any reference.
  2. Old or Tenured Generation
    where long surviving objects are stored.
  3. Permanent Generation
    consists of JVM metadata for the runtime classes and application methods
Stack vs Heap
  1. Because of simplicity in memory allocation (LIFO), access to stack memory is faster than to the heap memory.
  2. Stack memory size is much smaller than that of the Heap memory.
  3. Heap memory is used by all the parts of the application.
    Stack memory is used only by one thread of execution.
  4. Whenever a new object is created, it’s always stored in the Heap space and stack memory contains only the reference to it.
  5. Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  6. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Generations and cleaned by Java Garbage Collection.
  7. Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.

Compile time vs Run-time error

By YuwebDesign

Compile time error vs Run-time error

Compile time error

Compile time error is any type of error that prevents a java program from compiling, e.g.,

  1. syntax error
  2. class not found
  3. a bad file name for the defined class
  4. a possible loss of precision when you are mixing different java data types

Compiling errors are good, because they allow us to fix our code.

Run-time error

Run-time error happens, while the program is running.

Run-time errors are bad because they crash our program and we don’t always catch them before it is too late.

Types of Import statement in Java

By YuwebDesign

What is import?

Imports are a mechanism for accessing classes inside a package.

Regular Import

A class can have only one package declaration but it can have more than one package import statements.

A package name should be included in the import statement.

package abcpackage; //single package declaration
import xyzpackage;
import anotherpackage;
import anything;

  1. All the classes and interfaces of this package will be accessible but not subpackages.
    import package.*;

    E.g., import all the classes from util package contained inside java.
    import java.util.*;

  2. Only mentioned class of this package will be accessible.
    import package.classname;

    E.g., import Vector class from util package contained inside java.
    import java.util.vector;

    Class name is generally used to avoid conflict
    when two packages have same class name.
    import java.util.Date;
    import my.packag.Date;

Static Import

Static import is a feature introduced in Java (ver. 5+)
that allows members (fields and methods)
defined in a class as public static
to be used in Java code
without specifying the class
in which the field is defined.

You can use fully qualified name (package_name.class_name) to avoid the import statement.

Regular import:

//Declaring a package
package somepackage;
//importing a package
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));

Static import:

//Declaring a package
package anotherpackage;
public class Example{
public static void main(String args[]){
//Using fully qualified name instead of import
letmecalculate.Calculator obj =
new letmecalculate.Calculator();
System.out.println(obj.add(100, 200));

Package Structure in Java

By YuwebDesign

Package (Package Structure) in Java

Package in Java is a mechanism to encapsulate a group of related classes, sub packages and interfaces together.

These classes will all be related in some way, e.g.:

  1. belonging to the same category
    e.g., they might all have to do with a specific application;
  2. having similar functionality,
    e.g., they perform a specific set of tasks.

A package can contain the following types:

  1. classes,
  2. interfaces,
  3. enumerations,
  4. annotation types.

Packages help to:

  1. Avoid naming conflicts
    A Java package organizes Java classes into namespaces,
    providing a unique namespace for each type it contains.

    We can define two classes with the same name in different packages to avoid name collision.
    E.g., there can be two classes with name Employee in two packages,
    college.staff.cse.Employee and college.staff.ee.Employee

  2. Write a better maintainable code
  3. Reusability
    Define reusable code in form of classes inside a package.
    After that we can simply import a class from existing packages and use it in our program.
    We can reuse existing classes from the packages as many times as we need it in our program.
  4. Better Organization makes it easier to search for/locate and use classes, interfaces, enumerations, and annotations.

    For several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.

  5. Controlled access:
    public, protected and default have package level access control.

    Public members and classes are visible everywhere
    and private members are visible only in the same class.

    Classes in the same package can access each other’s package-private and protected members.

    A protected member is accessible by
    classes in the same package
    and its subclasses
    (classes in other packages that are subclasses of the declaring class).

    A default member (package-private) is accessible by
    classes in the same package only.

  6. Packages can be considered as data encapsulation (or data-hiding).
  7. Java packages can be stored in compressed files called JAR files, allowing classes to be downloaded faster as groups rather than individually.
Package naming conventions

The Java Language Specification establishes package naming conventions
to avoid the possibility of two published packages having the same name.

The naming conventions describe how to create unique package names,
so that packages that are widely distributed will have unique namespaces.

This allows packages to be separately, easily and automatically installed and catalogued.

Packages are usually defined using a hierarchical naming pattern,
levels in the hierarchy are separated by periods (., pronounced “dot”).

Although packages lower in the naming hierarchy
are often referred to as “subpackages
of the corresponding packages higher in the hierarchy,
there is almost no semantic relationship between packages.
E.g., java.util.Scanner
→ java is a top level package
→ util is a sub package
→ Scanner is a class which is present in the sub package util.

Packages are named in reverse order of domain names,
(highest hierarchy on the left):

  1. top level domain name of the organization
  2. .(dot)
  3. organization’s domain
  4. .(dot)
  5. any subdomains
  6. .(dot)
  7. organization can then choose a specific name for its package
  8. .(dot)
  9. subsequent components of the package name
    (vary according to an organization’s own internal naming conventions)

You can visualize a package as a folder/sub-folder structure in a file directory.

E.g, if a package name is college.staff.cse,
then there are three directories, college, staff and cse;
cse is located in staff and staff is located in college
(think of it as college/staff/cse in terms of folders in a file directory).
i.e., org.tarima.yuwebdesign
(think of it as org/tarima/yuwebdesign in terms of folders in a file directory).

The directory college is accessible through CLASSPATH variable,
i.e., path of parent directory of college is present in CLASSPATH.
The idea is to make sure that classes are easy to locate.

Types of Java packages
    Packages are divided into two categories:

  1. Built-in Packages (packages from the Java API)
  2. User-defined Packages (create your own packages)