Java Tutorial
- Get link
- X
- Other Apps
Java Tutorial | Learn Java Programming (geeksforgeeks.org)
Overview of Java:
Topic | Description/Answer |
Introduction to Java | - Java is a high-level, object-oriented programming language known for its portability and versatility. |
History of Java | - Java was created by James Gosling and released by Sun Microsystems in 1995. It was initially called Oak. |
Java vs C++ Python | - Java, C++, and Python are popular programming languages, each with its strengths and use cases. |
How to Download and Install Java? | - To install Java, download the Java Development Kit (JDK) from the official Oracle website and follow installation instructions. |
Setting Up the Environment in Java | - Configure system variables like JAVA_HOME and PATH to set up the Java development environment. |
How to Download and Install Eclipse on Windows? | - Download the Eclipse IDE from the official website and follow installation steps on a Windows system. |
Java Development Kit (JDK) in Java | - JDK is a package that includes the Java Compiler (javac) and other tools for Java development. |
JVM and its architecture | - The Java Virtual Machine (JVM) is responsible for executing Java bytecode. It has components like Class Loader, Execution Engine, and more. |
Differences between JDK, JRE, and JVM | - JDK includes the development tools. JRE is for running Java applications. JVM is the runtime environment. |
Just In Time Compiler | - JIT is a component of JVM that compiles bytecode into native machine code for improved performance. |
Difference Between JIT and JVM | - JVM is the runtime environment, while JIT is a part of JVM that compiles bytecode to native code at runtime. |
Difference Between Byte Code and Machine Code | - Bytecode is platform-independent, while machine code is specific to a particular hardware architecture. |
How is the Java platform independent? | - Java achieves platform independence by compiling source code to bytecode, which runs on any JVM. |
JAVA_HOME Environment Variable | - Set the JAVA_HOME environment variable to specify the Java installation directory. |
Installing Java on Linux | - On Linux, you can install Java using package managers like apt or by downloading the JDK from Oracle. |
Eclipse IDE Features | - Eclipse is a powerful IDE with features like code completion, debugging, and plug-in support. |
Variables and Data Types in Java | - Java has various data types (int, double, etc.) and supports variables to store data. |
Operators in Java | - Java provides operators for arithmetic, comparison, and logical operations. |
Control Flow Statements in Java | - Control flow statements like if, switch, and loops control the flow of execution in Java programs. |
Object-Oriented Programming in Java | - Java is an object-oriented programming language, supporting concepts like classes, objects, and inheritance. |
Basics of Java
Topic | Description/Answer | JAVA Code Example |
Java Basic Syntax | - Java programs follow a specific syntax, including semicolons, curly braces, and more. | N/A (Explanation only) |
First Java Program (Hello World) | - The traditional "Hello World" program is used to introduce Java to beginners. | java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } |
Datatypes in Java | - Java supports various data types like int, double, char, etc., for storing values. | N/A (Explanation only) |
Difference between Primitive and Non-Primitive Datatypes | - Primitive datatypes store simple values, while non-primitive datatypes store references to objects. | N/A (Explanation only) |
Java Identifiers | - Identifiers are names given to variables, methods, classes, etc., following specific rules. | N/A (Explanation only) |
Operators in Java | - Java provides operators for arithmetic, comparison, logical, and other operations. | N/A (Explanation only) |
Java Variables | - Variables are used to store data in Java and must be declared with a specific data type. | java int age = 25; |
Scope of Variables | - The scope of a variable defines where it can be accessed within a program. | N/A (Explanation only) |
Wrapper Classes in Java | - Wrapper classes provide an object representation for primitive data types. | java Integer num = new Integer(5); |
Input/Output in Java
Topic | Description/Answer | JAVA Code Example |
How to take Input from users in Java | - Java uses input streams like Scanner and BufferedReader to read input from users. | N/A (Explanation only) |
Scanner class in Java | - The Scanner class is used for reading input from various sources like the keyboard. | java import java.util.Scanner; Scanner scanner = new Scanner(System.in); |
BufferedReader class in Java | - The BufferedReader class is used for reading input with enhanced capabilities. | java import java.io.BufferedReader; import java.io.InputStreamReader; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); |
Scanner vs BufferedReader in Java | - Scanner is easier to use for simple input, while BufferedReader is more efficient for reading large amounts of data. | N/A (Explanation only) |
Ways to Read Input from Console in Java | - Use Scanner or BufferedReader to read input from the console in Java. | N/A (Explanation only) |
Print Output in Java | - Use System.out.print() or System.out.println() to display output in Java. | N/A (Explanation only) |
Difference between print() and println() in Java | - print() displays text without a newline, while println() adds a newline after the text. | N/A (Explanation only) |
Formatted Outputs in Java | - Use formatting options like printf() to display output with specific formatting in Java. | java int number = 42; System.out.printf("The number is %d", number); |
Fast Input-Output for Competitive Programming in Java | - Use fast input-output techniques like using BufferedReader and StringBuilder for competitive programming in Java. | N/A (Explanation only) |
Flow Control in Java
Topic | Description/Answer | JAVA Code Example |
Decision making in Java | - Decision-making involves executing different code blocks based on specified conditions. | N/A (Explanation only) |
If Statement in Java | - The if statement is used to execute a block of code only if a specified condition is true. | java if (condition) { // code to execute } |
If-Else Statement in Java | - The if-else statement is used to execute one block of code if a condition is true and another if it's false. | java if (condition) { // code to execute } else { // code to execute if the condition is false } |
If-Else-If ladder in Java | - The if-else-if ladder is used when you have multiple conditions to check, and only one of them should be executed. | java if (condition1) { // code to execute } else if (condition2) { // code to execute } else { // code to execute if all conditions are false } |
Loops in Java | - Loops are used for repetitive execution of code. Java supports for, while, do-while, and for-each loops. | N/A (Explanation only) |
For loop | - The for loop is used to iterate over a range of values or a collection of elements. | java for (int i = 0; i < 5; i++) { // code to execute } |
While Loop | - The while loop executes a block of code as long as a specified condition is true. | java while (condition) { // code to execute } |
Do while loop | - The do-while loop is similar to while, but it always executes the block of code at least once before checking the condition. | java do { // code to execute } while (condition); |
For each loop | - The for-each loop is used to iterate through elements in an array or collection. | java for (datatype variable : array/collection) { // code to execute } |
Continue Statement in Java | - The continue statement is used to skip the current iteration of a loop and continue with the next iteration. | java for (int i = 0; i < 5; i++) { if (i == 3) { continue; } // code to execute } |
Break Statement In Java | - The break statement is used to exit a loop prematurely, terminating the loop's execution. | java for (int i = 0; i < 5; i++) { if (i == 3) { break; } // code to execute } |
Usage of Break in Java | - The break statement can be used to exit loops, switch statements, and labeled blocks in Java. | N/A (Explanation only) |
Return Statement in Java | - The return statement is used to exit a method and optionally return a value to the calling code. | java public int add(int a, int b) { return a + b; } |
Operators in Java
Topic | Description/Answer | JAVA Code Example |
Arithmetic Operator | - Arithmetic operators perform mathematical operations like addition, subtraction, multiplication, division, and modulus. | java int result = a + b; |
Unary Operator | - Unary operators operate on a single operand and include increment (++), decrement (--), and negation (-). | java int a = 5; a++; // Increment a by 1 |
Assignment Operator | - The assignment operator (=) is used to assign values to variables. | java int x = 10; |
Relational Operator | - Relational operators compare two values and return true or false based on the comparison (e.g., <, >, ==). | java boolean isGreater = (a > b); |
Logical Operator | - Logical operators perform logical operations (e.g., &&, | |
Ternary Operator | - The ternary operator (? :) is a shorthand way to write if-else statements in a single line. | java int max = (a > b) ? a : b; |
Bitwise Operator | - Bitwise operators perform operations at the bit level (e.g., &, | , ^) on integer values. |
Strings in Java
Topic | Description/Answer | JAVA Code Example |
Introduction of Strings in Java | - Strings in Java represent sequences of characters and are widely used for text manipulation. | N/A (Explanation only) |
String class in Java Set-1 | Set-2 | - The String class in Java is used to create and manipulate strings. It offers various methods for string manipulation. |
Why strings are immutable in Java? | - Strings are immutable in Java to ensure their value cannot be changed once created, providing stability and security. | N/A (Explanation only) |
StringBuffer class in Java | - The StringBuffer class provides a mutable, thread-safe alternative to String for string manipulation. | java StringBuffer sb = new StringBuffer("Hello"); |
StringBuilder class in Java | - The StringBuilder class is similar to StringBuffer but is not thread-safe, making it more efficient for single-threaded operations. | java StringBuilder sb = new StringBuilder("Hello"); |
Strings vs StringBuffer vs StringBuilder in Java | - Strings are immutable, StringBuffer is mutable and thread-safe, StringBuilder is mutable but not thread-safe. | N/A (Explanation only) |
StringTokenizer class in Java Set-1 | Set-2 | - The StringTokenizer class is used to break a string into tokens or words based on a delimiter. |
StringJoiner in Java | - The StringJoiner class is used to join multiple strings with a delimiter, providing a convenient way to construct strings. | java StringJoiner sj = new StringJoiner(", "); |
Java String Programs | - Java string programs involve tasks like reversing a string, checking for palindromes, and other string manipulations. | N/A (Explanation only) |
Arrays in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Arrays in Java | - Arrays are data structures that store a fixed-size sequence of elements of the same data type in Java. | N/A (Explanation only) |
Arrays class in Java | - The Arrays class in Java provides various utility methods for working with arrays. | N/A (Explanation only) |
Multi-Dimensional Array in Java | - A multi-dimensional array is an array of arrays, allowing you to create tables or matrices in Java. | N/A (Explanation only) |
How to declare and initialize 2D arrays in Java | - You can declare and initialize 2D arrays using nested loops or directly specifying values. | java int[][] matrix = {{1, 2, 3}, {4, 5, 6}}; |
Jagged array in Java | - A jagged array is an array of arrays where each row can have a different number of elements. | N/A (Explanation only) |
Final Arrays in Java | - A final array in Java is a constant array whose size and elements cannot be changed after initialization. | java final int[] numbers = {1, 2, 3}; |
Reflect Arrays in Java | - Reflect arrays in Java are arrays that have runtime type information and can be inspected using reflection. | N/A (Explanation only) |
Difference between util.Arrays and reflect.Arrays | - java.util.Arrays provides utility methods for arrays, while java.lang.reflect.Array deals with reflective operations on arrays. | N/A (Explanation only) |
Java Array Programs | - Java array programs include tasks like finding the largest element, sorting, and other array manipulations. | N/A (Explanation only) |
OOPS in Java
Topic | Description/Answer | JAVA Code Example |
OOPS Concept in Java | - Object-Oriented Programming (OOPS) is a programming paradigm that represents real-world entities using objects in Java. | N/A (Explanation only) |
Why Java is not a purely Object-Oriented Language? | - Java is not purely object-oriented because it supports primitive data types and non-object-oriented features like static methods. | N/A (Explanation only) |
Classes and Objects | - Classes are blueprint templates for creating objects in Java, and objects are instances of classes. | N/A (Explanation only) |
Naming Convention in Java | - Java follows naming conventions like CamelCase for classes, methods, and PascalCase for variables. | N/A (Explanation only) |
Methods in Java | - Methods in Java are functions defined within classes that perform specific actions or return values. | java public void myMethod() { // code to execute } |
Access Modifiers in Java | - Access modifiers control the visibility and accessibility of classes, methods, and variables in Java. | java public class MyClass { private int x; } |
Constructors in Java | - Constructors are special methods used for initializing objects. They have the same name as the class. | java public class MyClass { public MyClass() { // constructor code } } |
Four pillars of OOPS in Java | - The four pillars of OOPS in Java are Inheritance, Abstraction, Encapsulation, and Polymorphism. | N/A (Explanation only) |
Inheritance in Java | - Inheritance allows a class to inherit properties and methods from another class, promoting code reuse. | N/A (Explanation only) |
Abstraction in Java | - Abstraction is the process of simplifying complex systems by hiding unnecessary details while exposing essential features. | N/A (Explanation only) |
Encapsulation in Java | - Encapsulation is the concept of bundling data and methods that operate on that data into a single unit, or class. | N/A (Explanation only) |
Polymorphism in Java | - Polymorphism allows objects of different classes to be treated as objects of a common superclass, promoting flexibility. | N/A (Explanation only) |
Interfaces in Java | - Interfaces define a contract of methods that implementing classes must provide, enabling multiple inheritance. | java interface MyInterface { void myMethod(); } |
This reference in Java | - this refers to the current object within a method or constructor, helping to distinguish between instance variables and method parameters. | java public class MyClass { private int x; public void setX(int x) { this.x = x; } } |
Inheritance in Java
Topic | Description/Answer |
Introduction to Inheritance in Java | - Inheritance in Java allows a class to inherit properties and behaviors from another class, promoting code reuse and extensibility. |
Inheritance and Constructors | - Constructors in the superclass are not inherited by the subclass, but they can be invoked using the super keyword. |
Multiple Inheritance in Java | - Java does not support multiple inheritance for classes (inheritance from multiple classes), but it allows multiple inheritance through interfaces. |
Interfaces and Inheritance | - Interfaces in Java provide a way to achieve multiple inheritance, where a class can implement multiple interfaces. |
Association, Composition, and Aggregation | - Association, composition, and aggregation are types of relationships between classes in Java, defining how they are related and interact. |
Difference between Inheritance in C++ and Java | - In C++, multiple inheritance for classes is allowed, while in Java, multiple inheritance is achieved through interfaces. |
Abstraction in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Abstraction in Java | - Abstraction in Java is the concept of hiding the complex implementation details and showing only the necessary features of an object. | N/A (Explanation only) |
Abstract Keyword in Java | - The abstract keyword is used to declare abstract classes and methods in Java, which cannot be instantiated directly. | N/A (Explanation only) |
Abstract classes in Java | - Abstract classes are classes that cannot be instantiated but can have abstract and concrete methods. They are meant to be extended. | N/A (Explanation only) |
Abstract class vs Interface in Java | - An abstract class can have both abstract and concrete methods, while an interface can only have abstract methods. A class can implement multiple interfaces but extend only one class. | N/A (Explanation only) |
Control Abstraction in Java | - Control abstraction in Java is achieved through methods, where you can encapsulate a sequence of statements and execute them as a single unit. | java public void doSomething() { // code to execute } |
Difference between Data Hiding and Abstraction | - Data hiding is the concept of hiding data members of a class, while abstraction is the concept of hiding the implementation details and showing only necessary features. | N/A (Explanation only) |
Encapsulation in Java
Topic | Description/Answer |
Introduction to Encapsulation in Java | - Encapsulation is one of the four fundamental OOP concepts. It refers to the bundling of data and methods that operate on that data into a single unit, or class. |
Difference between Encapsulation and Abstraction | - Encapsulation is the concept of hiding the internal state of an object, while abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object. |
Polymorphism in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Polymorphism in Java | - Polymorphism is one of the four fundamental OOP concepts. It allows objects of different classes to be treated as objects of a common superclass, promoting flexibility and extensibility. | N/A (Explanation only) |
Difference between Inheritance and Polymorphism | - Inheritance is a mechanism for reusing and extending classes, while polymorphism allows objects of different classes to be treated as if they belong to a common superclass. | N/A (Explanation only) |
Runtime Polymorphism in Java | - Runtime polymorphism, also known as dynamic polymorphism, occurs when the method to be executed is determined at runtime based on the actual object type. | java class Animal { void sound() { } } class Dog extends Animal { void sound() { // Dog's sound } } Animal a = new Dog(); a.sound(); // Calls Dog's sound() |
Compile-Time vs Runtime Polymorphism | - Compile-time polymorphism, also known as static polymorphism, occurs when the method to be executed is determined at compile time based on the reference type. Runtime polymorphism is determined at runtime based on the actual object type. | N/A (Explanation only) |
Constructors in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Constructors in Java | - Constructors are special methods in Java used for initializing objects. They have the same name as the class and do not have a return type. | N/A (Explanation only) |
Copy Constructor in Java | - A copy constructor in Java is a constructor that takes an object of the same class as a parameter and creates a new object by copying the content of the passed object. | java class Student { String name; int age; Student(Student other) { this.name = other.name; this.age = other.age; } } |
Constructor Overloading | - Constructor overloading is a feature that allows a class to have multiple constructors with different parameters, providing flexibility in object initialization. | java class Student { String name; int age; Student(String n, int a) { this.name = n; this.age = a; } Student(String n) { this.name = n; } } |
Constructor Chaining | - Constructor chaining in Java occurs when one constructor calls another constructor within the same class using the this() keyword. It helps avoid code duplication. | java class Student { String name; int age; Student(String n) { this.name = n; } Student(String n, int a) { this(n); this.age = a; } } |
Private Constructors and Singleton Class | - Private constructors in Java prevent the instantiation of a class from outside the class. They are often used in Singleton design patterns to ensure only one instance of a class exists. | java class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } |
Methods in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to methods in Java | - Methods in Java are functions defined within classes that perform specific actions or return values. | N/A (Explanation only) |
Different method calls in Java | - Method calls in Java can be made by invoking a method on an object or by using a class name for static methods. | N/A (Explanation only) |
Difference between Static methods and Instance methods in Java | - Static methods belong to the class and can be called using the class name, while instance methods belong to objects and can be called using object references. | N/A (Explanation only) |
Abstract methods in Java | - Abstract methods are declared without implementation in abstract classes and must be implemented by concrete subclasses. | java abstract class Shape { abstract void draw(); } |
Method Overriding in Java | - Method overriding is a mechanism where a subclass provides a specific implementation for a method that is already defined in its superclass. | java class Animal { void sound() { } } class Dog extends Animal { void sound() { // Dog's sound } } |
Method Overloading in Java | - Method overloading allows a class to have multiple methods with the same name but different parameters, providing flexibility in method calls. | java class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } |
Method Overloading Vs Method Overriding | - Method overloading involves having multiple methods with the same name in the same class with different parameters. Method overriding involves a subclass providing a specific implementation for a method defined in its superclass. | N/A (Explanation only) |
Interfaces in Java
Topic | Description/Answer | JAVA Code Example |
Java Interfaces | - Defines a contract or a set of abstract methods and constants. - Cannot be instantiated. | interface MyInterface { void display(); } |
Implementation of Java Interfaces | - A class implements an interface using implements keyword.- All methods must be defined. | class MyClass implements MyInterface { public void display() { System.out.println("Display Hmethod"); } } |
Interfaces and Inheritance in Java | - Multiple inheritance achieved using interfaces.- A class can implement multiple interfaces. | interface A {} interface B {} class MyClass implements A, B {} |
Difference between Interface and Class in Java | - Interface: only abstract methods; Class: can have both concrete and abstract methods.- Interface: no state; Class: can have state. | interface MyInterface {} class MyClass { int x; } |
Functional Interface | - Interface with just one abstract method.- Can have multiple default or static methods. | @FunctionalInterface interface Functional { void execute(); } |
Nested Interface | - Interface declared inside another interface or class. | class Outer { interface NestedInterface { void show(); } } |
Marker Interface | - Empty interface.- Used for providing essential information to JVM or other entities. | interface Marker {} class MyClass implements Marker {} |
Comparator Interface | - Used for sorting collections.- Overrides compare method. | import java.util.*; class MyClass implements Comparator<MyClass> { public int compare(MyClass a, MyClass b) { return a.value - b.value; } } |
Wrapper Classes in Java
Topic | Description/Answer | JAVA Code Example |
Need of Wrapper classes in Java | - Provide a way to use primitive data types as objects.- Useful for Collections which store only objects.- Offer utility methods. | N/A |
How to create instances of Wrapper classes | - Using constructor.- Using valueOf method. | Integer i1 = new Integer(10); Integer i2 = Integer.valueOf(10); |
Character class in Java | - Wrapper class for char data type.- Provides utility methods for characters. | Character ch = new Character('a'); |
Byte class in Java | - Wrapper for byte data type.- Range: -128 to 127. | Byte b = new Byte((byte) 5); |
Short class in Java | - Wrapper for short data type.- Provides utility methods. | Short s = new Short((short) 10); |
Integer class in Java | - Wrapper for int data type.- Provides utility methods. | Integer i = new Integer(10); |
Long class in Java | - Wrapper for long data type.- Provides utility methods. | Long l = new Long(100L); |
Float class in Java | - Wrapper for float data type.- Provides utility methods. | Float f = new Float(10.5f); |
Double class in Java | - Wrapper for double data type.- Provides utility methods. | Double d = new Double(10.5); |
Boolean class in Java | - Wrapper for boolean data type.- Provides utility methods. | Boolean bool = new Boolean(true); |
Autoboxing and Unboxing | - Autoboxing: Converting primitive to Wrapper object.- Unboxing: Converting Wrapper object to primitive. | // Autoboxing Integer auto = 5; // Unboxing int unbox = auto; |
Type Conversion in Java | - Converting one data type to another.- Can be done using casting or wrapper class methods. | int i = 10; double d = (double) i; |
Keywords in Java
Topic | Description/Answer | JAVA Code Example |
List of all Java Keywords | - Reserved words with special meaning in Java. - Cannot be used as variable names. | N/A (too many to list here) |
Important Keywords in Java | - Keywords central to Java programming. - Examples include class, public, if, while. | N/A |
Super Keyword | - Refers to parent class. - Useful for calling parent class methods and constructors. | super(); super.methodName(); |
Final Keyword | - Restricts modification. - Can be applied to variables, methods, and classes. | final int x = 10; final class MyFinalClass {} |
Abstract Keyword | - Indicates that something is incomplete. - Used with classes and methods. | abstract class MyClass {} abstract void myMethod(); |
Static Keyword | - Belongs to the class rather than object. - Used for variables, methods, blocks, and nested class. | static int x; static void myMethod() {} |
This Keyword | - Refers to the current instance of the class. - Useful for distinguishing between instance variables and parameters. | this.x = x; |
Enum Keyword in Java | - Defines a set of named constants. - Useful for creating user-defined data types. | enum Days {MONDAY, TUESDAY, WEDNESDAY;} |
Transient Keyword in Java | - Prevents variable serialization. - Useful when you don't want to save the state of an object. | transient int x; |
Volatile Keyword in Java | - Indicates that a variable may change unexpectedly. - Useful in multithreading. | volatile boolean flag; |
Final, Finally, and Finalize in Java | - final: restriction keyword.- finally: block always executed in try-catch.- finalize: garbage collection method. | final int x; try {} catch(Exception e) {} finally {} protected void finalize() {} |
Access Modifiers in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Access Modifiers in Java | - Control visibility of class members. - Determine which other classes can access these members. | N/A |
Public Access Modifier | - Can be accessed from any other class. - Offers the least restriction. | public int x; |
Protected Access Modifier | - Can be accessed within the same package - Or by a subclass in any package. | protected int x; |
Package (Default) Access Modifier | - No modifier keyword is used. - Accessible only within the same package. | int x; |
Private Access Modifier | - Can only be accessed within the same class. - Offers the most restriction. | private int x; |
Public vs Protected vs Package vs Private in Java | - Vary in terms of access level and restriction. - Ranging from least restricted (public) to most (private). | N/A |
Access Modifiers Vs Non-Access Modifiers in Java | - Access Modifiers control visibility. - Non-Access Modifiers control other properties (e.g. static, final). | N/A |
Example of Non-Access Modifier: static | - Pertains to class level, not instance. - Used for variables, methods, blocks, and inner classes. | static int count; |
Example of Non-Access Modifier: final | - Prevents further modification. - Can be used with variables, methods, and classes. | final int MAX_VALUE = 10; |
Example of Non-Access Modifier: abstract | - Denotes incompleteness. - Cannot instantiate an abstract class. Used for classes and methods. | abstract class Shape { abstract void draw(); } |
Example of Non-Access Modifier: synchronized | - Ensures only one thread can access the method at a time. - Used for methods. | synchronized void method() {} |
Example of Non-Access Modifier: transient | - Marks a member to be skipped during serialization. - Used for variables. | transient int tempValue; |
Example of Non-Access Modifier: volatile | - Variable's value is directly read from main memory, not from thread's cache. - Used for variables. | volatile boolean flag; |
Example of Non-Access Modifier: strictfp | - Ensures consistent floating-point results across platforms. - Used for classes, interfaces, and methods. | strictfp class MyClass {} |
Non-Access Modifiers related to inheritance: final class | - Prevents the class from being subclassed. - Cannot be inherited. | final class MyFinalClass {} |
Non-Access Modifiers related to inheritance: abstract class | - Denotes the class cannot be instantiated. - Requires subclasses to provide implementations for its abstract methods. | abstract class MyAbstractClass {} |
Non-Access Modifiers related to method overriding: final method | - Prevents a subclass from changing the content/definition of the method. - Method cannot be overridden in subclass. | final void display() {} |
Non-Access Modifiers related to method overriding: abstract method | - Method without a body in the superclass. - Must be overridden in any non-abstract subclass. | abstract void display(); |
Non-Access Modifiers related to method overriding: static method | - Method belongs to the class, not instance. - Cannot be overridden, but can be re-declared in subclass. | static void show() {} |
Memory Allocation in Java
Topic | Description/Answer | JAVA Code Example |
Java Memory Management | - The way Java manages and deallocates memory.- Ensures efficient use and recovery of memory resources. | N/A |
How are Java objects stored in memory? | - Stored in the Heap memory.- Variables referencing these objects may reside in Stack memory. | Object obj = new Object(); |
Stack vs Heap memory allocation | - Stack: for primitive types & object references.- Heap: for object data & instances. | int x; // Stack Object obj = new Object(); // Heap |
Types of memory areas allocated by JVM | - Method Area- Heap Area- Stack Area- PC Register- Native Method Stack | N/A |
Garbage Collection in Java | - Process to reclaim memory from objects no longer in use.- Automatic, managed by JVM. | System.gc(); or Runtime.getRuntime().gc(); |
Heap and Stack memory allocation | - Heap: Dynamic allocation for objects.- Stack: Static allocation for primitive types & object references. | int num; // Stack String str = new String("Hello"); // Heap |
Types of JVM Garbage Collectors in Java | - Serial Garbage Collector- Parallel Garbage Collector- CMS Garbage Collector- G1 Garbage Collector | N/A |
Memory leaks in Java | - Unintended retention of memory.- Occurs when objects are no longer used, but not released by the GC. | N/A (can be subtle and complex to represent briefly) |
Java Virtual Machine(JVM) Stack Area | - Part of memory where method calls & local variables are stored.- Each thread has its own JVM stack. | N/A |
Classes of Java
Topic | Description/Answer | JAVA Code Example |
Classes and Objects | - Fundamental concepts in OOP.- Classes define blueprints, Objects are instances of those blueprints. | class Car {} Car myCar = new Car(); |
Understanding classes and objects in Java | - Classes: template or blueprint.- Objects: instances of a class, representing real-world entities. | class Dog {} Dog buddy = new Dog(); |
Class vs interface | - Class: blueprint with properties and methods.- Interface: specification or contract without implementation. | class Bird {} interface Flyable {} |
Singleton class in java | - Design pattern ensuring only one instance of a class is created.- Provides global access to that instance. | public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } |
Object class in java | - Root of Java's class hierarchy.- Every class implicitly extends this class. | Object obj = new Object(); |
Inner class in java | - Class defined within another class.- Types: non-static, method-local, anonymous, and static. | class Outer { class Inner {} } |
Abstract classes in java | - Cannot be instantiated.- They can have both abstract and concrete methods. | abstract class Animal { abstract void sound(); } |
Throwable class in java | - Superclass of all errors and exceptions in Java.- Has two main subclasses: Error and Exception. | Throwable th = new Exception(); |
Packages in Java
Topic | Description/Answer | JAVA Code Example |
Java Packages | - Grouping of related classes and interfaces.- Enhances modularity and resolves naming conflicts. | N/A |
How to create a package in Java | - Use the package keyword.- Organize related classes and interfaces in directories. | package com.example.myapp; |
java.util package | - Contains collections framework, date & time facilities, miscellaneous utility classes. | import java.util.ArrayList; ArrayList<String> list = new ArrayList<>(); |
java.lang package | - Implicitly imported in every Java program.- Contains fundamental classes for Java programming. | String s = "Hello"; |
java.io package | - Provides classes for system input and output through streams.- Support for files and directories. | import java.io.File; File file = new File("example.txt"); |
Benefits of using packages | - Avoids class name conflicts.- Easier management of larger codebases. | N/A |
Default Package | - When no package is specified, the classes belong to this.- Not recommended for regular use. | class DefaultClass {} |
Classpath for custom packages | - Path where JVM looks for user-defined classes and packages. | N/A (usually set using -cp or -classpath while compiling) |
Sub-packages | - Packages within another package.- Hierarchical arrangement of packages. | package com.example.myapp.module; |
Importing classes from packages | - To use classes from a package directly without package qualifier. | import com.example.myapp.MyClass; |
Wildcard (*) imports | - Imports all classes from the specified package. | import java.util.*; |
static imports in Java | - Import static members of a class directly.- Avoid using class qualifier for static members. | import static java.lang.Math.PI; System.out.println(PI); |
Compilation with packages | - Requires correct directory structure that matches package declaration. | javac -d . MyClass.java |
Package Access Level | - No modifier results in package-private access.- Accessible within same package only. | class PackageClass {} |
Advantages of java.util | - Robust collection framework.- Utilities like Timer, Date, Scanner, etc. | import java.util.Scanner; Scanner sc = new Scanner(System.in); |
Core classes of java.lang | - Object, Class, System, String, StringBuffer, etc.- Automatically available. | System.out.println("Hello World!"); |
Importance of java.io | - Crucial for file I/O operations.- Classes like File, FileReader, FileWriter, etc. | import java.io.FileReader; FileReader fr = new FileReader("example.txt"); |
Collection Framework in Java
Topic | Description/Answer | JAVA Code Example |
Java Collection Framework | - Group of interfaces and classes to store, retrieve, and manipulate data- Provides standard operations for data structures. | N/A |
Collections class in Java | - Utility class for Collection framework- Provides static methods to operate on collections. | Collections.sort(list); |
Collection Interface in Java | - Root interface of Collection framework- Basic methods like add, remove, size, etc. | Collection<String> collection = new ArrayList<>(); |
How to learn Java collections | - Study core interfaces & classes- Practice through coding examples- Understand use cases. | N/A |
List Interface in Java | - Ordered collection- Allows duplicate values- Has methods like get, set, indexOf, etc. | List<String> list = new ArrayList<>(); |
Queue Interface in Java | - Follows FIFO principle- Methods like offer, poll, peek, etc. | Queue<String> queue = new LinkedList<>(); |
Map Interface in Java | - Associates keys with values- No duplicate keys- Methods like put, get, remove, etc. | Map<String, Integer> map = new HashMap<>(); |
Set in Java | - Collection with no duplicate values- Implementations: HashSet, TreeSet, etc. | Set<String> set = new HashSet<>(); |
Iterator in Java | - An interface to iterate over collections- Methods like hasNext, next, and remove. | Iterator<String> iterator = list.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } |
Comparator in Java | - Interface to compare objects for ordering- Used for custom comparison logic. | Comparator<String> comp = (a, b) -> a.length() - b.length(); |
Difference between Comparator and Comparable in Java | - Comparable: natural order comparison (using compareTo)- Comparator: external order (using compare) | class Person implements Comparable<Person> { public int compareTo(Person p) { return this.age - p.age; } } Comparator<Person> byName = (a, b) -> a.name.compareTo(b.name); |
List in Java
Topic | Description/Answer | JAVA Code Example |
ArrayList in Java | - Part of the Collection framework.- Resizable-array implementation of the List interface.- Not synchronized. | ArrayList<String> list = new ArrayList<>(); list.add("Java"); |
Vector class in Java | - Similar to ArrayList but synchronized.- Thread-safe.- Slower than ArrayList. | Vector<String> vector = new Vector<>(); vector.add("Java"); |
Stack class in Java | - Extends Vector class.- Last-In-First-Out (LIFO) data structure.- Provides push and pop operations. | Stack<Integer> stack = new Stack<>(); stack.push(1); int top = stack.pop(); |
LinkedList in Java | - Doubly-linked list implementation of List & Deque interfaces.- Allows insertion/removal at both ends.- Good for dynamic memory allocation. | LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Java"); |
AbstractList | - Abstract class that implements most of the List interface.- Used to create custom list implementations. | // Can't be instantiated directly; a subclass would provide concrete implementations. |
AbstractSequentialList | - Extends AbstractList.- Provides sequential access to elements.- For creating custom list implementations with sequential access. | // Can't be instantiated directly; a subclass would provide concrete implementations. |
CopyOnWriteArrayList | - Part of the Concurrent package.- Thread-safe version of ArrayList.- Every write operation makes a fresh copy. | CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<>(); cowList.add("Java"); |
Custom ArrayList in Java | - Create a class that mimics ArrayList functionality.- Dynamic resizing and other ArrayList features implemented from scratch. | public class CustomArrayList<T> { private Object[] elements; // Other methods to mimic ArrayList } CustomArrayList<Integer> customList = new CustomArrayList<>(); |
Queue in Java
Topic | Description/Answer | JAVA Code Example |
AbstractQueue | - Abstract class implementing the Queue interface.- Cannot be instantiated directly.- Provides skeletal implementations for some Queue operations. | // Can't be instantiated directly; subclass would provide concrete implementations. |
ArrayBlockingQueue | - Fixed-sized bounded blocking queue backed by an array.- Elements FIFO order.- Useful in producer-consumer scenarios. | ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(10); abq.put(1); |
ConcurrentLinkedQueue | - Non-blocking queue backed by linked nodes.- Implements a concurrent queue using compare-and-swap. | ConcurrentLinkedQueue<Integer> clq = new ConcurrentLinkedQueue<>(); clq.add(2); |
LinkedBlockingQueue | - Optionally bounded blocking queue backed by linked nodes.- Elements FIFO order. | LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<>(); lbq.put(3); |
LinkedTransferQueue | - A transfer queue based on linked nodes.- Useful for producer-consumer scenarios with transfer method. | LinkedTransferQueue<Integer> ltq = new LinkedTransferQueue<>(); ltq.add(4); |
PriorityBlockingQueue | - An unbounded concurrent queue supporting blocking retrievals and uses comparators for sorting.- Items are ordered in natural order or by a comparator provided at queue construction. | PriorityBlockingQueue<Integer> pbq = new PriorityBlockingQueue<>(); pbq.add(5); |
Deque in Java | - Double-ended queue.- Supports addition or removal from both ends.- Can function as both FIFO and LIFO. | Deque<Integer> deque = new ArrayDeque<>(); deque.addFirst(6); deque.addLast(7); |
ArrayDeque | - Resizable array implementation of the Deque interface.- Faster than Stack and LinkedList for queue operations. | ArrayDeque<Integer> ad = new ArrayDeque<>(); ad.addFirst(8); |
Concurrent LinkedDeque | - A concurrent deque backed by linked nodes.- Non-blocking deque operations. | // As of my last training data in January 2022, Java doesn't have a built-in ConcurrentLinkedDeque. Code N/A |
LinkedBlocking Deque | - An optionally bounded blocking deque based on linked nodes.- Elements FIFO order. | LinkedBlockingDeque<Integer> lbd = new LinkedBlockingDeque<>(); lbd.putFirst(9); |
Priority Queue in Java | - Queue implementing priority for elements.- Elements ordered in natural order or by a comparator provided at queue construction. | PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(10); |
Map in Java
Topic | Description/Answer | JAVA Code Example |
EnumMap | - Specialized Map implementation for enum keys.- More efficient than a general-purpose map. | EnumMap<Days, String> dayMap = new EnumMap<>(Days.class); dayMap.put(Days.MONDAY, "Workday"); |
HashMap | - Part of the Java Collections Framework.- Uses hashing to store key-value pairs.- Permits null keys and values. | HashMap<String, Integer> map = new HashMap<>(); map.put("one", 1); |
Working of HashMap | - Uses hash codes of keys.- Hash collisions resolved using linked list or tree structures.- Resize itself when a threshold is reached. | // No direct code; the internal mechanism of HashMap handles this. |
Traverse through a HashMap in Java | - Various methods: keySet(), values(), and entrySet(). | for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } |
WeakHashMap | - Map where keys are weak references.- An entry gets garbage collected if no strong references to its key exist. | WeakHashMap<String, String> weakMap = new WeakHashMap<>(); weakMap.put(new String("key"), "value"); |
LinkedHashMap | - Extends HashMap.- Maintains insertion order or access order. | LinkedHashMap<String, Integer> lMap = new LinkedHashMap<>(); lMap.put("two", 2); |
IdentityHashMap | - Uses reference equality for keys.- Not using object's equals() and hashCode() methods. | IdentityHashMap<String, Integer> iMap = new IdentityHashMap<>(); iMap.put(new String("three"), 3); |
ConcurrentHashMap | - Thread-safe version of HashMap.- Allows concurrent modifications without locking the whole map. | ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<>(); chm.put("four", 4); |
Dictionary | - Obsolete, abstract class.- Represents key/value storage.- Use newer implementations like HashMap. | // Deprecated; Example not recommended. Use HashMap or other newer structures. |
HashTable | - Similar to HashMap but synchronized.- Does not allow null keys or values. | Hashtable<String, Integer> table = new Hashtable<>(); table.put("five", 5); |
SortedMap | - Interface for key-ordered maps.- Guarantees keys to be in ascending order. | SortedMap<String, Integer> smap = new TreeMap<>(); smap.put("six", 6); |
TreeMap | - Red-Black tree based implementation of the Map interface.- Keeps keys in natural order or based on a comparator. | TreeMap<String, Integer> tmap = new TreeMap<>(); tmap.put("seven", 7); |
Stack | - Extends Vector.- Last-In-First-Out (LIFO) data structure. | Stack<Integer> stack = new Stack<>(); stack.push(8); int top = stack.pop(); |
Vector | - Synchronized, resizable-array implementation of the List interface.- Legacy, better to use ArrayList in non-thread-safe situations or other concurrent lists in multithreaded. | Vector<Integer> vector = new Vector<>(); vector.add(9); |
Set in Java
Topic | Description/Answer | JAVA Code Example |
AbstractSet | - Abstract implementation of the Set interface.- Serves as a base for creating custom set implementations. | // Abstract; cannot be instantiated directly. Extend it to create custom sets. |
EnumSet | - Specialized set for use with enum types.- Compact and efficient. | EnumSet<Days> weekend = EnumSet.of(Days.SATURDAY, Days.SUNDAY); |
HashSet | - Part of the Java Collections Framework.- Uses hashing to store elements.- Doesn't guarantee order.- Allows one null element. | HashSet<String> hSet = new HashSet<>(); hSet.add("one"); |
TreeSet | - Implements NavigableSet interface.- Red-Black tree based structure.- Elements are ordered using natural ordering or a comparator. | TreeSet<Integer> tSet = new TreeSet<>(); tSet.add(2); |
SortedSet | - Interface for ordered sets.- Elements are ordered in ascending manner. | SortedSet<String> sSet = new TreeSet<>(); sSet.add("three"); |
LinkedHashSet | - Extends HashSet.- Maintains insertion order of elements. | LinkedHashSet<String> lhSet = new LinkedHashSet<>(); lhSet.add("four"); |
NavigableSet | - Extended version of the SortedSet.- Offers methods to navigate the set. | NavigableSet<Integer> nSet = new TreeSet<>(); nSet.add(5); int lower = nSet.lower(5); |
ConcurrentSkipListSet | - Thread-safe version of a SortedSet.- Implemented using skip list data structure.- Provides scalable concurrent navigable operations. | ConcurrentSkipListSet<Integer> csSet = new ConcurrentSkipListSet<>(); csSet.add(6); |
CopyOnWriteArraySet | - Thread-safe variant of a Set.- All mutative operations (add, set, and so on) are implemented by making a new copy of the underlying array, hence the name "CopyOnWrite".- Best for read-heavy environments. | CopyOnWriteArraySet<String> cwSet = new CopyOnWriteArraySet<>(); cwSet.add("seven"); |
Exception Handling in Java
Topic | Description/Answer | JAVA Code Example |
Exceptions in Java | - An event that disrupts the normal flow of a program.- Used to handle runtime errors. | java try { int[] arr = new int[5]; arr[10] = 50; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bounds!"); } |
Types of Exceptions | - Checked: Checked at compile-time.- Unchecked: Checked at runtime. | java // Checked: IOException, SQLException // Unchecked: NullPointerException, ArithmeticException |
Difference between Checked and Unchecked Exceptions | - Checked: Must be caught or declared in the method signature.- Unchecked: Derived from RuntimeException and doesn't need to be declared or caught. | // Checked: throw new IOException("IO error"); // Unchecked: throw new NullPointerException("Null reference"); |
Try, Catch, Finally, throw, and throws | - Used for exception handling in Java.- Allows for graceful error handling and recovery. | java try { int div = 10/0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("This always executes"); } |
Flow control in Try catch block | - Execution moves to the catch block if an exception occurs.- finally block always executes. | java try { return; } catch (Exception e) { } finally { System.out.println("Finally block"); } // Outputs "Finally block" even if return is in try block. |
Throw vs Throws | - throw: Used to explicitly throw an exception.- throws: Declares that a method might throw exceptions. | java void someMethod() throws IOException { // method body } void anotherMethod() { throw new ArithmeticException(); } |
Final vs Finally vs Finalize | - final: No further modification allowed (used with classes, methods, variables).- finally: Always executed after try-catch.- finalize: Called before garbage collection. | java final int x = 10; try { // some code } finally { // cleanup code } protected void finalize() { System.out.println("object is garbage collected"); } |
User-defined custom exception | - Custom exceptions created by extending Exception class.- Useful for specific error conditions in an application. | java class CustomException extends Exception { public CustomException(String message) { super(message); } } |
Chained Exceptions | - One exception causes another exception.- Helpful for debugging as it keeps the history of exceptions. | java try { throw new IOException("IO Error"); } catch(IOException e) { throw new RuntimeException("Runtime Error", e); } |
Null pointer Exceptions | - Occurs when calling a method or accessing a property on a null object. | java String str = null; try { int length = str.length(); } catch (NullPointerException e) { System.out.println("Null Pointer Exception caught"); } |
Exception handling with method Overriding | - The overridden method should not throw broader exceptions than the parent method.- If the parent doesn't throw an exception, the child can only throw unchecked exceptions, throwing checked exceptions will lead to a compile-time error. | java class Parent { void show() {} } class Child extends Parent { void show() throws ArithmeticException {} } |
Multithreading in Java
Topic | Description/Answer | JAVA Code Example |
Introduction to Multithreading in Java | - Process of executing multiple threads concurrently.- Enhances performance as tasks run simultaneously. | class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } |
Lifecycle and Stages of a Thread | - New- Runnable- Running- Blocked/Waiting- Terminated | N/A |
Thread Priority in Java | - Each thread has a priority.- Ranges from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10). | Thread t = new Thread(); t.setPriority(7); |
Main Thread in Java | - The default thread that executes the main method.- Can be controlled using the Thread class. | public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t.getName()); } |
Thread class | - Built-in Java class used to create and manage threads. | class MyThread extends Thread { public void run() { // thread task } } |
Runnable interface | - An alternative way to create threads by implementing the Runnable interface. | class MyRunnable implements Runnable { public void run() { // thread task } } |
How to name a thread | - Use the setName() method of the Thread class. | Thread t = new Thread(); t.setName("MyThread"); |
start() method in thread | - Used to begin the execution of a thread.- Invokes the run() method. | Thread t = new Thread(); t.start(); |
Difference between run() and start() Method | - run(): Just a method call.- start(): Begins a new thread of execution and invokes the run() method. | new Thread().run(); // No new thread started new Thread().start(); // New thread started |
sleep() method | - Pauses the execution of the current thread for a specified period. | try { Thread.sleep(2000); } catch (InterruptedException e) { } |
Daemon thread | - A low-priority thread running in the background.- It terminates when all user threads terminate. | Thread t = new Thread(); t.setDaemon(true); |
Thread Pool in Java | - A group of worker threads ready for execution.- Reuses threads to optimize performance. | ExecutorService executor = Executors.newFixedThreadPool(5); executor.submit(new MyRunnable()); |
Thread Group in Java | - Represents a set of threads.- Provides a mechanism to group multiple threads as a single unit. | ThreadGroup tg = new ThreadGroup("MyGroup"); Thread t = new Thread(tg, new MyRunnable(), "Thread1"); |
Thread Safety in Java | - Techniques to ensure multiple threads can access shared resources without interference.- Synchronized methods, blocks are used for this. | public synchronized void safeMethod() { // thread-safe task } |
ShutdownHook | - Mechanism to execute a piece of code just before the JVM shuts down. | java Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("JVM shutdown hook"); } }); |
Multithreading Tutorial | - A detailed guide or lesson that explains various aspects of multithreading.- It provides practical examples and usage of multithreading concepts. | N/A |
Synchronization in Java
Topic | Description/Answer | JAVA Code Example |
Java Synchronization | - Mechanism that prevents multiple threads from accessing shared resources concurrently.- Ensures thread safety. | synchronized void syncMethod() { // code here } |
Importance of Thread synchronization in Java | - Prevents data inconsistency.- Avoids race conditions.- Ensures reliable and predictable results. | N/A |
Method and Block Synchronization in Java | - Method: entire method is synchronized.- Block: only a particular section of code is synchronized. | java synchronized void syncMethod() { // method } synchronized(obj) { // block } |
Local frameworks vs thread synchronization | - Local frameworks: Allow data access in a thread-safe manner without explicit synchronization.- Thread synchronization: Explicit way to ensure only one thread accesses shared data at a time. | N/A |
Difference between Atomic, Volatile, and Synchronized | - Atomic: Operations are indivisible and completed without interruption.- Volatile: Variable's value is read directly from memory, ensuring latest value.- Synchronized: Ensures only one thread can execute a synchronized block/method at a time. | java AtomicInteger atomicInt = new AtomicInteger(0); volatile boolean flag; synchronized void syncMethod() { // code } |
Deadlock in Multithreading | - A situation where two or more threads wait for each other to release resources, causing them to block indefinitely. | N/A |
Deadlock Prevention and Avoidance | - Prevention: Ensure a global order of acquiring locks.- Avoidance: Use algorithms like Banker's algorithm to check if safe to allocate resources. | N/A |
Difference between Lock and Monitor in Concurrency | - Lock: Explicit locking mechanism, more flexible than monitors.- Monitor: Implicit locking mechanism using synchronized keyword. | java Lock lock = new ReentrantLock(); lock.lock(); try { // critical section } finally { lock.unlock(); } synchronized(this) { // monitor } |
Reentrant Lock | - A lock that allows its holder to lock it multiple times.- Ensures fairness and supports conditions. | java ReentrantLock reentrantLock = new ReentrantLock(); reentrantLock.lock(); try { // code } finally { reentrantLock.unlock(); } |
File Handling in Java
Topic | Description/Answer | JAVA Code Example |
File Class in Java | - Represents filesystem paths.- Used for file and directory operations. | File file = new File("path/to/file.txt"); |
How to create files in Java | - Use createNewFile() method of the File class.- Returns true if the file is created successfully, else false. | java File file = new File("newfile.txt"); boolean isCreated = file.createNewFile(); |
How to read files in Java | - Use FileReader or Scanner for text files.- Use FileInputStream for binary files. | java FileReader fr = new FileReader("file.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); |
How to write on files in Java | - Use FileWriter for text files.- Use FileOutputStream for binary files. | java FileWriter fw = new FileWriter("file.txt"); fw.write("Hello, World!"); fw.close(); |
How to delete a file in Java | - Use delete() method of the File class.- Returns true if the file is deleted successfully, else false. | java File file = new File("deletefile.txt"); boolean isDeleted = file.delete(); |
File Permissions | - Check and set file/directory read, write, and execute permissions.- Methods include canRead(), canWrite(), setReadOnly(), etc. | java File file = new File("file.txt"); boolean canRead = file.canRead(); |
FileReader | - Used for reading character files.- Reads text files in the system's default encoding. | java FileReader fr = new FileReader("file.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); |
FileWriter | - Used for writing character files.- Writes text files in the system's default encoding. | java FileWriter fw = new FileWriter("file.txt"); fw.write("Hello, World!"); fw.close(); |
FileDescriptor class | - Represents an open file or an open socket.- Provides a mechanism to get the standard input, output, and error streams. | java FileOutputStream fos = new FileOutputStream("file.txt"); FileDescriptor fd = fos.getFD(); |
RandomAccessFile class | - Allows to both read and write to a file, and to move back and forth.- Especially useful when you need to make updates in the middle of a file without overwriting the entire file. | java RandomAccessFile raf = new RandomAccessFile("file.txt", "rw"); raf.writeUTF("Hello!"); raf.seek(0); String str = raf.readUTF(); raf.close(); |
Java Regex
Topic | Description/Answer | JAVA Code Example |
Introduction to Java Regex | - Short for Regular Expression.- Provides a way to match strings against a pattern.- Useful for text processing tasks like search, match, and text extraction. | Pattern pattern = Pattern.compile("[a-z]+"); Matcher matcher = pattern.matcher("hello"); |
How to write Regex expressions | - Consist of literals and metacharacters.- For example: \d for digits, . for any character.- Can include quantifiers like *, +, ? to specify how many times a pattern should occur. | String regex = "\\d{3}-\\d{2}-\\d{4}"; |
Matcher class | - Used to match character sequences against a pattern.- Provides methods like find(), group(), and matches(). | java Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher("123 abc 456"); while(matcher.find()) System.out.println(matcher.group()); |
Pattern class | - Represents a compiled regex expression.- Provides static compile() method to compile regex string.- Used to create a Matcher object. | Pattern pattern = Pattern.compile("[a-z]+"); |
Quantifiers | - Specifies how many times a pattern should occur.- Common ones include: * - 0 or more times + - 1 or more times ? - 0 or 1 time {n} - exactly n times {n,} - n or more times {n,m} - between n and m times | String regex = "\\d{3,5}"; |
Character class | - Defines a set of characters to match.- Enclosed in [].- Common ones include: [a-z] - any lowercase letter [A-Z] - any uppercase letter [0-9] - any digit [^a-e] - any character except a to e | String regex = "[A-Za-z0-9]"; |
Java IO
Topic | Description/Answer | JAVA Code Example |
Introduction to Java IO | - Java's Input/Output library.- Used for reading from and writing to data sources (like files). | N/A |
Reader Class | - Abstract class for reading character streams.- Many classes like FileReader and BufferedReader extend Reader. | java Reader reader = new FileReader("example.txt"); |
Writer Class | - Abstract class for writing to character streams.- Many classes like FileWriter and BufferedWriter extend Writer. | java Writer writer = new FileWriter("example.txt"); |
FileInput stream | - Reads raw byte data.- Useful for binary files like images. | java FileInputStream fis = new FileInputStream("example.jpg"); |
File Output stream | - Writes raw byte data.- Useful for binary files like images. | java FileOutputStream fos = new FileOutputStream("output.jpg"); |
BufferedReader Input Stream | - Reads text from a character input stream.- Buffers characters for efficient reading. | java BufferedReader br = new BufferedReader(new FileReader("example.txt")); String line = br.readLine(); |
BufferedReader Output stream | - Seems to be a mixup. BufferedReader is for input. BufferedWriter would be the output counterpart. | java BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); bw.write("Hello, World!"); |
BufferedReader vs Scanner | - BufferedReader is faster and buffers input.- Scanner is more versatile and can parse different types of input. | N/A |
Fast I/O in Java | - Techniques to speed up I/O operations.- Using buffers, avoiding frequent disk I/O, etc. | java BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
Java Networking
Topic | Description/Answer | JAVA Code Example |
Introduction to Java Networking | - Overview of networking capabilities in Java.- Allows communication between applications over the network. | N/A |
TCP architecture | - Transmission Control Protocol.- Connection-oriented.- Reliable data transfer. | N/A |
UDP architecture | - User Datagram Protocol.- Connectionless.- Faster but less reliable than TCP. | N/A |
IPV4 vs IPV6 | - IPV4: 32-bit address, 4 billion addresses.- IPV6: 128-bit address, vastly larger address space. | N/A |
Connection-oriented vs connectionless protocols | - Connection-oriented: Establishes connection before data transfer (e.g., TCP).- Connectionless: Data sent without establishing a connection (e.g., UDP). | N/A |
Socket programming in Java | - Technique to communicate between computers using TCP or UDP. | java Socket socket = new Socket("localhost", 8080); |
Server Socket class | - Used to create servers that listen for incoming client connections. | java ServerSocket serverSocket = new ServerSocket(8080); Socket clientSocket = serverSocket.accept(); |
URL class and methods | - Represents a Uniform Resource Locator.- Used to access and manipulate URLs. | java URL url = new URL("https://www.example.com"); InputStream is = url.openStream(); |
Java SE 8 Features
Topic | Description/Answer | JAVA Code Example |
Lambda Expressions | - Anonymous function without a name.- Short block of code that takes parameters and returns a value. | java (a, b) -> a + b |
Streams API | - Introduced in Java 8.- Used for processing sequences of elements (e.g., collections). | java list.stream().forEach(System.out::println); |
New Date/Time API | - Introduced in Java 8.- Provides improved date and time capabilities. | java LocalDate date = LocalDate.now(); |
Default Methods | - Allows interface to have methods with implementations.- Useful for backwards compatibility. | java default void myMethod() { System.out.println("Default Implementation"); } |
Functional Interfaces | - Interface with just one abstract method.- Can have multiple default or static methods. | java @FunctionalInterface interface MyFunc { void method(); } |
Method references | - Shortened syntax for methods used as arguments.- Used with Stream API and lambda. | java System.out::println |
Optional class | - Container object that may or may not contain a non-null value.- Helps in handling potential null values. | java Optional<String> opt = Optional.ofNullable("test"); |
Stream Filter | - Used to filter elements of stream based on condition. | java list.stream().filter(num -> num > 5).collect(Collectors.toList()); |
Type Annotations | - Allows annotations to be used in any place where type is used.- Helps in improved type checking. | java @NonNull String name; |
String Joiner | - Used to construct a sequence of characters separated by a delimiter.- Can add prefix and suffix. | java StringJoiner joiner = new StringJoiner(", "); joiner.add("one").add("two"); System.out.println(joiner); |
Java Date & Time
Topic | Description/Answer | JAVA Code Example |
Date Class in Java | - Represents a specific instant in time.- Part of java.util package. | Date date = new Date(); |
Methods of the Date class | - Provides various methods to manipulate date.- Examples: before(), after(), getTime() | long time = date.getTime(); |
Java Current Date and time | - Can be obtained using the Date class.- Represents the current moment in time. | Date currentDate = new Date(); System.out.println(currentDate); |
Compare dates in Java | - Compare two date instances for chronological order.- Use methods like before() and after(). | java if(date1.before(date2)) { System.out.println("Date1 is before Date2"); } |
Java JDBC
Topic | Description/Answer | JAVA Code Example |
Introduction to Java JDBC | - JDBC stands for Java Database Connectivity.- API for connecting Java applications to databases.- Provides methods to query and update data. | N/A |
JDBC Driver | - Acts as an interface between the Java application and the database.- Different types for different databases (e.g., MySQL, Oracle). | Class.forName("com.mysql.cj.jdbc.Driver"); |
JDBC Connection | - Represents a session between Java application and database.- Required to send commands and receive results. | Connection conn = DriverManager.getConnection(url, user, password); |
Types of Statements in JDBC | - There are 3 main types:1. Statement2. PreparedStatement3. CallableStatement | java Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(query); |
JDBC Tutorial | - A guide or set of instructions to help users understand and use the JDBC API effectively. | N/A |
Java Miscellaneous
Topic | Description/Answer | JAVA Code Example |
Introduction to Reflection API | - Allows for introspection of classes, methods, fields, etc.- Used for retrieving class information at runtime. | Class<?> cls = Class.forName("java.lang.String"); |
Java IO Tutorial | - Guide on Java Input/Output operations.- Covers streams, readers, writers, and more. | FileReader fr = new FileReader("sample.txt"); |
JavaFX Tutorial | - Framework for creating desktop applications in Java.- Offers a rich set of graphics and media API. | Stage stage = new Stage(); stage.setTitle("Hello JavaFX"); |
Java RMI | - Stands for Remote Method Invocation.- Allows invoking methods on a remote object in a different JVM. | N/A |
How to Run Java RMI application? | - Requires setup of both client and server side.- Needs rmiregistry tool. | java -cp . -Djava.rmi.server.codebase=file:./ Server |
Java 17 New Features | - Latest long-term support release as of now.- Comes with new features, enhancements, and performance improvements. | N/A |
Interview Questions on Java
Topic | Description/Answer | JAVA Code Example |
What is Java? | - Object-oriented programming language.- Platform-independent.- Known for its "Write Once, Run Anywhere" principle. | N/A |
Features of Java | - Simple- Object-oriented- Robust- Secure- Architecture-neutral- Portable- High performance | N/A |
Difference between JDK, JRE, and JVM | - JDK: Java Development Kit- JRE: Java Runtime Environment- JVM: Java Virtual Machine | N/A |
Explain garbage collection in Java | - Process to reclaim memory.- Frees space taken by unreferenced objects.- Executed by Garbage Collector. | System.gc(); |
Final vs finally vs finalize | - Final: constant declaration/inheritance restriction.- Finally: always executed block after try-catch.- Finalize: method to clean up before garbage collection. | final int x = 10;try {} catch(Exception e) {} finally {} |
Overloading vs Overriding | - Overloading: same method name, different parameters.- Overriding: same method name, same parameters in child class. | void display(int a) vs @Override void display() |
Describe access modifiers in Java | - Private, Protected, Public, Default.- Control visibility and accessibility of classes, methods, and variables. | public class Testprivate int x; |
Explain the 'static' keyword | - Belongs to the class, not instance.- Used with variables, methods, blocks, nested classes. | static int counter;static void display() {} |
What are Java packages? | - Group related classes and interfaces.- Provide access protection and namespace management. | package com.example; |
Explain exception handling | - Mechanism to handle runtime errors.- Uses try, catch, throw, throws, and finally keywords. | try { throw new Exception(); } catch (Exception e) {} finally {} |
Describe the 'transient' keyword | - Variables marked as transient won't be serialized.- Used in object serialization. | transient int tempValue; |
What are Java annotations? | - Metadata about code.- Provide information about other annotations, classes, methods, variables. | @Override@Deprecated |
Difference between Array and ArrayList | - Array: fixed size, needs to specify size.- ArrayList: dynamic, can grow or shrink. | int[] arr = new int[5];ArrayList<Integer> list = new ArrayList<>(); |
Describe 'synchronized' keyword | - Used to lock an object for any shared resource.- Helps in achieving thread safety. | synchronized void display() {} |
What is Java reflection? | - API to inspect Java classes, methods, fields at runtime.- Allows dynamic operation call. | Class<?> cls = obj.getClass(); |
Explain the 'volatile' keyword | - Indicates a variable can be accessed by multiple threads.- Ensures variable is read from main memory, not thread's cache. | volatile boolean flag; |
Java Enum | - Special data type.- Represents a group of constants (variables that cannot change). | enum Colors {RED, BLUE, GREEN;} |
Describe 'this' keyword | - Refers to the current instance of a class.- Can be used to differentiate between class attributes and parameters with the same name. | this.value = value; |
What is inheritance in Java? | - Mechanism where a new class acquires properties of another class.- Helps in achieving reusability. | class Child extends Parent {} |
Describe Java's 'super' keyword | - Refers to immediate parent class object.- Used to call parent class methods, constructors. | super();super.display(); |
- Get link
- X
- Other Apps
Comments
Post a Comment