Complete Core Java Final PDF
Document Details
Uploaded by Deleted User
2024
Tags
Summary
This document is a set of notes covering various topics in Core Java. The document is organized into different sections, such as Java Introduction, Basic Java, Java Data Types and Variables, and so on, covering many Java topics and concepts. It's a good resource for learning Core Java, possibly for study or review purposes.
Full Transcript
Core Java 1. Java Introduction 2. Basic Java 3. Java Data Types and Variables 4. Java Operators 5. Java Decision Making, Looping 6. Java Packages 7. Java String 8. Java Classes and Objects 9. Java 8,9,10..22 10.Java Methods 11.Java Constructors 12.Java Modifiers 13.Java Blo...
Core Java 1. Java Introduction 2. Basic Java 3. Java Data Types and Variables 4. Java Operators 5. Java Decision Making, Looping 6. Java Packages 7. Java String 8. Java Classes and Objects 9. Java 8,9,10..22 10.Java Methods 11.Java Constructors 12.Java Modifiers 13.Java Blocks 14.Java Static and Final Keywords 15.Java Inner Classes 16.Java OOPS 17.Java Encapsulation 18.Java Inheritance 19.Java Super and This Keyword 20. Java Method Overloading 21.Java Method Overriding 22.Java Abstraction 23.Java Polymorphism 24.Java Exception Handling 25.Java File Handling 26.Java Multithreading 27.Java Collection Framework 28.Java Wrapper Class 29.Java I/O Stream 30.Java Object Input and output 31.Java Arrays 32.Java Generics 33.Miscellaneous All Topic of Core Java Tuesday, December 10, 2024 12:35 AM Java Introduction 1. What is Java 2. Java Interpreter 3. Features of Java 4. Download and Install JDK in Windows 5. What is JDK (Java Development Kit) 6. First Simple Java Program: Hello World 7. Bytecode in Java 8. Download and Install Eclipse IDE for Java Developers 9. What is JRE (Java Runtime Environment) in Java 10. How to Write, Compile, and Run Simple Java Program in Eclipse 11. What is JVM (Java Virtual Machine) in Java 12. 26 Vital Difference Between C and Java 13. What is Java Compiler 14. 22 Vital Difference Between C++ and Java Basic Java 1. Java Tokens 2. Identifiers in Java 3. Java Character Set 4. Java Comments 5. Reserve Keywords in Java 6. Escape Sequence in Java Java Data Types and Variables -16 1. Data Types in Java 2. Java Variables 3. Non-primitive Data Types in Java 4. Scope of Variables 5. Memory Allocation for Data Types 6. Constants in Java Java Operators -24 1. Operators in Java 2. Unary Operators 3. Relational Operators -27 4. Conditional Operators 5. Logical Operators 6. Bitwise Operators 7. Assignment Operators 8. Shift Operators Java Decision Making, Branching, and Looping 1. Conditional Control Statements in Java 2. Java Nested For Loop with Example 3. If Statement in Java with Example 4. For Each Loop in Java with Example 5. If-else in Java with Example 6. Switch Statement in Java with Example 7. Nested and Infinite Loops in Java Java Break Statement with Example All Interview inone Page 1 8. Java Break Statement with Example 9. While Loops in Java with Example 10. Java Continue Statement with Example 11. Do While Loop in Java with Example 12. Labelled Loop in Java with Example 13. For Loop in Java with Example Java Packages 1. Packages in Java with Example Java String Interview Question 31 1. String and Ways of String creat 2. String Control Pol Java Classes and Objects 1. Classes and Objects in Java with Realtime Example 2. Life Cycle of Object in Java 3. How to Create Objects in Java 4. Anonymous Object in Java 5. Object Declaration and Initialization 6. Types of Classes in Java Java 8,9,10..22 1. Java 8 - 50 2. Java 8 coding Interview - 56 3. Java Stream API -63 4. Java Stream API Coding -67 5. Key Feature all Version -75 Java Methods -82 1. Methods in Java with Example 2. Java Call by Value and Call by Reference 3. Public Static Void Main(String[ ] args) 4. How to Call Methods with Parameters in Java 5. Java Arguments and Parameters 6. Return Statement in Java with Example Java Constructors -84 1. Constructors in Java with Examples 2. Java Copy Constructor with Example 3. Constructor Overloading in Java with Examples 4. Private Constructor in Java with Example 5. Constructor Chaining in Java with Examples Java Modifiers -95 1. Access Modifiers in Java with Example 2. Java Non-access modifiers Java Blocks - 1. Instance Block in Java with Example Java Static and Final Keywords -98 1. Static Variable in Java with Example 2. Java Static Block with Example 3. Static Method in Java with Example 4. Final Keyword in Java with Example -107 5. Can We Override Static Method in Java Java Inner Classes All Interview inone Page 2 Java Inner Classes 1. Inner Classes in Java with Realtime Example 2. Anonymous Inner Class in Java with Example 3. Normal Inner Class in Java with Example 4. Nested Inner Class in Java with Example 5. Method Local Inner Class in Java Java Object-oriented Programming System -122 OOPs Concepts in Java with Realtime Example Java Encapsulation - 125 1. Encapsulation in Java with Realtime Example 2. Top 5 Encapsulation Program in Java for Practice 3. Getter and Setter in Java with Example Java Inheritance -129 1. Inheritance in Java with Realtime Example 2. Java Has-A Relationship 3. Superclass and Subclass in Java 4. Java Association with Example 5. Behavior of Access Modifiers in Inheritance 6. Aggregation in Java with Example 7. Types of Inheritance in Java with Example 8. Composition in Java with Example 9. Top 10 Inheritance Interview Programs 10. Association vs Aggregation vs Composition 11. Class Relationships in Java 12. Multiple Inheritance in Java with Example Java Super and This Keyword - 135 1. Super Keyword in Java 2. Difference between Super and This Keyword 3. This Keyword in Java Java Method Overloading - 149 1. Method Overloading in Java 2. Class Casting in Java 3. When to Use Method Overloading in Java 4. Upcasting and Downcasting in Java 5. Type Conversion and Casting in Java 6. Java Method Overloading Interview Programs for Practice 7. Automatic Type Promotion in Method Overloading Java Method Overriding - 151 1. Method Overriding in Java with Example 2. Method Hiding in Java with Example 3. Covariant Return Types in Java 4. Dynamic Method Dispatch in Java 5. Rules of Exception Handling with Method Overriding 6. Method Overriding Interview Programs for Practice 7. Method Overloading vs Method Overriding Java Abstraction - 157 1. Abstraction in Java with Realtime Example 2. Abstract Class vs Interface Java Interface with Example All Interview inone Page 3 3. Java Interface with Example 4. Class vs Interface 5. Use of Interface in Java Project 6. Default Method in Java 8 Interface 7. Nested Interface in Java 8. Static Method in Java 8 Interface Java Polymorphism - 136 1. Polymorphism in Java with Realtime Example 2. Static and Dynamic Binding in Java Java Exception Handling - 178 1. Exception Handling in Java 2. When Finally Block Is Not Executed 3. Exception Hierarchy 4. Throw Keyword in Java with Example 5. Checked and Unchecked Exception 6. Throws Keyword in Java with Example 7. Java Try Catch Block 8. User-defined Exception in Java 9. Multiple Catch Block in Java 10. Chained Exception in Java 11. Nested Try Catch Block in Java 12. Throwable Class in Java 13. Finally Block in Java 14. Java Errors 15. Return Statement in Try Catch Finally Block 16. Exception Handling Interview Programs Java File Handling - 197 Java Multithreading - 204 , 207 Java Collections Framework Java Wrapper Class 1. Java Wrapper Class with Example| List of Wrapper | Use of Wrapper | Key Point for Interview 2. Long Class with Example | Use of | Key Point for Interview 3. Number Class with Example | Use of | Key Point for Interview 4. Double Class with Example| Use of | Key Point for Interview 5. Byte Class with Example| Use of | Key Point for Interview 6. Float Class with Example| Use of| Key Point for Interview 7. Short Class with Example| Use of | Key Point for Interview 8. Boolean Class with Example| Use of | Key Point for Interview 9. Integer Class with Example| Use of | Key Point for Interview 10. Java Math Class with Example| Use of | Key Point for Interview Java I/O Stream 1. Java IO Classes and Interface |Use of | Example |key point 2. Java InputStreamReader |Use of | Example |key point 3. Stream in Java with Example |Use of | Example |key point 4. Java FileReader |Use of | Example |key point Java Stream Classes |Use of | Example |key point All Interview inone Page 4 5. Java Stream Classes |Use of | Example |key point 6. Java BufferedReader |Use of | Example |key point 7. Java CharacterStream Classes |Use of | Example |key point 8. Writer in Java |Use of | Example |key point 9. FileInputStream Class |Use of | Example |key point 10. OutputStreamWriter Class |Use of | Example |key point 11. FileOutputStream Class |Use of | Example |key point 12. FileWriter in Java |Use of | Example |key point 13. BufferedInputStream Class |Use of | Example |key point 14. BufferedWriter in Java |Use of | Example |key point 15. BufferedOutputStream Class |Use of | Example |key point 16. PrintWriter in Java |Use of | Example |key point 17. FilterInputStream Class |Use of | Example |key point 18. Java Scanner Class |Use of | Example |key point 19. FilterOutputStream Class |Use of | Example |key point 20. Java Console |Use of | Example |key point 21. DataInputStream Class |Use of | Example |key point 22. Java File |Use of | Example |key point 23. DataOutputStream Class |Use of | Example |key point 24. How to Create a File in Java |Use of | Example |key point 25. SequenceInputStream Class |Use of | Example |key point 26. How to Read Text File in Java |Use of | Example |key point 27. PrintStream in Java |Use of | Example |key point 28. How to Write File in Java |Use of | Example |key point 29. PushBackInputStream in Java |Use of | Example |key point 30. Take Input from User or Keyword |Use of | Example |key point 31. Java RandomAccessFile |Use of | Example |key point 32. Output Formatting in Java |Use of | Example |key point 33. Java Reader Class |Use of | Example |key point Java Object Input and Output 1. Java ObjectInputStream 2. Java Serialization and Deserialization Java Generics 3. Java ObjectOutputStream 1. Generics in Java 4. Externalization in Java 2. Generic Constructor with Example Java Arrays 3. Generic Class with Example 1. Arrays in Java 4. Generic Interface in Java with Example 2. Java Arrays Class Miscellaneous Tutorials 3. Array Initialization with Example 1. Java Annotations 4. Array Copy in Java with Example 2. Command Line Arguments in Java 5. One Dimensional Array with Example 3. Java Custom Annotation 6. Linear Array Search in Java 4. Recursion in Java with Example 7. Java Multidimensional Array 5. Garbage Collection in Java with Example 8. Binary Search in Java for Sorted Array 6. What is Factory Method in Java 9. Three Dimensional Array in Java 7. Object Finalization in Java with Example 10. Sorting Array in Java with Example 8. Java Math Class 11. Passing Arrays to Methods in Java 9. Object Class in Java with Example 12. Array of Objects in Java with Example 10. Object Cloning in Java with Example 13. Return Array in Java from Method All Interview inone Page 5 Java introduction Friday, December 6, 2024 4:56 PM Java is a :- 1. Programming Language : ○ Java is a high-level, object-oriented programming language that enables developers to write instructions for execution. ○ For example "teacher" who gives the instructions to students to perform specific tasks, developers use Java to instruct the system to execute desired operations like addition, subtraction, division, login, register, add items into cart, online payment etc. ○ Developers can use Java to perform various tasks such as addition, subtraction, user authentication (login and registration), adding items to a cart, or processing online payments. ○ It is designed to be simple, object-oriented, and user-friendly, similar to languages like C and C++. 2. Platform : ○ Java is a platform that provides a robust environment, or "stage," where developers can execute Java code. This platform ensures all necessary tools and libraries are available for the code to run smoothly. ○ For example "stage in a theater" provides the setup for actors to perform their roles, Java provides the environment where we can write, run and manage Java programs easily. Java was originally developed by James Gosling and his team of engineers at Sun Microsystems. its development was started in June 1991 and first public version was released in 1996. In 2010, Oracle Corporation acquired Sun Microsystems, which made Oracle the owner of Java and its associated technologies. Since then, Oracle has been responsible for maintaining and advancing the Java platform. 1995(Java alpha Beta version) 1996(JDK 1.0) The original name of Java was "Oak". James Gosling and his team initially named it after an oak tree that stood outside Gosling's office at Sun Microsystems. However, the name was later changed to Java in 1995 due to trademark issues. The name "Java" was inspired by the Java coffee from Indonesia, as coffee was considered a metaphor for energy and vitality. Java code is written in human-readable form and saved with a.java file extension. This code is then compiled into bytecode by the Java compiler (javac), which is a lower-level, platform-neutral representation of the code. This bytecode is later executed by the Java Virtual Machine (JVM). Example - -> Java Program Example 2. Types of Java Edition MainApp.java There are total 5 editions in Java which are as below :- public class MainApp 1. Java Standard Edition (Java SE) { 2. Java Enterprise Edition (Java EE) public static void main(String[] args) 3. Java Micro Edition (Java ME) { 4. JavaFX System.out.println("Hello, World!"); 5. Java Card } These are explained deeply in below.... } 1. Java Standard Edition (Java SE) Introduction : Java SE is the core edition of the Java platform and provides the foundational APIs and tools for general-purpose programming. It includes basic libraries for data structures, networking, I/O, and more. Applications : Desktop Applications : Java SE is used to create standalone desktop applications, such as productivity software, utilities, and games. Examples include IDEs like IntelliJ IDEA and software like Eclipse. Command-Line Tools : Java SE is also used for developing command-line tools and utilities that run on various operating systems. Small-to-Medium Size Application : Java SE is suitable for developing smaller-scale applications that don’t require the extensive features of Java EE. 2. Java Enterprise Edition (Java EE) Introduction : Java EE (now Jakarta EE) is designed for large-scale, distributed, and multi-tiered applications. It extends Java SE with additional libraries and APIs for enterprise-level development, including web services, component-based architecture, and database interaction. Applications : Web Applications : Java EE is used to build robust web applications using technologies like Servlets, JSP (JavaServer Pages), and JSF (JavaServer Faces). It supports frameworks like Spring and Hibernate. Enterprise Applications : Java EE is ideal for developing complex, scalable enterprise systems like ERP (Enterprise Resource Planning) and CRM (Customer Relationship Management) systems. Web Services : Java EE supports the development of RESTful and SOAP-based web services that allow different systems to communicate over the web. E-Commerce Systems : Java EE is widely used to create large e-commerce platforms that require high availability, scalability, and security. Note: Java EE has been rebranded as Jakarta EE under the Eclipse Foundation. The shift is more about the organization managing the technology rather than the technology itself. 3. Java Micro Edition (Java ME) Introduction : Java ME is a subset of Java SE designed for developing applications on resource-constrained devices like embedded systems, mobile phones, and IoT (Internet of Things) devices. Applications : Mobile Applications : Before the rise of Android, Java ME was the primary platform for developing mobile applications for feature phones and early smartphones. All Interview inone Page 1 and early smartphones. Embedded Systems : Java ME is used in embedded devices such as smart cards, GPS devices, and home automation systems. IoT Applications : Java ME provides a lightweight platform for IoT devices, enabling the development of applications that run on small, connected devices with limited processing power and memory. 4. JavaFX Introduction : JavaFX is a platform for building rich internet applications (RIAs) that can run on various devices. It provides a modern, hardware-accelerated user interface and is often used for creating visually appealing desktop applications. Applications : Rich Internet Applications (RIAs) : JavaFX is used to create interactive, visually rich applications that can run on the desktop, web, or embedded devices. Multimedia Applications : JavaFX is suitable for developing applications that require advanced graphics, media playback, and complex animations. Data Visualization Tools : JavaFX is often used in building tools that visualize complex data, such as charts, graphs, and simulations. 5. Java Card Introduction : Java Card is a specialized edition of the Java platform designed for secure, resource-constrained environments like smart cards and SIM cards. It enables small applications (applets) to run securely on devices with minimal memory and processing power, commonly used in industries requiring high security, such as banking, telecommunications, and government ID systems. Applications : Smart Cards: Java Card is used in the development of applications for smart cards, including payment cards (credit/debit), identification cards, and access control systems. The technology enables secure storage of sensitive data like cryptographic keys and personal identification information. SIM Cards: Java Card powers SIM cards used in mobile phones. It allows telecom providers to securely manage and store subscriber information, including authentication keys and contact information. It also enables Over-the-Air (OTA) updates of applets and services on SIM cards. Secure Authentication: Java Card is used in devices that require strong authentication, such as hardware security tokens (e.g., for two- factor authentication), digital signatures, and encryption devices. The small, secure environment of Java Card makes it ideal for cryptographic operations and secure transaction processing. Contactless Payment Systems: Java Card is commonly employed in contactless payment systems such as NFC-based payment cards and mobile payment solutions. Its secure and lightweight environment ensures the protection of financial transactions. ePassports and ID Cards: Governments use Java Card technology to power ePassports and national ID cards. These cards securely store and manage biometric data and personal identification details to ensure security and privacy in identification and travel systems. 3. Java History The history of Java is a rich and fascinating journey that highlights its evolution from a niche project into one of the most widely used programming languages in the world. Below is a detailed timeline of Java's history, broken down into key milestones: Java Evolution Timeline 1. Early Beginnings (1990-1995) 1990: The Green Project Sun Microsystems, led by James Gosling, Mike Sheridan, and Patrick Naughton, launched the "Green Project" to explore programming for consumer electronics like TVs and VCRs. The goal was to create a simple, platform-independent, and secure language for embedded systems, eventually leading to the rejection of C++ due to its complexity. 1991: Birth of Oak James Gosling began developing a new language called "Oak" to address these challenges. The team built the "Star7" handheld device to demonstrate Oak's potential but failed to gain traction. 1992: Star7 Prototype The Green Project's "Star7" controller was the team's first success, showcasing Oak's GUI features, but the slow adoption of digital electronics led them to shift focus. 1993: Shift to the Internet As the World Wide Web grew, the team saw a new opportunity for Oak’s platform independence and began adapting it for web-based applications. 2. The Birth of Java (1994-1995) 1994: Oak Becomes Java Oak was renamed "Java" due to trademark issues. The name "Java" was chosen after brainstorming, inspired by Java coffee. The team created the first Java-enabled browser, "WebRunner" (later renamed "HotJava"). 1995: Official Release of Java 1.0 Java 1.0 was officially released on May 23, 1995. The "Write Once, Run Anywhere" (WORA) capability became central, allowing Java programs to run on any device with a Java Virtual Machine (JVM). Key components included the Java Development Kit (JDK), Java Runtime Environment (JRE), and the HotJava browser. 1995: Netscape Integrates Java Netscape Navigator became the first web browser to integrate Java, increasing Java's visibility. Java applets enabled dynamic web content, helping developers create interactive web experiences. 3. Java’s Rise to Prominence (1996-2000) All Interview inone Page 2 3. Java’s Rise to Prominence (1996-2000) 1996: Java 1.1 Java 1.1 introduced inner classes, JavaBeans, JDBC, RMI, garbage collection, and enhanced security. The reflection API was also added for runtime class manipulation. 1997: Java 2 Platform (J2SE 1.2) Java 2 introduced the Swing GUI toolkit, Collections Framework, and the HotSpot JVM. Java was rebranded into three editions: ○ J2SE (Standard Edition) for general development ○ J2EE (Enterprise Edition) for distributed applications ○ J2ME (Micro Edition) for mobile devices and embedded systems 1998: Java Enterprise Edition (J2EE) J2EE focused on enterprise applications with technologies like Servlets, JSP, and EJBs. Swing provided a flexible GUI development approach. 1999: Java Community Process (JCP) Sun Microsystems established the JCP to formalize Java's evolution. JavaServer Pages (JSP) and Servlets were introduced, revolutionizing web development. 4. Expansion and Maturity (2000-2005) 2000: J2ME for Mobile Devices J2ME became a standard for mobile phones and embedded devices, particularly in early feature phones. 2002: Java 2 Standard Edition 1.4 (J2SE 1.4) J2SE 1.4 introduced important features like the assert keyword, regular expressions, and the NIO package, along with security enhancements. 2004: Java 5 (J2SE 5.0) Java 5 introduced generics, enhanced for-loops, autoboxing/unboxing, enumerated types, annotations, and the java.util.concurrent package. 2005: Emergence of JavaFX JavaFX was introduced for building rich internet applications with multimedia, animations, and modern user interfaces. 5. The Open-Source Era (2006-2010) 2006: Java Goes Open Source Sun Microsystems announced Java's release under the GNU General Public License (GPL). The OpenJDK project provided an open-source implementation of Java SE. 2007: Android Adopts Java Google adopted Java as the primary language for Android development, significantly increasing Java’s popularity in mobile development. 2009: Oracle Acquires Sun Microsystems Oracle’s acquisition of Sun Microsystems sparked debates about Java's future but also led to new developments in Java's evolution. 2010: Java SE 6 Java SE 6 focused on GUI enhancements, better web service support, and scripting language support. 6. Java’s Continued Evolution (2011-2020) 2011: Java 7 Java SE 7 introduced the try-with-resources statement, the diamond operator, and multi-core support via the Fork/Join framework. 2014: Java 8 Java SE 8 was a landmark release with lambda expressions, the Stream API, a new Date and Time API, and Optional classes. 2017: Java 9 and New Release Cycle Java SE 9 introduced the Java Platform Module System (Project Jigsaw) and a new release model with versions every six months. Java 11 became the first Long-Term Support (LTS) release under this cycle. 2020: Java 15 Java 15 introduced preview features like sealed classes and continued regular updates to the language and performance. 7. Modern Java (2021-Present) 2021: Java 16 and 17 (LTS) Java 17, an LTS release, included sealed classes, pattern matching, and improved garbage collection, solidifying Java’s place in cloud-native and microservices development. 2022: Java 18 and 19 Java 18 added features like a Simple Web Server, while Java 19 introduced structured concurrency and better native code interfacing. 2023: Java 20 and 21 Java 20 introduced scoped values for concurrency, and Java 21 (another LTS) further enhanced developer productivity with virtual threads and pattern matching. 2024 and Beyond Java continues to evolve, with a focus on modularity, cloud-native capabilities, and innovations for AI, ML, and distributed systems. All Interview inone Page 3 Java continues to evolve, with a focus on modularity, cloud-native capabilities, and innovations for AI, ML, and distributed systems. 4. Features of Java Java is a popular programming language known for its simplicity, platform independence, and robustness which makes it versatile for a wide range of applications. Some most important core features in java are as below :- 1. Platform-Independent Definition : Java applications are designed to run on any platform that has a Java Virtual Machine (JVM) without requiring modification. Detailed Explanation : Bytecode : Java source code is compiled into an intermediate form called bytecode (.class files). Bytecode is platform-independent and can be executed on any system with a compatible JVM. This bytecode is portable across different operating systems and hardware configurations. JVM : The JVM is a crucial component of Java’s platform independence. It interprets or compiles bytecode into native machine code specific to the underlying hardware and operating system. By adhering to the JVM specification, Java applications can run consistently on any platform that has a JVM implementation. 2. Object-Oriented Definition : Java is built around the principles of object-oriented programming (OOP), which organizes software design around data, or objects, rather than functions and logic. Detailed Explanation : Encapsulation : Encapsulation involves bundling the data (attributes) and methods (functions) that operate on the data into a single unit called a class. Access to the data is controlled using access modifiers like private, protected, and public, which helps in protecting the integrity of the data and exposing only what is necessary. Inheritance : Inheritance allows one class (subclass) to inherit the fields and methods of another class (superclass). This promotes code reuse and establishes a natural hierarchy. For example, a Dog class can inherit from an Animal class, gaining all its attributes and behaviors. Polymorphism : Polymorphism enables objects to be treated as instances of their parent class rather than their actual class. It allows methods to be overridden in derived classes and provides flexibility in method invocation. For example, a method makeSound() can be defined in a parent class Animal and overridden in subclasses Dog and Cat to produce different sounds. Abstraction : Abstraction involves hiding complex implementation details and showing only the essential features of an object. In Java, abstraction is achieved through abstract classes and interfaces, which define what methods a class should implement without specifying how these methods should be implemented. 3. Robust Definition : Java is designed to be a reliable and error-resistant programming language. Detailed Explanation : Exception Handling : Java uses a structured approach to handle runtime errors through exceptions. The language provides robust exception handling mechanisms using try, catch, finally, and throw keywords, enabling developers to handle and recover from errors gracefully. Automatic Garbage Collection : Java’s garbage collector automatically reclaims memory used by objects that are no longer reachable, reducing the risk of memory leaks and ensuring efficient memory management. Type Checking : Java performs strict type checking at compile-time and runtime. This ensures that operations are performed on compatible data types and helps catch errors early in the development process. 4. Secure Definition : Java incorporates various security features to protect applications from unauthorized access and malicious activities. Detailed Explanation : Bytecode Verification : Before execution, Java bytecode undergoes verification to ensure it adheres to the Java language specification and does not contain illegal code that could compromise the security of the JVM. Sandboxing : Java applets and applications can run in a restricted environment called a sandbox, which limits their ability to access system resources and perform potentially harmful operations. This is especially important for applets running in a web browser. Security Manager : Java includes a security manager that allows applications to set security policies and control access to sensitive system resources like files, network connections, and system properties. 5. Portable Definition : Java's portability allows compiled programs to run on any platform with a JVM, ensuring cross-platform compatibility. Detailed Explanation : Bytecode and JVM : Java compiles code into platform-independent bytecode, executable on any JVM. No Recompilation : Unlike C/C++, Java doesn't require platform-specific recompilation. Standard Libraries : Libraries handle system-specific differences, maintaining consistent behavior. Example : A Java app compiled on Windows runs seamlessly on Linux or macOS if JVM is installed. 6. Simple Definition : Java is designed to be a straightforward and accessible programming language. Detailed Explanation : Syntax and Structure : Java’s syntax is derived from C and C++ but is simplified to remove complex features that often lead to errors. For instance, it eliminates explicit pointers, which can lead to memory leaks and undefined behavior. Automatic Memory Management : Java handles memory allocation and garbage collection automatically, reducing the burden on developers to manage memory manually. This reduces the risk of memory leaks and errors related to memory management. No Multiple Inheritance : Java does not support multiple inheritance (a class cannot inherit from more than one class), which simplifies the design and avoids the “diamond problem” found in languages like C++. Instead, Java uses interfaces to achieve multiple inheritance of All Interview inone Page 4 the design and avoids the “diamond problem” found in languages like C++. Instead, Java uses interfaces to achieve multiple inheritance of type. 7. Multithreaded Definition : Java provides built-in support for concurrent execution, allowing multiple threads to run simultaneously. Detailed Explanation : Threading Support : Java provides a comprehensive threading model with the java.lang.Thread class and the java.util.concurrent package. Threads allow Java applications to perform multiple tasks concurrently, improving performance and responsiveness. Synchronization : Java includes mechanisms to manage access to shared resources among threads. The synchronized keyword and concurrency utilities like ReentrantLock ensure that only one thread can access a critical section of code at a time, preventing race conditions. Concurrency Utilities : The java.util.concurrent package offers high-level concurrency utilities such as thread pools (ExecutorService), concurrent collections (ConcurrentHashMap), and atomic variables (AtomicInteger), which simplify the development of multithreaded applications. 8. Distributed Definition : Java facilitates the development of distributed applications, where components can communicate over a network. Detailed Explanation : Networking Capabilities : Java provides robust networking classes in the java.net package, including support for sockets, URLs, and HTTP. This allows Java applications to communicate over various types of networks. Remote Method Invocation (RMI) : RMI enables Java objects to communicate and invoke methods on objects located remotely. It abstracts the complexities of network communication, making it easier to develop distributed applications. Web Services : Java offers comprehensive support for web services through APIs such as JAX-WS (Java API for XML Web Services) and JAX- RS (Java API for RESTful Web Services). These APIs allow Java applications to interact with other services over the web using standardized protocols like HTTP and SOAP. 9. Dynamic Definition : Java is an adaptable and flexible language, capable of accommodating changes and extending its functionalities. Detailed Explanation : Runtime Polymorphism : Java supports runtime polymorphism, allowing methods to be bound to their implementations at runtime rather than compile-time. This enables flexible and dynamic behavior in Java applications. Reflection : Java’s reflection API allows programs to examine and manipulate the structure and behavior of classes, interfaces, and objects at runtime. This enables dynamic instantiation of classes, invocation of methods, and access to fields, even if their names are not known until runtime. Dynamic Class Loading : Java supports dynamic class loading, where classes can be loaded into the JVM at runtime. This allows for on-the- fly updates and extensibility, making it possible to load and execute classes that were not known at compile-time. 10. High Performance Definition : Java is designed to deliver high performance while maintaining portability and security. Detailed Explanation : Just-In-Time (JIT) Compiler : The JVM includes a Just-In-Time (JIT) compiler that translates bytecode into native machine code at runtime. The JIT compiler optimizes code execution by compiling frequently executed methods, which significantly improves performance. Efficient Memory Management : Java’s garbage collection mechanism is optimized to manage memory efficiently. The JVM uses techniques like generational garbage collection and concurrent garbage collectors to minimize pauses and improve application responsiveness. Optimized Libraries : Java provides a rich set of standard libraries that are highly optimized for performance. These libraries include efficient data structures, algorithms, and utility classes that contribute to the overall performance of Java applications. 11. Rich API Definition : Java offers a comprehensive and extensive set of APIs (Application Programming Interfaces) that simplify development and provide a wide range of functionalities. Detailed Explanation : Core Libraries : Java’s core libraries cover essential functionalities such as data structures (java.util package), input/output (java.io package), networking (java.net package), and concurrency (java.util.concurrent package). These libraries provide ready-to-use components that simplify common programming tasks. Graphics and GUI : Java includes APIs for developing graphical user interfaces (GUIs) and handling graphics. The Swing and JavaFX libraries offer components for building desktop applications, while the java.awt package provides classes for drawing and manipulating graphics. Database Connectivity : Java’s JDBC (Java Database Connectivity) API allows seamless interaction with databases. It supports SQL queries, transactions, and connection pooling, making it easy to integrate Java applications with relational databases. Web and Networking : Java provides extensive support for web development through APIs like Servlets, JSP (JavaServer Pages), and WebSockets. The java.net package also includes classes for working with URLs, HTTP, and sockets, enabling Java applications to communicate over networks. Enterprise APIs : Java EE (Enterprise Edition) offers a suite of APIs for building enterprise-level applications. These include APIs for web services (JAX-WS, JAX-RS), messaging (JMS), and persistence (JPA), among others, which provide a solid foundation for developing scalable and robust enterprise applications. 12. Community Support Definition : Java has a vast and active global community that contributes to its development, provides resources, and supports developers. Detailed Explanation : OpenJDK and Oracle JDK : Java is available as both the open-source OpenJDK and the commercially supported Oracle JDK. The OpenJDK community actively contributes to the language’s development, ensuring that Java remains up-to-date and continues to evolve. All Interview inone Page 5 community actively contributes to the language’s development, ensuring that Java remains up-to-date and continues to evolve. Libraries and Frameworks : The Java community has developed a wide range of libraries and frameworks that extend the language’s capabilities. Popular frameworks like Spring, Hibernate, and Apache Struts simplify development and are widely used in the industry. Forums and Resources : Java developers have access to numerous online forums, documentation, and tutorials. Websites like Stack Overflow, GitHub, and Oracle’s official documentation provide valuable resources for learning and troubleshooting Java-related issues. Conferences and Meetups : The global Java community organizes conferences, meetups, and events where developers can share knowledge, discuss trends, and collaborate on projects. Events like JavaOne and Devoxx are prominent in the Java ecosystem. 13. Scalability and Performance Definition : Java is designed to be scalable and perform efficiently across different types of applications, from small programs to large enterprise systems. Detailed Explanation : Thread Management : Java’s built-in support for multithreading allows developers to create scalable applications that can handle multiple tasks simultaneously. The java.util.concurrent package offers advanced tools for managing thread pools and executing parallel tasks. Load Balancing and Distributed Systems : Java’s ability to handle distributed systems, along with frameworks like Apache Kafka and Spring Cloud, makes it suitable for creating scalable, high-performance applications. These frameworks help in load balancing, message queuing, and managing distributed transactions. Enterprise-Level Scalability : Java EE (now Jakarta EE) provides enterprise-level features like clustering, caching, and session management that are essential for building large, scalable applications. These features allow applications to handle increasing loads without compromising performance. 14. Versatility Definition : Java’s versatility allows it to be used across a wide range of domains and application types, from mobile apps to large-scale enterprise systems. Detailed Explanation : Mobile Applications : Java is the foundation for Android app development, which uses the Android SDK and Java APIs. Android apps are built using Java, making it a key player in the mobile app ecosystem. Web Applications : Java’s robust web frameworks, such as Spring and JavaServer Faces (JSF), make it an excellent choice for developing dynamic and responsive web applications. Java Servlets and JSPs are commonly used for server-side development. Scientific Applications : Java’s reliability, portability, and high performance make it ideal for scientific and research-based applications. Libraries like Apache Commons Math and Java 3D are used for mathematical calculations and visual simulations. Enterprise Solutions : Java is widely used for building enterprise-level applications that require reliability, scalability, and security. Industries such as finance, healthcare, and telecommunications rely on Java for mission-critical systems. 15. Interoperability Definition : Java’s interoperability features allow it to work seamlessly with other programming languages and platforms, enhancing its flexibility in diverse environments. Detailed Explanation : Java Native Interface (JNI) : JNI allows Java code to interact with native applications and libraries written in other languages like C or C++. This feature is particularly useful when integrating Java with existing legacy systems or when performance-critical operations need to be implemented in a lower-level language. Web Services and API Integration : Java supports the development and consumption of web services, enabling integration with external systems through RESTful and SOAP APIs. Java EE provides APIs like JAX-RS and JAX-WS for building and consuming web services. Multilingual Support : Java applications can interact with other languages using scripting APIs and frameworks like Jython (Python on Java) or JRuby (Ruby on Java). This allows developers to leverage the strengths of other languages within a Java environment. 16. Community and Ecosystem Definition : Java benefits from a large, active community and a rich ecosystem that contribute to its development and support. Detailed Explanation : Large Community : Java has a vast and diverse community of developers, enthusiasts, and professionals who contribute to its growth and evolution. The community provides support through forums, blogs, and open-source projects, helping developers solve problems and stay up-to-date with best practices. Rich Ecosystem : The Java ecosystem includes a wide range of tools, libraries, and frameworks that enhance development capabilities. The ecosystem supports various aspects of development, such as build tools (e.g., Maven, Gradle), IDEs (e.g., IntelliJ IDEA, Eclipse), and continuous integration tools (e.g., Jenkins). 5. Usage of Java Java is a versatile and widely-used programming language known for its platform independence, reliability, and scalability. It is employed in various domains, including web development, mobile applications, enterprise systems, and embedded devices. Java’s "write once, run anywhere" capability, thanks to the Java Virtual Machine (JVM), allows developers to create applications that can run on multiple platforms without modification. Additionally, Java's extensive ecosystem of libraries and frameworks supports efficient and effective development across different types of software projects, making it a preferred choice for businesses and developers worldwide. Types of usage 1. Web Development Server-Side Technologies : Java is extensively used in web development, particularly on the server side. Frameworks like Spring, JavaServer Faces (JSF), and Apache Struts help build robust, scalable web applications. Servlets and JSPs : Java Servlets and JavaServer Pages (JSP) are core technologies for building dynamic web content. Servlets handle requests and responses, while JSPs simplify the creation of HTML pages with embedded Java code. 2. Enterprise Applications All Interview inone Page 6 2. Enterprise Applications Enterprise Resource Planning (ERP) : Java is a popular choice for building large-scale enterprise applications. It supports a range of enterprise frameworks and standards like Java EE (Enterprise Edition), which includes EJB (Enterprise JavaBeans), JPA (Java Persistence API), and JMS (Java Message Service). Scalability and Reliability : Java’s ability to handle large-scale transactions, security, and high concurrency makes it suitable for enterprise solutions. 3. Mobile Applications Android Development : Java has been a primary language for developing Android applications. The Android SDK provides tools and libraries for creating mobile apps on the Android platform. While Kotlin is now officially preferred, Java remains a significant part of Android development. 4. Desktop Applications GUI Applications : Java provides libraries like Swing and JavaFX for building cross-platform desktop applications with graphical user interfaces (GUIs). These libraries allow developers to create rich desktop applications that run on various operating systems. 5. Scientific and Research Applications Data Analysis : Java is used in scientific computing and data analysis due to its robustness, portability, and performance. Libraries like Apache Commons Math and JAMA (Java Matrix Library) facilitate complex calculations and data processing. Simulation and Modeling : Java's performance and extensive libraries make it suitable for simulations, modeling, and research applications. 6. Big Data Technologies Hadoop : Java is a key language for Hadoop, a popular framework for distributed storage and processing of large data sets. Hadoop’s components, like MapReduce and HDFS (Hadoop Distributed File System), are written in Java. Apache Kafka : Java is also used with Apache Kafka, a distributed streaming platform that handles real-time data feeds. 7. Embedded Systems Java ME : Java Micro Edition (Java ME) is designed for developing applications on embedded and mobile devices. It’s used in various devices like smartcards, IoT devices, and other resource-constrained systems. 8. Cloud Computing Cloud Platforms : Java is commonly used for building cloud-based applications. It integrates with cloud platforms like AWS (Amazon Web Services), Google Cloud Platform, and Microsoft Azure to create scalable and resilient applications. 6. Java Software If we want to learn Java, we need tools for writing, compiling and running Java code. Here’s a list of software you can use, along with explanations for each :- 1. Java Development Kit (JDK) 2. Text Editors 3. Integrated Development Environments (IDEs) These softwares are explained below.... 1. Java Development Kit (JDK) Introduction : The JDK is a core component for Java development. It includes the Java compiler (javac), Java Runtime Environment (JRE), and other tools which are required for Java Development. Use : The JDK software is used to compile and runs Java programs. Version : We should always try to install "JDK - Long Term Service (LTS) Version" i.e. JDK 8, JDK 11, JDK 17, JDK 21 etc. Download link : Download the JDK Software from this link. How to install : ○ Download the JDK for the respective operating system. ○ Then set the Java Path & JAVA_HOME environment variable. Reference Video : Click Here to see how to download/install JDK Software and How to set Java Path & JAVA_HOME. 2. Text Editors Introduction : These are the pre-installed, lightweight and simple tools available in every platform. Examples : ○ Notepad in Windows Platform ○ Notepad++ ○ TextEdit in macOS ○ Gedit in Linux ○ etc... Use : These are used to write basic java code. 3. Integrated Development Environments (IDEs) Introduction : IDEs are advanced software tools to write Java Code including development, debugging, project management etc. Examples : ○ IntelliJ IDEA ○ Eclipse ○ NetBeans ○ VS Code ○ etc... Reference Video : ○ Click Here to see how to download & install IntelliJ IDEA. ○ Click Here to see how to download & install Eclipse IDE. All Interview inone Page 7 ○ etc... Reference Video : ○ Click Here to see how to download & install IntelliJ IDEA. ○ Click Here to see how to download & install Eclipse IDE. JDK, JRE, JVM What is JDK? The Java Development Kit (JDK) is a software development kit used to develop applications in the Java programming language. It includes ○ various tools which are essential for compiling, running, documenting, packaging, and debugging Java applications, such as The Java Application Launcher (java), Java Compiler (javac), Documentation Generator (javadoc) etc and a runtime environment (Java Runtime Environment or JRE). Below is the diagram showing JDK architecture in Java. Components of JDK :- There are 2 main components in JDK which are as below :- JDK (Java Development Kit) = 1 - Development Tools + 2 - JRE (Java Runtime Environment) 1. Development Tools: Tool Description java The Java Application Launcher: Executes Java applications and applets. It replaces the older jre tool, combining development and deployment functionalities. javac Java Compiler: Converts Java source code into Java bytecode, producing.class files. javado Documentation Generator: Automatically creates HTML documentation from Java source code comments. cjar Archiver and Manager: Packages related class libraries into a single JAR (Java ARchive) file and manages JAR files. jdb Java Debugger: Provides a command-line interface for debugging Java programs. Other Development Tools (you can skip) Tool Description appletviewer Runs and debugs Java applets without a web browser. javah C Header and Stub Generator: Generates C header files and JNI (Java Native Interface) stubs for native methods. javap Class File Disassembler: Displays information about Java class files, including bytecode and structure. javaws Java Web Start Launcher: Launches and manages Java applications distributed via JNLP (Java Network Launch Protocol). jps Java Virtual Machine Process Status Tool: Lists HotSpot JVMs on the system and provides process details. jrunscript Command-Line Script Shell: Allows execution of JavaScript and other scripting languages from the command line. jstack Prints Java stack traces of Java threads, useful for diagnosing thread-related issues (experimental). jstat JVM Statistics Monitoring Tool: Monitors various JVM statistics, such as garbage collection and memory usage (experimental). jstatd jstat Daemon: Provides a network interface to monitor JVM statistics (experimental). and many more.... 2. Java Runtime Environment (JRE): ○ Function: Provides the libraries, Java Virtual Machine (JVM), and other components to run Java applications. ○ Included: The JRE is part of the JDK, and it includes the JVM along with the necessary runtime libraries. Usage of JDK :- Development : Used by developers to create and compile Java applications. Installation : Requires installation on the developer’s machine and is not required for end-users who only need to run Java applications. What is JRE ? The Java Runtime Environment (JRE) is a software platform that enables the execution of Java applications. It works by providing a runtime environment that includes a set of core libraries and Java Virtual Machine (JVM). The JRE allows Java programs to run on any device or operating system without modification, by translating Java bytecode into native machine code that the JVM executes. Below is the diagram showing JRE architecture in JDK. All Interview inone Page 8 without modification, by translating Java bytecode into native machine code that the JVM executes. Below is the diagram showing JRE architecture in JDK. Components of JRE :- There are 4 main components in JDK which are as below :- 1. Java Libraries Java libraries are collections of pre-written code that provide essential functionality for development. They include base libraries (e.g., java.lang, java.util), additional base libraries (e.g., java.beans, java.security), and integration libraries (e.g., JDBC, JNDI) for external system integration. These are divided in 3 main categories :- 1. lang & util Base Libraries (e.g., java.lang, java.util): Provide core classes for Java, including fundamental utilities (e.g., collections, strings, math) and language features (e.g., threading, exceptions). 2. Other Base Libraries (e.g., java.beans, java.security): Provide additional functionality, such as object introspection (beans) and security features (cryptography, authentication). 3. Integration Libraries (e.g., JDBC, JNDI): Offer APIs for database connectivity (JDBC), directory services (JNDI), and integrating with external systems like databases and networks. 2. User interface toolkits :- User interface toolkits in JRE, like AWT, Swing, and Java 2D, provide tools for building graphical user interfaces (GUIs). They offer components for windows, buttons, and graphics rendering, enabling developers to create interactive, visually-rich applications with support for both basic and advanced UI elements and 2D graphics. 3. Deployment :- Deployment in JRE involves packaging and distributing Java applications for execution on client machines. This includes delivering Java programs in formats like JAR or WAR files, ensuring they run within the Java Runtime Environment, often using tools like Java Web Start or applet technology for deployment. 4. Java Virtual Machine :- The Java Virtual Machine (JVM) is an engine that executes Java bytecode. It provides platform independence by allowing Java programs to run on any device with a JVM, handling tasks like memory management, garbage collection, and code optimization. JRE (Java Runtime Environment) = Java Libraries + Unser Interface Toolkits + Deployment + JVM (Java Virtual Machine) Usage of JRE :- Java Runtime Environment (JRE) is used to provide a runtime platform for executing Java applications. It includes the JVM, core libraries, and resources required to run Java programs, ensuring platform independence and handling tasks like memory management, security, and execution of compiled Java code. What is JVM ? The JVM is a part of the Java platform that executes Java bytecode, converting it into machine code for the host system. It provides an abstraction layer between compiled Java code and the operating system. The main use of the JVM is to enable platform-independent execution of Java programs by interpreting or compiling bytecode to machine code, managing memory, ensuring security, Basic and optimizing performance. Architecture Below is the diagram showing JVM architecture in JRE. of JVM is - It is a Runtime Engine responsible to run java based applications. It has two main tasks : 1. load.class file 2. execute.class file Basic Architecture of JVM is : --> Components of JVM :- There are 3 main components in JVM :- 1. Class Loader: The class loader is responsible for dynamically loading Java classes into memory at runtime. It handles loading, linking, and initialization, organizing classes into namespaces and ensuring they are available for execution. It is responsible for the following three tasks: 1.Loading 2.Linking 3.Initailisation 1) Loading: 1) Reads.class files and stores corresponding information in the Method Area. 2) For each class, the JVM stores the following details in the method area: 1) Fully qualified class name. 2) Fully qualified parent class name. All Interview inone Page 9 2) For each class, the JVM stores the following details in the method area: 1) Fully qualified class name. 2) Fully qualified parent class name. 3) Methods information. 4) Variables information. 5) Constructors information. 6) Modifiers information. 7) Constant pool information. 3) Java has three types of Class Loaders: 1) Bootstrap Class Loader: Loads core Java classes from rt.jar (present in JDK/JRE). 2) Extension Class Loader: Loads classes from the extension classpath (e.g., ext.jar). 3) Application Class Loader: Loads classes from the application classpath (defined by the user). 2) Linking: This stage involves verifying, preparing, and resolving the loaded classes: 1) Verification: Ensures the.class file is correctly compiled and well-formed. If it fails, JVM throws java.lang.VerifyError. This makes Java secure. 2) Preparation: JVM allocates memory for static variables and assigns default values (not original values). 3) Resolution: Symbolic references in the class are replaced with direct memory references in the method area. 3) Initialization: In this phase, all static variables are assigned their original values, and static blocks are executed from top to bottom. 2. Memory Areas: The JVM's memory areas include the heap (for objects), stack (for method calls and local variables), method area (for class-level data), and native method stacks. These regions manage memory allocation, storage of program data, and execution context. 3. Execution Engine: The execution engine interprets or compiles bytecode into machine code for execution by the CPU. It includes the interpreter for line-by-line execution and the Just-In-Time (JIT) compiler for optimizing frequently executed code paths. JVM (Java Virtual Machine) = Class Loader + Memory Areas + Execution Engine Usage of JVM :- The JVM interprets or compiles the bytecode into native machine code that can be executed by the host machine. This enables Java programs to run on any device or operating system that has a compatible JVM implementation, adhering to the principle of "Write Once, Run Anywhere." Here’s a table outlining the key differences between JDK, JRE, and JVM: Feature JDK (Java Development Kit) JRE (Java Runtime Environment) JVM (Java Virtual Machine) Definition A full package that includes JRE and An environment that contains JVM A virtual machine that executes Java bytecode development tools (compiler, and libraries required to run Java and converts it to machine code. debugger, etc.). applications. Components JRE, JVM, compiler (javac), debugger, JVM and core libraries (but not Core component of JRE, includes class loader, other development tools. development tools). memory management, and execution engine. Purpose Used to develop and run Java Used to run Java applications. Used to execute Java bytecode. applications. Usage Required by developers to write, Required by users to run Java Acts as an interpreter to run the compiled Java compile, and debug Java programs. programs. bytecode. Included Compiler (javac), JavaDoc, Java Only necessary libraries and JVM for No additional tools; just responsible for running Tools Debugger, and other tools. running applications. bytecode. Installation Larger compared to JRE because it Smaller than JDK, as it contains only Not separately installed; part of JRE. Size includes both JRE and development runtime libraries and JVM. tools. Target Developers who want to build Java End-users who want to run Java Not directly interacted with; it's used internally Audience applications. applications. by JRE/JDK. Platform Includes platform-specific libraries for Includes platform-specific libraries for Platform-independent in terms of running Java Dependency compiling and running Java programs. running Java programs. bytecode, but requires a platform-specific implementation. This concise comparison covers the main differences between JDK, JRE, and JVM. Structure of Java Program When writing a program in any programming language, it's important to follow a basic structure recommended by experts. Typically, a Java program is made up of the following parts, as shown in the figure below. This structure if explained below :- 1. Package Declaration Statement (Optional) The package declaration specifies the package name for the Java class. It is the first statement in a Java program (if present). Purpose : Package statement is used to group related classes and organize the code. Syntax : package packageName; All Interview inone Page 10 It is the first statement in a Java program (if present). Purpose : Package statement is used to group related classes and organize the code. Syntax : package packageName; Example : package com.example.myapp; 2. Import Statements (If Necessary) The import statement is used to include other Java classes or packages in the program, enabling the use of pre-defined classes (e.g., java.util.Scanner). Purpose : Import statement is used to import built-in or user-defined classes for reusability. Syntax : import packageName.ClassName; // Imports a specific class import packageName.*; // Imports all classes in the package Example : import java.util.Scanner; // Imports Scanner class import java.util.*; // Imports all classes in java.util package 3. Class Definition Statements The class is the fundamental building block of a Java program. Every Java program must have at least one class. Syntax : class ClassName { // Class body } We can create any number of classes in one program. There should be atleast one main class which should contains the main() method as main() method is the entry point for the program. A class can include the following components which are known as "Class Members": a. Variables : Also called fields or attributes, which hold data. b. Constructors : Used to initialize objects. Example : c. Methods : Define behaviors or actions of the class. public class Car { d. etc... // Class members go here 3.1 Variables Declaration Statements (Optional) [Class Members] } Variables are used to store data and are declared within the class (as fields) or within methods (local variables). Syntax : dataType variableName = value; // Field or local variable declaration Example : String model = "Tata Nexon" // Field int year = 2020; // Field 3.2 Constructors Declaration Statements (Optional) [Class Members] Constructor is a special method having same name as that of class name but should name have any return type. A constructor initializes objects of a class. If no constructor is provided, Java supplies a default constructor. Syntax : ClassName() { // Constructor body ○ Example : } public Car() { System.out.println("Constructor 3.3 Methods Declaration Statements [Class Members] called!"); Methods are the set of codes which performs a particular task. } We can create any number of methods in one class. Example : Syntax : public void start() { accessModifier returnType methodName(parameters) { System.out.println("Car Started"); // Method body } } 3.4 Main Method [Class Members] main() method is the entry point for java program from where program execution starts. main() method can have different syntax but below is the standard syntax that we should use. Syntax : Example : public static void main(String[] args) { public static void main(String[] args) { // Code to execute System.out.println("Hello Deepak...!!"); } } Simple Java Hello Program In last tutorial, we have deeply explained the Structure of Java Hello Program. Now, below is the simple Java Hello Program. MainApp.java public class MainApp { public static void main(String[] args) All Interview inone Page 11 MainApp.java public class MainApp { public static void main(String[] args) { System.out.println("Hello Deepak"); } } In this example, we have a class named MainApp, and within this class, there is a main method. The method prints "Hello Deepak...!!" to the console. Breaking Down the program as below:- 1. public (Keyword - Access Modifier) ○ The "public access modifier keyword" declares that the MainApp class is accessible from anywhere in the program (other packages are also included) and JVM can invoke it from outside the class. ○ Note that when a class is declared as public, it must have the same name as the file name (in this case, MainApp.java). 2. class (Keyword) ○ The "class keyword" is used to define a class in Java, which acts as a blueprint for creating objects. ○ The class can contain :- Variables: Store data or attributes of the class. Constructors: Initialize the object’s state. Methods: Define the behavior or actions of the class. 3. MainApp (User-Defined Class Name) ○ The "MainApp" is the user-defined class name which contains the overall program. ○ The class must follows the Java naming conventions (CamelCase starting with an uppercase letter). ○ The "MainApp" class acts as the entry point of the program because it contains the main method. 4. { (Class Opening Curly Brace) ○ Here "{" denotes the beginning of the class definition. ○ Every class body is enclosed in curly braces. 5. public (Keyword - Access Modifier) ○ The "public access modifier keyword" here makes the main method accessible to the Java Virtual Machine (JVM) so it can execute the program. 6. static (Keyword) ○ The "static keyword" denotes that the main method belongs to the class rather than an instance of the class. ○ It means that the main method is called without creating an object of the MainApp class. 7. void (Keyword - Return Type) ○ The "void return-type keyword" indicates that the main method does not return any value. ○ Since the program’s execution does not require any return value from the main method, it is declared void. 8. main (Pre-Defined Method) ○ The "main pre-defined method" is an entry point of the program from where execution begins. ○ The JVM looks for this specific method (main() method) to start the program. If there is no main() method then JVM will not start the program execution. 9. String[] (Parameter Type - Array of Strings) ○ The "String[] parameter type" is used for Command-line Arguments. It holds the arguments passed to the program when it is executed via the command line. ○ For example: If we run java MainApp Hello Deepak, the array will contain: String = "Hello" String = "Deepak" 10. args (Parameter Name - Argunment Variable) ○ The "args" is the user-defined variable name for the String[] parameter. ○ "args" is the short name for arguments, but can be renamed to any valid identifier (e.g., data or parameters). ○ It is used to hold the command-line arguments passed to the program. 11. { (Method Opening Curly Brace) ○ Here "{" denotes the beginning of the main method body. 12. System (Pre-Defined Class Name) ○ "System" is the built-in Java class from java.lang package. ○ It provides access to system-level functionality, such as input/output streams, properties, and environment variables. ○ It contains: in: Standard input stream (e.g., keyboard input). out: Standard output stream (e.g., console output). err: Standard error stream (e.g., error messages). 13.. (Member Access Operator) ○ "." is the member access operator which is used to access fields, methods and nested classes of a class or an object. ○ For example: System.out accesses the out field of the System class. It contains: All Interview inone Page 12 ○ It contains: in: Standard input stream (e.g., keyboard input). out: Standard output stream (e.g., console output). err: Standard error stream (e.g., error messages). 14. out (Pre-Defined Object) ○ "out" is the static member (field or property) of "System" class that represents the standard output stream (usually the console). ○ It is used to print the data like strings, numbers or objects to the console. 15. println (Pre-Defined Method) ○ "println" is the pre-defined method of "PrintStream" class (referenced by System.out). ○ It prints the given text or data to the console and moves the cursor to a new line. 16. "Hello Deepak" (String Literal) ○ "Hello Deepak" is the sequence of characters enclosed in double quotes. ○ The text Hello Deepak is passed as an argument to the println method and will be displayed in the console. 16. ; [Semicolon] (Statement Terminator) ○ ";" marks the end of a statement in Java. Every executable statement must be terminated with a semicolon. 17. } (Method Closing Curly Brace:) ○ Here "}" marks the end of the main method body. 18. } (Class Closing Curly Brace) ○ Here "}" marks the end of the class definition. How to compile and run Java Program using CMD ? To compile and run a Java program using Notepad, follow these steps: Step 1: Set Up Java (if not already done) ○ Install JDK (if not installed click here for steps) ○ Verify the installation: Open a Command Prompt. Type java -version and javac -version. If both commands display version information, Java is set up correctly. Step 2: Write the Java Program Step 3: Compile the Java Program ○ Open Notepad. ○ Open a Command Prompt. ○ Write Java program code as below : ○ Navigate to the directory where we have saved the.java file. For MainApp.java example: public class MainApp cd /d D:\JavaPrograms { cd means Change Directory. public static void main(String[] args) The /d switch changes the drive while navigating to the directory. { ○ Compile the program using javac: System.out.println("Hello Deepak"); javac MainApp.java } ○ If there is no error in the code then it will generate.class file in the } same location where.java file is present. But if there is an error in ○ Save the file with a.java extension. For example: code then it will display the error. File Name: MainApp.java Step 4: Run the Java Program Location: Save it in a directory, e.g., d:\JavaPrograms ○ Run the compiled program using the java command: java MainApp ○ Output: Hello Deepak Deep Explanation of How Java Works Step by Step Below diagram visually explains the steps involved when writing, compiling, and executing a Java program using Notepad and CMD. Below is detailed explanation: Step 1: Writing the Java Program ○ We write our Java program in a plain text editor like Notepad. ○ The program is saved with a.java extension, e.g., MainApp.java. MainApp.java public class MainApp { public static void main(String[] args) { System.out.println("Hello Deepak"); } } ○ The.java file contains our Java source code, including a class with a main method (the entry point of the program). Step 2: Compilation ○ In compilation phase, we open CMD, navigate to the directory where our.java file is located, and run the javac command: javac MainApp.java What happens in compilation phase: All Interview inone Page 13 ○ What happens in compilation phase: The Java Compiler (javac) reads the.java file. It checks the code for syntax errors. If there are no errors, it compiles the code into bytecode, a platform-independent intermediate representation. The bytecode is saved in a.class file (e.g., MainApp.class). Step 3: Bytecode (.class file) ○ The.class file contains the compiled bytecode, which can be executed on any system with a Java Virtual Machine (JVM). ○ Bytecode ensures Java's "Write Once, Run Anywhere" principle because it is not tied to a specific machine. Step 4: Execution ○ To run the program, we execute the java command in CMD: java MainApp Do not include the.class extension in this command. ○ What happens during execution phase: JVM (Java Virtual Machine): □ The JVM reads the bytecode in the.class file. □ It converts the bytecode into machine code that the operating system understands. □ It executes the machine code line by line. The main method is the entry point for execution. Step 5: Output ○ If the program contains a print statement, such as: System.out.println("Hello Deepak"); ○ The JVM executes it, and the output is displayed in the Command Prompt: Hello Deepak Type of Compiler in Java ? In Java, the compiler is responsible for converting source code into bytecode, which can then be executed by the Java Virtual Machine (JVM). There are two primary types of compilers used in Java: 1. Javac (Java Compiler): ○ Purpose: Compiles Java source code (.java files) into bytecode (.class files). ○ How it works: The javac tool, which is part of the JDK, reads the.java files and compiles them into platform-independent bytecode that can be executed on any machine with a JVM. 2. JIT Compiler (Just-In-Time Compiler): ○ Purpose: Converts bytecode into native machine code at runtime. ○ How it works: JIT compiler is part of the JVM. It takes bytecode and translates it into native code for better performance, as native code is directly executed by the CPU. JIT optimizes the program while it's running. All Interview inone Page 14 Java Generics 1. Generics in Java 2. Generic Constructor with Example 3. Generic Class with Example 4. Generic Interface in Java with Example Miscellaneous Tutorials 1. Java Annotations 2. Command Line Arguments in Java 3. Java Custom Annotation 4. Recursion in Java with Example 5. Garbage Collection in Java with Example 6. What is Factory Method in Java 7. Object Finalization in Java with Example 8. Java Math Class 9. Object Class in Java with Example 10. Object Cloning in Java with Example Basic Java 1. Tokens in Java Tokens are the smallest building blocks of a Java program, and they are fundamental for the compilation process. The Java compiler uses these tokens to understand and process the code. Tokens can be broadly categorized into different types. Types of Tokens in Java Token Type Description Examples 1. Keywords Predefined words with special meanings reserved by class, public, static, int, if, else, for, while, return Java. 2. Identifiers User-defined names for variables, methods, classes, etc. myVariable, calculateSum, Student, main 3. Literals Constant values directly written in the code. - Integer: 123 - Floating-point: 12.34 - Boolean: true, false - String: "Hello" - Char: 'A' 4. Operators Symbols used for operations like arithmetic, comparison, +, -, *, /, %, ==, !=, &&, ` logical, etc. 5. Separators Characters that structure and organize the code. {, }, (, ), [, ], ;, ,,. 6. Comments Non-executable text used to explain the code. - Single-line: // This is a comment - Multi-line: 7. Special Characters with special purposes, often used in program@ (Annotations), $ (Special identifiers), _ (for variable Symbols control or structure. naming in Java 9+) Details on Token Types 4. Operators 1. Keywords Used to perform operations on variables or Reserved words in Java that have predefined functionality. values. Cannot be used as identifiers. Categories: Examples: static, try, catch, void. ○ Arithmetic: +, -, *, /. 2. Identifiers ○ Relational: ==,. Names assigned to program elements (classes, methods, variables). ○ Logical: &&, ||. Rules: ○ Bitwise: &, |. ○ Must start with a letter, $, or _. 5. Separators ○ Cannot start with a digit or use a Java keyword. Used to define code structure and delimit blocks 3. Literals or parameters. Values directly assigned to variables. Examples: Types: ○ { }: Block of code. ○ Integer Literals: 42, 0b101 (binary), 0x2A (hexadecimal). ○ ( ): Function call or control structure. ○ Floating-Point Literals: 3.14, 2.1e5. ○ ;: Statement terminator. ○ Character Literals: 'c', '\n'. 6. Comments ○ String Literals: "Hello, World!". Not executed by the compiler. Improves code readability. Types: Examples of Token Usage in Java Code ○ Single-line: Starts with //. All Interview inone Page 5 ○ String Literals: "Hello, World!". Not executed by the compiler. Improves code readability. Types: Examples of Token Usage in Java Code ○ Single-line: Starts with //. public class Example { // Keywords: public, class ○ Multi-line: Starts with. int number = 100; // Identifier: number, Literal: 100 7. Special Symbols float pi = 3.14f; // Identifier: pi, Literal: 3.14f Serve specific roles in annotations, variable public static void main(String[] args) { // Keywords, Identifiers, Separators names, or advanced Java features. System.out.println("Hello, Java!"); // Literal: "Hello, Java!", @ is used for metadata (annotations like Identifier: System @Override). } $ can be used in identifiers (commonly in } generated code). Understanding tokens is crucial for writing error-free, syntactically correct Java programs. They form the basis for further concepts like expressions, statements, and control structures. 2. Identifiers in Java Identifiers in Java are the names used for variables, methods, classes, packages, and other elements in a program. They are user- defined and must follow certain rules to be valid. Rules for Identifiers 1. Allowed Characters: ○ Must begin with a letter (A-Z or a-z), underscore (_), or dollar sign ($). ○ Can include digits (0-9), letters, underscore (_), and dollar sign ($) after the first character. 2. No Reserved Keywords:- Cannot be the same as Java reserved keywords (e.g., int, class, if). 3. Case Sensitivity:- Identifiers are case-sensitive (myVariable and MyVariable are different). 4. No Special Characters:- Only _ and $ are allowed; others like @, #, -, &, etc., are invalid. 5. Unlimited Length:- Identifiers can have any length but should be meaningful for readability. 6. No Spaces:- Identifiers cannot contain spaces (e.g., my variable is invalid). Valid Examples of Identifiers Identifier Reason Invalid Examples of Identifiers variable1 Starts with a letter and contains alphanumeric Identifier Reason characters. 123variable Starts with a digit. _temp Starts with an underscore. int Uses a reserved keyword. $value Starts with a dollar sign. my-variable Contains a special character (-). employeeName CamelCase notation, recommended for variable voidFunction Includes void, which is a reserved keyword. names. my variable Contains a space, which is not allowed. compute_Sum Includes an underscore, which is valid. Best Practices for Naming Identifiers 1. Use Meaningful Names:- Choose descriptive names to make the code self-documenting (e.g., studentAge instead of x). 2. Follow Naming Conventions: ○ Variables and Methods: Use camelCase (e.g., calculateSum). ○ Classes: Use PascalCase (e.g., StudentRecord). ○ Constants: Use UPPERCASE with underscores (e.g., MAX_VALUE). 3. Avoid Using $ and _ Excessively:- These are valid but should be used sparingly unless necessary. Example Usage in Java Code public class IdentifiersExample { int age = 25; // Valid identifier for a variable Q3: What are the common mistakes to avoid with identifiers? static final int MAX = 100; // Valid identifier for a constant A: Common mistakes include using ambiguous names, choosing non- public void calculateSum() { // Valid identifier for a method descriptive identifiers, and using single-letter names excessively. int totalSum = 0; // Valid identifier for a local variable Q4: How do Java keywords differ from identifiers? System.out.println(totalSum); A: In Java, keywords are reserved words with predefined meanings } and we cannot use them as identifiers in a Java program. } By following the rules and best practices, you can create identifiers that make your Java code clean, readable, and maintainable. FAQs on Identifiers: Q1: What is an identifier in Java programming? A: An identifier refers to a name used to identify various elements in a Java program, such as variables, methods, classes, interfaces, and packages. Q2: Why are meaningful identifiers important in Java? A: Meaningful identifiers enhance code understanding as well as make it easier to identify the purpose of variables, methods, or All Interview inone Page 6 A: Meaningful identifiers enhance code understanding as well as make it easier to identify the purpose of variables, methods, or classes. 3. Java Character Set Java Character Set | Characters are the smallest units (elements) of Java language that are used to write Java tokens. These characters are defined by the Unicode character set. A character set in Java is a set of alphabets, letters, and some special characters that are valid in java programming language. The first character set used in the computer system was US-ASCII (American Standard Code for Information Interchange (ASCII pronounced as ass-kee)). It is limited to represent only American English. US-ASCII consists of uppercase and lowercase Latin alphabets, numerals, punctuation, a set of control codes, and a few miscellaneous symbols. Unicode defines a standardized 16-bit character coding system. It currently supports more than 34,000 defined characters derived from 24 languages from America, Europe, Middle East, Africa, and Asia (including India). However, we use mostly basic ASCII characters to develop a program that includes letters, digits, and punctuation marks used in normal English. Java language uses the character sets as the building block to form the basic elements such as identifiers, variables, array, etc in the program. These are as follows: Letters: Both lowercase (a, b, c, d, e, etc.) and uppercase (A, B, C, D, E, etc.) letters. Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Special symbols: _, (, ), {, }, [, ], +, -, *, /, %, !, &, |, ~, ^, , $, #, ?, Comma (,), Dot (.), Colon (:), Semi-colon (;), Single quote (‘), Double quote (“), Back slash (\). White space: Space, Tab, New line. Unicode represents a standardized and universal character set that can be extended to accommodate additions. When the program source code file encoding does not support Unicode in Java, we can define Unicode characters as escape sequences by using the notation \uXXXX, where XXXX specifies the character’s 16-bit representation in hexadecimal. Hope that this tutorial has covered all the basic points related to character set in Java with example. I hope that you will have understood this simple and basic topic. In the next tutorial, we will learn a set of keywords in Java. Thanks for reading!!! 4. Comparison of Comment Types Type Syntax Purpose Single-Line Comments // Quick notes or explanations for specific lines. Multi-Line Comments Detailed explanations or code block comments. Documentation Comments Generate Java documentation with javadoc. Best Practices for Comments 1. Keep Comments Relevant: ○ Ensure comments add value and explain the "why" rather than the "what" (which should be evident from code). 2. Use Documentation Comments for Public APIs: ○ Provide detailed documentation for classes and methods accessible to other developers. 3. Avoid Overusing Comments: ○ Code should be self-explanatory; excessive comments may indicate unclear coding practices. 4. Update Comments with Code Changes: ○ Ensure comments remain accurate and in sync with the code. 5. Escape Sequences in Java Escape sequences in Java are used to represent special characters that cannot be typed directly into the code. They are defined with a backslash (\) followed by a specific character. Common Escape Sequences in Java Significance of Escape Sequences Escape Sequence Description Example Output 1. Enhances Readability:- \n Inserts a newline "Hello\nWorld" Hello Allows inclusion of special World characters in strings without \t Inserts a tab "Hello\tWorld" Hello World confusion. \b Inserts a backspace "Hello\bWorld" HellWorld 2. Facilitates Special Formatting:- Useful for \r Inserts a carriage return "Hello\rWorld" World (overwrites text) aligning text and formatting \' Inserts a single quote "\'Java\'" 'Java' output. \" Inserts a double quote "\"Java\"" "Java" 3. Supports Unicode Characters:- Enables \\ Inserts a backslash "C:\\Users\\Rishi" C:\Users\Rishi All Interview inone Page 7 aligning text and formatting \' Inserts a single quote "\'Java\'" 'Java' output. \" Inserts a double quote "\"Java\"" "Java" 3. Supports Unicode Characters:- Enables \\ Inserts a backslash "C:\\Users\\Rishi" C:\Users\Rishi representation of global \f Inserts a form feed "Hello\fWorld" Moves to next page scripts and symbols. \uXXXX Inserts a Unicode character "\u0905" अ Examples of Escape Sequences Notes public class EscapeSequenceExample { Escape sequences are public static void main(String[] args) { interpreted within string System.out.println("Hello\nWorld"); // Newline literals and character Output System.out.println("Tab\tSpace"); // Tab literals. Hello System.out.println("Backspace\bTest"); // Backspace If an escape sequence is used World System.out.println("Carriage\rReturn"); // Carriage return incorrectly (e.g., \x), Java will Tab Space System.out.println("\"Quote\""); // Double quotes throw a compilation error. BackspacTest System.out.println("\\Backslash\\"); // Backslash Return System.out.println("Unicode character: \u0905"); // Unicode "Quote" } \Backslash\ } Unicode character: अ 6. What are the keywords of Java? Keywords are the reserved words in Java having certain meanings. These words are not allowed to use as variable names or object names. 2. How many keywords are in Java? There are 67 Keywords in Java. Here is the table of Java keywords, including their explanations and the new keywords highlighted in bold: Keyword Explanation abstract Specifies a class or method that will be implemented later, in a subclass. assert Tests a condition in the program for debugging; throws an error if false. boolean A data type for variables holding true or false. break Exits a loop or a switch block prematurely. byte A data type that stores 8-bit integer values. case Defines a branch in a switch statement. catch Handles exceptions thrown in a try block. char A data type for storing 16-bit Unicode characters. class Declares a new class. const Reserved but not used; use final instead. continue Skips the current iteration of a loop and moves to the next. default Specifies the default block in a switch statement. do Starts a do-while loop, which runs at least once. double A data type for 64-bit floating-point numbers. else Defines a branch in an if statement if the condition is false. enum Declares an enumerated type with predefined constant values. extends Specifies that a class is derived from a superclass. final Declares constants, prevents inheritance, or prohibits method overriding. finally Defines a block that executes after a try-catch block, regardless of outcome. float A data type for 32-bit floating-point numbers. for Starts a loop with an initialization, condition, and increment/decrement. goto Reserved but not used in Java for code clarity and structure. if Tests a condition and executes a block of code if true. implements Indicates that a class implements an interface. import Allows the inclusion of other Java classes or packages. All Interview inone Page 8 import Allows the inclusion of other Java classes or packages. instanceof Tests whether an object is an instance of a specific class or subclass. int A data type for storing 32-bit integer values. interface Declares an interface, which is a cont