# Java Basics
> *Click ★ if you like the project. Your contributions are heartily ♡ welcome.*
## Related Topics
* *[Multithreading](multithreading-questions.md)*
* *[Collections](collections-questions.md)*
* *[Java Database Connectivity (JDBC)](JDBC-questions.md)*
* *[Java Programs](java-programs.md)*
* *[Java String Methods](java-string-methods.md)*
* *[Jakarta Server Pages (JSP)](jsp-questions.md)*
* *[Servlets](servlets-questions.md)*
* *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)*
* *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)*
* *[Hibernate](https://github.com/learning-zone/hibernate-basics)*
* *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)*
## Table of Contents
* [Introduction](#-1-introduction)
* [Java Architecture](#-2-java-architecture)
* [Java Data Types](#-3-java-data-types)
* [Java Methods](#-4-java-methods)
* [Java Functional programming](#-5-java-functional-programming)
* [Java Lambda expressions](#-6-java-lambda-expressions)
* [Java Classes](#-7-java-classes)
* [Java Constructors](#-8-java-constructors)
* [Java Array](#-9-java-array)
* [Java Strings](#-10-java-strings)
* [Java Reflection](#-11-java-reflection)
* [Java Streams](#-12-java-streams)
* [Java Regular Expressions](#-13-java-regular-expressions)
* [Java File Handling](#-14-java-file-handling)
* [Java Exceptions](#-15-java-exceptions)
* [Java Inheritance](#-16-java-inheritance)
* [Java Method Overriding](#-17-java-method-overriding)
* [Java Polymorphism](#-18-java-polymorphism)
* [Java Abstraction](#-19-java-abstraction)
* [Java Interfaces](#-20-java-interfaces)
* [Java Encapsulation](#-21-java-encapsulation)
* [Java Generics](#-22-java-generics)
* [Miscellaneous](#-23-miscellaneous)
## # 1. INTRODUCTION
## Q. What are the important features of Java 8 release?
* Interface methods by default;
* Lambda expressions;
* Functional interfaces;
* References to methods and constructors;
* Repeatable annotations
* Annotations on data types;
* Reflection for method parameters;
* Stream API for working with collections;
* Parallel sorting of arrays;
* New API for working with dates and times;
* New JavaScript Nashorn Engine ;
* Added several new classes for thread safe operation;
* Added a new API for `Calendar`and `Locale`;
* Added support for Unicode 6.2.0 ;
* Added a standard class for working with Base64 ;
* Added support for unsigned arithmetic;
* Improved constructor `java.lang.String(byte[], *)` and method performance `java.lang.String.getBytes()`;
* A new implementation `AccessController.doPrivileged` that allows you to set a subset of privileges without having to check all * other access levels;
* Password-based algorithms have become more robust;
* Added support for SSL / TLS Server Name Indication (NSI) in JSSE Server ;
* Improved keystore (KeyStore);
* Added SHA-224 algorithm;
* Removed JDBC Bridge - ODBC;
* PermGen is removed , the method for storing meta-data of classes is changed;
* Ability to create profiles for the Java SE platform, which include not the entire platform, but some part of it;
* Tools
* Added utility `jjs` for using JavaScript Nashorn;
* The command `java` can run JavaFX applications;
* Added utility `jdeps` for analyzing .class files.
## Q. What is difference between Heap and Stack Memory in java? **1. Java Heap Space:** Java Heap space is used by java runtime to allocate memory to **Objects** and **JRE classes**. Whenever we create any object, it\'s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn\'t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application. **2. Java Stack Memory:** Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. Stack memory is always referenced in LIFO ( Last-In-First-Out ) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. **Difference:** |Parameter |Stack Memory |Heap Space | |------------------|-----------------------------|-----------------------------------| |Application |Stack is used in parts, one at a time during execution of a thread| The entire application uses Heap space during runtime| |Size |Stack has size limits depending upon OS and is usually smaller then Heap|There is no size limit on Heap| |Storage |Stores only primitive variables and references to objects that are created in Heap Space|All the newly created objects are stored here| |Order |It is accessed using Last-in First-out (LIFO) memory allocation system| This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.| |Life |Stack memory only exists as long as the current method is running|Heap space exists as long as the application runs| |Efficiency |Comparatively much faster to allocate when compared to heap| Slower to allocate when compared to stack| |Allocation/Deallocation| This Memory is automatically allocated and deallocated when a method is called and returned respectively|Heap space is allocated when new objects are created and deallocated by Gargabe Collector when they are no longer referenced | ## Q. How many types of memory areas are allocated by JVM? JVM is a program which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM perform some particular types of operations: * Loading of code * Verification of code * Executing the code * It provide run-time environment to the users **Types of Memory areas allocated by the JVM:** **1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. **2. Class(Method) Area**: Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. **3. Heap**: It is the runtime data area in which objects are allocated. **4. Stack**: Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. **5. Program Counter Register**: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. **6. Native Method Stack**: It contains all the native methods used in the application. ## # 3. JAVA DATA TYPES
Method | Description |
---|---|
public final Class getClass() | returns the Class class object of this object. The Class class can further be used to get the metadata of this class. |
public int hashCode() | returns the hashcode number for this object. |
public boolean equals(Object obj) | compares the given object to this object. |
protected Object clone() throws CloneNotSupportedException | creates and returns the exact copy (clone) of this object. |
public String toString() | returns the string representation of this object. |
public final void notify() | wakes up single thread, waiting on this object\'s monitor. |
public final void notifyAll() | wakes up all the threads, waiting on this object\'s monitor. |
public final void wait(long timeout)throws InterruptedException | causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait(long timeout,int nanos)throws InterruptedException | causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait()throws InterruptedException | causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). |
protected void finalize()throws Throwable | is invoked by the garbage collector before object is being garbage collected. |
**Example:** ```java /** * Exception classes */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class CustomExceptionExample { public static void main(String[] args) throws MyException { try { processFile("file.txt"); } catch (MyException e) { processErrorCodes(e); } } private static void processErrorCodes(MyException e) throws MyException { switch(e.getErrorCode()){ case "BAD_FILE_TYPE": System.out.println("Bad File Type, notify user"); throw e; case "FILE_NOT_FOUND_EXCEPTION": System.out.println("File Not Found, notify user"); throw e; case "FILE_CLOSE_EXCEPTION": System.out.println("File Close failed, just log it."); break; default: System.out.println("Unknown exception occured," +e.getMessage()); e.printStackTrace(); } } private static void processFile(String file) throws MyException { InputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION"); } finally { try { if(fis !=null) fis.close(); } catch (IOException e) { throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION"); } } } } ``` ## Q. What is difference between Error and Exception? |BASIS FOR COMPARISON |ERROR |EXCEPTION | |-----------------------|-----------------------------------------|----------------------------------------| |Basic |An error is caused due to lack of system resources.|An exception is caused because of the code.| |Recovery |An error is irrecoverable. |An exception is recoverable.| |Keywords |There is no means to handle an error by the program code.| Exceptions are handled using three keywords "try", "catch", and "throw".| |Consequences |As the error is detected the program will terminated abnormally.|As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly.| |Types |Errors are classified as unchecked type.|Exceptions are classified as checked or unchecked type.| |Package |In Java, errors are defined "java.lang.Error" package.|In Java, an exceptions are defined in"java.lang.Exception".| |Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.| ## Q. Explain about Exception Propagation? An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation. **Example:** ```java /** * Exception Propagation */ class TestExceptionPropagation { void method1() { int data = 10 / 0; // generates an exception System.out.println(data); } void method2() { method1(); // doesn't catch the exception } void method3() { // method3 catches the exception try { method2(); } catch (Exception e) { System.out.println("Exception is caught"); } } public static void main(String args[]) { TestExceptionPropagation obj = new TestExceptionPropagation(); obj.method3(); } } ``` ## Q. What are different scenarios causing "Exception in thread main"? Some of the common main thread exception are as follows: * **Exception in thread main java.lang.UnsupportedClassVersionError**: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version. * **Exception in thread main java.lang.NoClassDefFoundError**: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found. * **Exception in thread main java.lang.NoSuchMethodError: main**: This exception comes when you are trying to run a class that doesn\'t have main method. * **Exception in thread "main" java.lang.ArithmeticException**: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message. ## Q. What are the differences between throw and throws? **Throw** keyword is used in the method body to throw an exception, while **throws** is used in method signature to declare the exceptions that can occur in the statements present in the method. **Example:** ```java /** * Throw in Java */ public class ThrowExample { void checkAge(int age) { if (age < 18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]) { ThrowExample obj = new ThrowExample(); obj.checkAge(13); System.out.println("End Of Program"); } } ``` Output ```java Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at Example1.checkAge(Example1.java:4) at Example1.main(Example1.java:10) ``` **Example:** ```java /** * Throws in Java */ public class ThrowsExample { int division(int a, int b) throws ArithmeticException { int t = a / b; return t; } public static void main(String args[]) { ThrowsExample obj = new ThrowsExample(); try { System.out.println(obj.division(15, 0)); } catch (ArithmeticException e) { System.out.println("You shouldn't divide number by zero"); } } } ``` Output ```java You shouldn\'t divide number by zero ``` ## Q. While overriding a method can you throw another exception or broader exception? If a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. This is because of polymorphism. **Example:** ```java class A { public void message() throws IOException {..} } class B extends A { @Override public void message() throws SocketException {..} // allowed @Override public void message() throws SQLException {..} // NOT allowed public static void main(String args[]) { A a = new B(); try { a.message(); } catch (IOException ex) { // forced to catch this by the compiler } } } ``` ## Q. What is checked, unchecked exception and errors? **1. Checked Exception**: * These are the classes that extend **Throwable** except **RuntimeException** and **Error**. * They are also known as compile time exceptions because they are checked at **compile time**, meaning the compiler forces us to either handle them with try/catch or indicate in the function signature that it **throws** them and forcing us to deal with them in the caller. * They are programmatically recoverable problems which are caused by unexpected conditions outside the control of the code (e.g. database down, file I/O error, wrong input, etc). **Example:** **IOException, SQLException** etc. ```java import java.io.*; class Main { public static void main(String[] args) { FileReader file = new FileReader("C:\\assets\\file.txt"); BufferedReader fileInput = new BufferedReader(file); for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } } ``` output: ```java Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at Main.main(Main.java:5) ``` After adding IOException ```java import java.io.*; class Main { public static void main(String[] args) throws IOException { FileReader file = new FileReader("C:\\assets\\file.txt"); BufferedReader fileInput = new BufferedReader(file); for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } } ``` output: ```java Output: First three lines of file “C:\assets\file.txt” ``` **2. Unchecked Exception**: * The classes that extend **RuntimeException** are known as unchecked exceptions. * Unchecked exceptions are not checked at compile-time, but rather at **runtime**, hence the name. * They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration. **Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. ```java class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } ``` Output: ```java Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) Java Result: 1 ``` **3. Error**: **Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? `ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. `ClassNotFoundException` is an exception that occurs when you try to load a class at run time using `Class.forName()` or `loadClass()` methods and mentioned classes are not found in the classpath. `NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. ## # 16. JAVA INHERITANCE
Aggregation | Composition |
---|---|
Aggregation is a weak Association. | Composition is a strong Association. |
Class can exist independently without owner. | Class can not meaningfully exist without owner. |
Have their own Life Time. | Life Time depends on the Owner. |
A uses B. | A owns B. |
Child is not owned by 1 owner. | Child can have only 1 owner. |
Has-A relationship. A has B. | Part-Of relationship. B is part of A. |
Denoted by a empty diamond in UML. | Denoted by a filled diamond in UML. |
We do not use "final" keyword for Aggregation. | "final" keyword is used to represent Composition. |
Examples: - Car has a Driver. - A Human uses Clothes. - A Company is an aggregation of People. - A Text Editor uses a File. - Mobile has a SIM Card. | Examples: - Engine is a part of Car. - A Human owns the Heart. - A Company is a composition of Accounts. - A Text Editor owns a Buffer. - IMEI Number is a part of a Mobile. |
Abstraction | Encapsulation |
---|---|
Abstraction is a process of hiding the implementation details and showing only functionality to the user. | Encapsulation is a process of wrapping code and data together into a single unit |
Abstraction lets you focus on what the object does instead of how it does it. | Encapsulation provides you the control over the data and keeping it safe from outside misuse. |
Abstraction solves the problem in the Design Level. | Encapsulation solves the problem in the Implementation Level. |
Abstraction is implemented by using Interfaces and Abstract Classes. | Encapsulation is implemented by using Access Modifiers (private, default, protected, public) |
Abstraction means hiding implementation complexities by using interfaces and abstract class. | Encapsulation means hiding data by using setters and getters. |