0% found this document useful (0 votes)
5 views42 pages

Java Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 42

Contents

INTRODUCTION TO JAVA 3

The History & Overview of Java 3

Key Milestones in Java's History 3

Java Version History 4

Features of Java 6

Applications of java 8

Comparision between c ++ & java 10

Download and Install JDK: 11

Java Development kit 12

JVM | Java Virtual Machine 14

JRE 20

Difference between Byte Code and Machine Code 20

JDK JRE JVM 21

TYPED LANGUAGES 22

JAVA TOKENS, DATA TYPES, VARIABLES 28

Comments in Java 28

Keywords 29

Identifiers in Java 31

Naming Conventions of the Different Identifiers 32

Java literals 33

Operators 35

Separators in Java: 36

Java Programming Structure 37

Data Types 37

Java Variables 41
INTRODUCTION TO JAVA
The History & Overview of Java

The history of Java is indeed fascinating and highlights the evolution of a language that has become
integral to modern computing.
Java was initially conceived for interactive television but quickly found its niche as a robust, versatile
programming language suitable for internet applications. The journey of Java began with a small team at
Sun Microsystems, known as the Green Team, which aimed to develop a language for digital devices like
set-top boxes and televisions. However, as the project evolved, it became clear that the language had
broader potential, particularly for the burgeoning internet.

Key Milestones in Java's History

1. Early Development (1991-1995)


- June 1991: James Gosling, Mike Sheridan, and Patrick Naughton, engineers at Sun Microsystems,
initiated the Java project, initially called the Green Project.
- Initial Name: The language was first called "Greentalk," with the file extension `.gt`. It was later
renamed "Oak" after an oak tree that stood outside Gosling's office.
- Purpose: Oak was designed for embedded systems, particularly for use in electronic appliances like
set-top boxes.

2. Transition from Oak to Java (1995)


- Renaming: In 1995, Oak was renamed "Java" because "Oak" was already a registered trademark by
Oak Technologies.
- Naming Inspiration: The name "Java" was chosen because it was unique, dynamic, and easy to spell. It
was inspired by Java coffee, a type of espresso bean, and the island of Java in Indonesia where the first
coffee was produced.

3. Java's Launch and Rise to Prominence (1995-1996)


- 1995 Release: Java was officially launched by Sun Microsystems. The language was particularly noted
for its portability, allowing developers to "write once, run anywhere," which was a major selling point in
the era of diverse computing environments.
- Integration with Netscape: Java technology was quickly adopted by Netscape, one of the leading web
browsers of the time, which helped boost its popularity.
- Accolades: Time magazine recognized Java as one of the Ten Best Products of 1995, highlighting its
revolutionary impact.

4. Java Development Kit (JDK) 1.0


- Release: JDK 1.0 was released on January 23, 1996, marking the first official version of Java.
- Features: This initial release included the foundational features of Java, such as the Java Virtual
Machine (JVM), which allowed Java programs to run on any platform, and the core libraries.

Certainly! Below is the revised version of the Java version history, streamlined for clarity and ease of
reading, with repetitive information removed and headings appropriately set:
Java Version History
Early Development and Initial Releases

1. JDK Alpha and Beta (1995)


- These were the first releases of Java but had highly unstable APIs and ABIs.
- The supplied Java web browser was named WebRunner .

2. JDK 1.0 (January 23, 1996)


- Codename: Oak .
- This was the first stable version of Java, marking the official launch of the language.
- Introduced foundational features, but some capabilities, like private and protected keywords used
together, were removed in the subsequent update (JDK 1.0.2).

Evolution of Java Versions

3. JDK 1.1 (February 19, 1997)


- Introduced significant features including:
- Inner Classes
- JavaBeans
- JDBC (Java Database Connectivity)
- RMI (Remote Method Invocation)
- Reflection (supporting introspection only).
- The AWT event model was reshaped, and the Just-In-Time (JIT) compiler was introduced for
Windows platforms.

4. J2SE 1.2 (December 8, 1998)


- Codename: Playground .
- Marked a major release, tripling the size of the Java platform.
- Key additions:
- Swing GUI was integrated.
- Collections Framework introduced.
- Java Plug-in and Java IDL (for CORBA interoperability).
- Sun's JVM was equipped with a JIT compiler for the first time.

5. J2SE 1.3 (May 8, 2000)


- Codename: Kestrel .
- Key additions:
- HotSpot JVM .
- JNDI (Java Naming and Directory Interface).
- JavaSound and Java Platform Debugger Architecture (JPDA) .

6. J2SE 1.4 (February 6, 2002)


- Codename: Merlin .
- First release under the Java Community Process.
- Key additions:
- Perl-style Regular Expressions .
- IPv6 support and Logging API .
- Integrated XML Parser and XSLT Processor .
- Security extensions (JCE, JSSE, JAAS) integrated.

7. J2SE 5.0 (September 30, 2004)


- Codename: Tiger .
- Introduced major language features:
- Generics .
- Metadata (Annotations) .
- Autoboxing/Unboxing .
- Enumerations and Enhanced for loop .
- Library improvements included:
- Concurrency Utilities in `java.util.concurrent`.
- Scanner Class for parsing input.

8. Java SE 6 (December 11, 2006)


- Codename: Mustang .
- Transition from J2SE to Java SE .
- Key additions:
- Scripting Language Support and JDBC 4.0 .
- Java Compiler API for programmatic compilation.
- Dropped support for older Windows 9x versions.

9. Java SE 7 (July 28, 2011)


- Codename: Dolphin .
- Key additions:
- Strings in Switch Statements .
- Automatic Resource Management in try-statements.
- Binary Literals and Underscores in Numeric Literals .
- Improved support for dynamic languages .

10. Java SE 8 (March 18, 2014)


- Codename: Spider .
- Introduced features initially planned for Java SE 7:
- Lambda Expressions and Stream API .
- Date and Time API .
- Removal of Permanent Generation in the JVM.
- JavaFX applications could now be launched natively.

11. Java SE 9 (September 21, 2017)


- Major features:
- Modularization of the JDK (Project Jigsaw).
- Integration of Reactive Streams and Concurrency Updates .
- Introduction of Java Linker .

12. Java SE 10 (March 20, 2018)


- Introduced features like:
- Local-Variable Type Inference .
- Application Class-Data Sharing .
- Experimental Java-Based JIT Compiler (Graal).
- Parallel Full GC for G1 and Garbage-Collector Interface .

13. Java SE 11 (September 2018) to Java SE 21 (2023)


- Continued to evolve with regular updates, adding features for better performance, improved language
syntax, and enhanced JVM capabilities.
Features of Java
Java was designed with the goal of making a programming language that is portable, simple, and secure.
These foundational objectives, coupled with additional features, have made Java one of the most popular
and enduring programming languages in the world. These features, often referred to as Java buzzwords,
are crucial in understanding why Java remains relevant.

Java Features

- Simple
- Object-Oriented
- Portable
- Platform Independent
- Secured
- Robust
- Architecture Neutral
- Interpreted
- High Performance
- Multithreaded
- Distributed
- Dynamic

Simple

Java is straightforward to learn and its syntax is clear, making it easier for developers, especially those
familiar with C++, to adopt. The removal of complex features like explicit pointers and operator overloading
further simplifies the language. Automatic garbage collection also alleviates the developer's burden of
manual memory management.

Object-Oriented

Java is a fully object-oriented language, which means it models everything as an object, encapsulating data
and behavior. Object-Oriented Programming (OOP) simplifies software development by promoting code
reuse and modularity.

Key OOP Concepts:

- Object: An instance of a class.


- Class: A blueprint for creating objects.
- Inheritance: Mechanism where one class inherits properties and behavior from another.
- Polymorphism: Ability to process objects differently based on their data type or class.
- Abstraction: Hiding the complex implementation details and showing only the essential features.
- Encapsulation: Bundling data and methods that operate on the data within one unit, like a class.

Platform Independent

Java achieves platform independence through the use of bytecode. Java code is compiled into bytecode by
the Java compiler, which can then be executed on any device that has the Java Virtual Machine (JVM)
installed. This is summed up by the phrase "Write Once, Run Anywhere" (WORA).

Example: A Java program compiled on a Windows machine can run on a Linux or Mac machine without
modification, as long as the JVM is present on those machines.

Secured

Java is designed with security features that help develop secure applications. The absence of pointers
reduces the risk of unauthorized memory access, and Java applications run in a sandbox environment,
which limits the program’s ability to access system resources.

Security Mechanisms:
- Classloader: Differentiates between classes loaded from the local file system and those loaded from
the network.
- Bytecode Verifier: Ensures that the code follows Java's security rules before execution.
- Security Manager: Defines the access control policies for applications.

Example: The Java security manager can be used to restrict file read/write permissions for a particular
application, preventing it from performing unauthorized actions.

Robust

Java's robustness stems from its strong memory management, exception handling mechanisms, and lack
of pointers, which avoids many vulnerabilities common in other languages.

Example: Java’s automatic garbage collection removes objects that are no longer referenced, reducing
the chances of memory leaks.

Architecture Neutral

Java's architecture neutrality is ensured by the fact that its primitive data types have consistent sizes across
all platforms, which is not the case in languages like C or C++.

Example: In Java, an `int` always occupies 4 bytes, regardless of the underlying platform.

Portable
Java’s portability is a direct result of its platform independence. The compiled bytecode can be executed on
any system with a compatible JVM.

Example : Developers can compile their Java programs on one platform and distribute the bytecode,
which can then run on any other platform without modification.

High Performance

Although Java is an interpreted language, its performance is enhanced by Just-In-Time (JIT) compilers and
various optimizations in the JVM, making it faster than many other interpreted languages.

Example: The JVM optimizes bytecode execution by compiling frequently executed code paths to native
machine code, boosting performance.

Multithreaded

Java’s multithreading capability allows developers to build applications that can perform multiple tasks
concurrently, improving performance and responsiveness, especially in graphical applications.

Distributed

Java simplifies the development of distributed applications, allowing methods to be invoked over a network
as easily as on a local machine. Technologies like RMI (Remote Method Invocation) and EJB (Enterprise
JavaBeans) make it easier to build distributed systems.

Example: Using RMI, a Java program can call methods on an object located on a different machine as if it
were local.

Dynamic
Java is dynamic because it supports dynamic loading of classes and libraries. This allows developers to
load classes at runtime and even modify the application behavior on the fly.

Example:

Java's reflection API allows for the inspection and modification of a program's behavior at runtime, which
can be particularly useful in frameworks and tools.

Applications of java
As of 2024, Java continues to be a highly versatile and widely used programming language across various
industries. Its applications have evolved to keep pace with modern technology trends, making it relevant in
several key areas:

1. Enterprise Applications
- Description : Java remains the backbone of many large-scale enterprise systems, particularly in
banking, finance, and e-commerce. Its robustness, scalability, and extensive ecosystem make it ideal for
building complex, high-availability applications.
- Examples :
- Enterprise Resource Planning (ERP) systems
- Customer Relationship Management (CRM) software
- Financial transaction processing systems

2. Web Development
- Description : Java continues to play a significant role in web development, especially for server-side
applications. The Spring Framework, Java Server Faces (JSF), and Java EE (Jakarta EE) are commonly
used in developing scalable and secure web applications.
- Examples :
- E-commerce platforms
- Online banking portals
- Content management systems (CMS)

3. Android Development
- Description : Java has been the traditional language for Android app development, and it remains
relevant even as Kotlin gains popularity. Many legacy Android apps are still maintained and developed in
Java.
- Examples :
- Mobile banking apps
- Social networking apps
- Utility and productivity apps

4. Cloud Computing
- Description : With the rise of cloud computing, Java has found new applications in building cloud-
native applications. Java’s platform independence, combined with frameworks like Spring Boot and Micro
Profile, makes it suitable for developing microservices and cloud-based applications.
- Examples:
- Microservices architecture in cloud platforms
- Cloud-based enterprise applications
- Serverless computing applications

5. Big Data and Analytics


- Description : Java is often used in big data technologies due to its performance and scalability.
Apache Hadoop and Apache Kafka, which are written in Java, are widely used in data processing and real-
time data streaming applications.
- Examples :
- Distributed data processing pipelines
- Real-time analytics platforms
- Machine learning model training and deployment

6. Internet of Things (IoT)


- Description : Java is increasingly used in IoT applications due to its platform independence and ability
to run on small, resource-constrained devices. The Java ME (Micro Edition) and Java SE Embedded are
specifically designed for IoT development.
- Examples :
- Smart home automation systems
- Industrial IoT applications
- Connected devices and sensors

7. Artificial Intelligence (AI) and Machine Learning (ML)


- Description : While Python is often the go-to language for AI and ML, Java is also used, especially in
enterprise environments where existing Java infrastructure can be leveraged. Java libraries like
Deeplearning4j and Weka are used for machine learning tasks.
- Examples :
- Predictive analytics tools
- Natural language processing (NLP) applications
- Recommendation engines

8. Blockchain Development
- Description : Java is used in blockchain development, particularly in building secure and scalable
blockchain applications. Its strong security features and mature ecosystem make it suitable for developing
blockchain solutions.
- Examples :
- Smart contracts
- Cryptocurrency exchanges
- Decentralized applications (DApps)

9. Game Development
- Description : While not as common as some other languages, Java is still used in game development,
particularly for Android games and simple 2D games. The Java-based LibGDX framework is popular for
this purpose.
- Examples :
- Mobile games for Android
- Browser-based games
- Educational games

10. DevOps and Automation


- Description : Java is also applied in DevOps for automation tasks and building CI/CD pipelines. Tools
like Jenkins, which is written in Java, are widely used in DevOps environments.
- Examples :
- Continuous integration/continuous deployment (CI/CD) pipelines
- Infrastructure automation scripts
- Monitoring and logging tools

Conclusion
In 2024, Java remains a dominant force in the software development landscape, with applications spanning
from traditional enterprise systems to emerging technologies like IoT, AI, and blockchain. Its versatility,
extensive ecosystem, and continued evolution ensure its relevance in a wide range of industries and use
cases.

Comparision between c ++ & java


C++ vs Java
3There are many differences and similarities between the C++ programming language
and Java. A list of top differences between C++ and Java are given below:
Comparison Index C++ Java
Platform-
C++ is platform-dependent. Java is platform-independent.
independent
Java is mainly used for application
C++ is mainly used for system programming. It is widely used in Windows-
Mainly used for
programming. based, web-based, enterprise, and mobile
applications.
Java was designed and created as an
C++ was designed for systems and
interpreter for printing systems but later
applications programming. It was
Design Goal extended as a support network computing. It
an extension of the C programming
was designed to be easy to use and accessible
language.
to a broader audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Java doesn't support multiple inheritance
Multiple
C++ supports multiple inheritance. through class. It can be achieved by
inheritance
using interfaces in java.
Operator
C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Java supports pointer internally. However,
C++ supports pointers. You can you can't write the pointer program in java. It
Pointers
write a pointer program in C++. means java has restricted pointer support in
java.
Java uses both compiler and interpreter. Java
C++ uses compiler only. C++ is
source code is converted into bytecode at
compiled and run using the
Compiler and compilation time. The interpreter executes
compiler which converts source
Interpreter this bytecode at runtime and produces
code into machine code so, C++ is
output. Java is interpreted that is why it is
platform dependent.
platform-independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is no
Call by reference call by reference. call by reference in java.
Structure and C++ supports structures and
Java doesn't support structures and unions.
Union unions.
C++ doesn't have built-in support
Thread Support for threads. It relies on third-party Java has built-in thread support.
libraries for thread support.
Java supports documentation comment (/ ...
Documentation C++ doesn't support
/) to create documentation for java source
comment documentation comments.
code.
Java has no virtual keyword. We can override
C++ supports virtual keyword so
all non-static methods by default. In other
Virtual Keyword that we can decide whether or not
words, non-static methods are virtual by
to override a function.
default.
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>>
shift >>> operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
Java always uses a single inheritance tree
C++ always creates a new because all classes are the child of the Object
Inheritance Tree
inheritance tree. class in Java. The Object class is the root of
the inheritance tree in java.
Hardware C++ is nearer to hardware. Java is not so interactive with hardware.
Java is also an object-oriented language.
C++ is an object-oriented language.
However, everything (except fundamental
However, in the C language, a
Object-oriented types) is an object in Java. It is a single root
single root hierarchy is not
hierarchy as everything gets derived from
possible.
java.lang.Object.

Download and Install JDK:


Setting up a Java development environment involves installing the Java Development Kit (JDK) and
configuring environment variables. Here’s a step-by-step guide for setting up Java on different operating
systems:

1. Download and Install the JDK


The JDK includes the Java Runtime Environment (JRE), compiler (`javac`), and other tools needed to
develop Java applications.

For Windows:

1. Download JDK:
- Visit the official Oracle JDK download page: [Oracle JDK
Downloads](https://www.oracle.com/java/technologies/javase-downloads.html) or use OpenJDK from Adopt
OpenJDK (https://adoptopenjdk.net/).
- Choose the appropriate version and download the installer for Windows.

2. Install JDK:
- Run the downloaded installer.
- Follow the installation prompts. You can choose the default installation directory, typically `C:\Program
Files\Java\jdk-x.x.x_xx`.

3. Set up Environment Variables:


- Right-click "This PC" or "My Computer" and select "Properties."
- Click "Advanced system settings" on the left, then click the "Environment Variables" button.
- Under "System variables," click "New" to create a new variable named `JAVA_HOME`.
- Set `JAVA_HOME` to the path where you installed the JDK, e.g., `C:\Program Files\Java\jdk-x.x.x_xx`.
- Find the `Path` variable in "System variables," select it, and click "Edit."
- Add a new entry: `%JAVA_HOME%\bin`.
- Click "OK" to save your changes.

4. Verify the Installation:


- Open a new Command Prompt and type:
```bash
java -version
```
- You should see the installed version of Java.

(or)
How to Set Path in Java
1. How to set the path of JDK in Windows OS
1. Setting Temporary Path of JDK
2. Setting Permanent Path of JDK
The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set
because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.
There are two ways to set the path in Java:
1. Temporary
2. Permanent
1) How to set the Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow the following steps:
 Open the command prompt
 Copy the path of the JDK/bin directory
 Write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
 Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable
-> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Java Development kit

JDK (Java Development Kit):

 Includes JRE along with development tools like compiler, debugger, etc.

 Used for developing Java applications and applets.Contains a private JVM for execution during
development

The Java Development Kit (JDK) is a cross-platformed software development environment that offers a
collection of tools and libraries necessary for developing Java-based software applications and applets. It is
a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment).

Beginners often get confused with JRE and JDK, if you are only interested in running Java programs on your
machine then you can easily do it using Java Runtime Environment. However, if you would like to develop a
Java-based software application then along with JRE you may need some additional necessary tools, which
is called JDK.

The Java Development Kit is an implementation of one of the Java Platform:


 Standard Edition (Java SE),
 Java Enterprise Edition (Java EE),
 Micro Edition (Java ME),
Contents of JDK
The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development
of a Java Application.
JDK contains:
 Java Runtime Environment (JRE),
 An interpreter/loader (Java),
 A compiler (javac),
 An archiver (jar) and many more.
The Java Runtime Environment in JDK is usually called Private Runtime because it is separated from the
regular JRE and has extra content. The Private Runtime in JDK contains a JVM and all the class libraries
present in the production environment, as well as additional libraries useful to developers, e.g,
internationalization libraries and the IDL libraries.
Most Popular JDKs:
 Oracle JDK: the most popular JDK and the main distributor of Java11,
 OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,
 Azul Systems Zing: efficient and low latency JDK for Linux os,
 Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,
 IBM J9 JDK: for AIX, Linux, Windows, and many other OS,
 Amazon Corretto: the newest option with the no-cost build of OpenJDK and long-term support.
Compile and Run Java Code using JDK:
You can use the JDK compiler to convert your Java text file into an executable program. Your Java text
segment is converted into bytecode after compilation which carries the .class extension.
First, create a Java text file and save it using a name. Here we are saving the file as Hello.java.
Java
class Hello{
public static void main (String[] args) {
System.out.println("Hello Geek!");
}
}

After that just simply use the javac command, which is used for the compilation purpose in Java. Please
don’t forget to provide the full path of your java text file to the command line else you will get an error as
“The system cannot find the path specified”,
Your command should be similar to the given below example where Hello is the file name and the full path
to the file is specified before the file name. The path and javac.exe should be inside the quotes.
“C:\Program Files\Java\jdk-11.0.9\bin\javac.exe” Hello.java
You can notice now that the Hello.class file is being created in the same directory as Hello.java. Now you
can run your code by simply using the java Hello command, which will give you the desired result
according to your code. Please remember that you don’t have to include the .class to run your code.
C:\Users\Pinaki\Documents>java Hello
(Output:) Hello Geek!

The Jar component:


JDK contains many useful tools and among them, the most popular after javac is the jar tool. The jar file is
nothing but a full pack of Java classes. After creating the .class files, you can put them together in a .jar,
which compresses and structures them in a predictable fashion. Now, let’s convert our Hello.class to a jar
file.
Before proceeding, please note that you should be in the same directory where the Hello.java file was
saved. Now type the command given below in the command line.
Creating a .jar file
C:\Users\Pinaki\Documents>”c:\Program Files\Java\jdk-11.0.9\bin\jar.exe” –create –file Hello.jar
Hello.class
Now you can notice that Hello.jar file had been created in the same directory using Hello.class file and
jar.exe. You can use the jar file by adding it to your classpath and executing the program inside it. Here the
-cp stands for classpath which helps to add the jar to the same classpath.
Executing the .jar file
java -cp hello_world.jar hello_world

JVM | Java Virtual Machine


JVM (Java Virtual Machine) Architecture
1. Java Virtual Machine
2. Internal Architecture of JVM

JVM (Java Virtual Machine):

An abstract, virtual machine that executes Java bytecode. Platform-independent runtime environment.
Performs tasks like code loading, verification, execution, and provides runtime support. JVMs are available
for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine
etc.
Class Loader Subsystem
It is mainly responsible for three activities.
 Loading
 Linking
 Initialization

Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the
method area. For each “.class” file, JVM stores the following information in the method area.

 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.

After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory.
Please note that this object is of type Class predefined in java.lang package. These Class object can be used
by the programmer for getting class level information like the name of the class, parent name, methods
and variable information etc. To get this object reference we can use getClass() method of Object class.

Linking: Performs verification, preparation, and (optionally) resolution.

 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly
formatted and generated by a valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once this
activity is completed then the class file is ready for compilation.
 Preparation: JVM allocates memory for class static variables and initializing the memory to default
values.
 Resolution: It is the process of replacing symbolic references from the type with direct references.
It is done by searching into the method area to locate the referenced entity.

Initialization: In this phase, all static variables are assigned with their values defined in the code and static
block(if any). This is executed from top to bottom in a class and from parent to child in the class hierarchy.
In general, there are three class loaders:

Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the classloader. There are three built-in classloaders in Java.

Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading
trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib” directory. This path is
popularly known as the bootstrap path. It is implemented in native languages like C, C++. This is the first
classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class
files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package
classes, java.io package classes, java.sql package classes etc.

Extension class loader: It is a child of the bootstrap class loader. parent classloader of System classloader It
loads the classes the jar files located present in the extensions directories
“JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs system
property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class.. It
inside $JAVA_HOME/jre/lib/ext directory.
System/Application class loader: It is a child of the extension class loader. It is responsible to load classes
from the application classpath. It internally uses Environment Variable which mapped to java.class.path. It
is also implemented in Java by the sun.misc.Launcher$AppClassLoader class. \, It loads the classfiles from
classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-
classpath" switch. It is also known as Application classloader
Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load
request to extension class loader and extension class loader delegate request to the bootstrap class
loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to
the extension class loader and then to the system class loader. At last, if the system class loader fails to
load class, then we get run-time exception java.lang.ClassNotFoundException.

JVM Memory
1. Method area: In the method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There is
only one method area per JVM, and it is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per
JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of
this stack is called activation record/stack frame which stores methods calls. All local variables of
that method are stored in their corresponding frame. After a thread terminates, its run-time stack
will be destroyed by JVM. It is not a shared resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has
separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native method
information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and
information present in various memory area and executes instructions. It can be classified into three parts:
 Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that
when one method is called multiple times, every time interpretation is required.
 Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the
entire bytecode and changes it to native code so whenever the interpreter sees repeated method
calls, JIT provides direct native code for that part so re-interpretation is not required, thus efficiency
is improved.
 Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.
 Java Native Interface (JNI) :
 It is an interface that interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++
libraries which may be specific to hardware.
 Native Method Libraries :
 It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

Introduction to Java and JIT Compilation


 Java’s Design as an Interpreted Language
 Originally, Java was designed to be an interpreted language, where the Java Virtual Machine (JVM)
interprets bytecode line-by-line.
 This interpretation allows for Java’s portability—its ability to run on any device that has a JVM.
Performance Improvements and the Need for JIT:
 While interpretation allows for portability, it can be slow, especially for performance-critical
applications.
 To enhance performance, Java’s design does not preclude the compilation of bytecode into native
machine code at runtime, leading to the development of Just-In-Time (JIT) compilation.
HotSpot JVM and JIT Compiler
 - Introduction of the HotSpot JVM:
 - The HotSpot JVM was released shortly after Java’s initial launch to address performance issues.
 - This JVM includes a JIT compiler, which dynamically compiles bytecode into native code as the
program runs.

Functionality of the JIT Compiler:


 Selective Compilation: Not all bytecode is compiled into native code. The JIT compiler selectively
compiles only those portions of the bytecode that will benefit the most from the conversion to
native code.
 On-Demand Compilation: Compilation happens in real-time, as needed during the execution of
the program.
 Caching Compiled Code: Once a segment of code is compiled, it can be cached and reused,
reducing the need for repeated compilation.
JIT Compiler’s Interaction with the JVM
 - Interpreting vs. Compiling:
 - In standard JVM operation, interpreting bytecode can slow down execution.
 - The JIT compiler interacts with the JVM during runtime, identifying and compiling critical sections
of bytecode into machine code, thereby improving performance.
Role of Hardware:
 - Once bytecode is compiled into machine code, it’s the hardware, rather than the JVM, that
executes the code.
 - This shift from interpretation to native execution leads to significant performance gains.
JIT Compilation Strategies
 - Per-File, Per-Function, or Arbitrary Code Fragment:
 - JIT compilation can occur at different granular levels, such as individual files, specific functions, or
even arbitrary fragments of code.
 - This flexibility allows the JIT compiler to optimize performance based on the specific needs of the
program.
Optimization Techniques:
 Data Analysis: The JIT compiler analyzes the code to identify optimization opportunities.
 Stack to Register Translation: The JIT compiler translates stack-based operations into register-
based operations, which are faster for the CPU to execute.
 Memory Access Reduction: By optimizing register allocation, the JIT compiler reduces the need for
frequent memory access, speeding up execution.
 Elimination of Common Sub-Expressions: The JIT compiler eliminates redundant calculations or
operations, streamlining code execution.
Portability and Security
 - Maintaining Java’s Core Features:
 - Despite the use of JIT compilation, Java’s core features of portability and security remain intact.
 - The JVM continues to control the execution environment, ensuring that dynamically compiled
code adheres to Java’s security model.
Summary of Benefits
 Performance Gains: The JIT compiler significantly enhances the execution speed of Java programs
by converting performance-critical bytecode into machine code at runtime.
 Optimizations: The JIT compiler applies various optimizations, such as data analysis and register
allocation, to further boost efficiency.
 Portability and Security: Even with dynamic compilation, Java retains its portability and security,
as the JVM oversees the execution environment.
 This comprehensive overview illustrates the sophisticated workings of the JIT compiler and its
crucial role in optimizing Java program execution while preserving the language's inherent
advantages.

JVM Vs JIT

JVM JIT

JVM stands for Java Virtual Machine. JIT stands for Just-in-time compilation.

JVM was introduced for managing system memory and JIT was invented to improve the
providing a transportable execution environment for Java- performance of JVM after many years of
based applications its initial release.

JVM consists of many other components like stack area,


JIT is one of the components of JVM.
heap area, etc.

JIT compiles only the reusable byte code


JVM compiles complete byte code to machine code.
to machine code.

JVM provides platform independence. JIT improves the performance of JVM.


JRE
(Java Runtime Environment) is an installation package that provides an environment to only run(not
develop) the java program(or application)onto your machine. JRE is only used by those who only want to
run Java programs that are end-users of your system.
Now let us discuss the components of JRE in order to understand its importance of it and perceive how it
actually works. For this let us discuss components.
The components of JRE are as follows:
1. Deployment technologies, including deployment, Java Web Start, and Java Plug-in.
2. User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility,
Image I/O, Print Service, Sound, drag, and drop (DnD), and input methods.
3. Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity
(JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote
Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP), and scripting.
4. Other base libraries, including international support, input/output (I/O), extension mechanism,
Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking,
Override Mechanism, Security, Serialization, and Java for XML Processing (XML JAXP).
5. Lang and util base libraries, including lang and util, management, versioning, zip, instrument,
reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref
Objects, and Regular Expressions.
6. Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

Difference between Byte Code and Machine Code

Byte code is an intermediate code between the source code and machine code. It is a low-level code that is
the result of the compilation of a source code which is written in a high-level language. It is processed by a
virtual machine like Java Virtual Machine (JVM).
Byte code is a non-runnable code after it is translated by an interpreter into machine code then it is
understandable by the machine. It is compiled to run on JVM, any system having JVM can run it
irrespective of their operating system. That’s why Java is platform-independent. Byte code is referred to as
a Portable code.

Machine Code:
Machine code is a set of instructions that is directly machine-understandable and it is processed by the
Central Processing Unit (CPU). Machine code is in binary (0’s and 1’s) format which is completely different
from the byte code and source code. It is regarded as the most lowest-level representation of the source
code. Machine code is obtained after compilation or interpretation. It is also called machine language.

S.NO. Byte Code Machine Code

Byte Code consisting of binary, hexadecimal, macro


instructions like (new, add, swap, etc) and it is not Machine code consisting of binary
01. directly understandable by the CPU. It is designed for instructions that are directly understandable
efficient execution by software such as a virtual by the CPU.
machine.intermediate-level

Byte code is considered as the intermediate-level Machine Code is considered as the low-level
02.
code. code.

03. Byte code is a non-runnable code generated after Machine code is a set of instructions in
compilation of source code and it relies on an machine language or in binary format and it is
S.NO. Byte Code Machine Code

interpreter to get executed. directly executed by CPU.

Byte code is executed by the virtual machine then the Machine code is not executed by a virtual
04.
Central Processing Unit. machine it is directly executed by CPU.

Byte code is less specific towards machine than the Machine code is more specific towards
05.
machine code. machine than the byte code.

It is not platform independent because the


object code of one platform can not be run on
It is platform-independent as it is dependent on the
the different Operating System. Object varies
06. virtual machine and the system having a virtual
depending upon system architecture and
machine can be executed irrespective of the platform.
native instructions associated with the
machine.

All the source code need not be converted into All the source code must be converted into
Machine code(or Object Code) for execution by CPU. machine code before it is executed by the
07. Some source code written by any specific high-level CPU.
language is converted into byte code then byte code
to object code for execution by CPU.

JDK JRE JVM

Typed languages
can be broadly categorized based on their typing disciplines. Besides strongly typed languages, other
common categories include weakly typed languages, statically typed languages, dynamically typed
languages, and untyped languages. Here's an overview of these categories:

1. Weakly Typed Languages


In weakly typed languages, types are less strictly enforced, meaning that implicit type conversions (often
called "type coercion") can happen automatically, sometimes leading to unexpected behavior.

- Examples:
- JavaScript : You can add a string to a number, and JavaScript will coerce the number to a string and
concatenate them.
```javascript
let result = "5" + 3; // "53"
```
- PHP : PHP will also perform type juggling automatically.
```php
$result = "5" + 3; // 8
```

2. Statically Typed Languages


In statically typed languages, the type of a variable is known at compile-time. This means that types are
checked before the code is run, often resulting in fewer runtime errors.

- Examples:
- C : Variables must be declared with a type, and the type is checked during compilation.
```c
int number = 10;
```
- C++ : Similar to C, but with support for more advanced type features like templates.
```cpp
std::string text = "Hello";
```

3. Dynamically Typed Languages


In dynamically typed languages, types are determined at runtime. This allows for more flexibility but can
lead to type-related errors that are only discovered when the code is executed.

- Examples:
- Python : Variables do not require a type declaration; types are inferred at runtime.
```python
number = 5 Initially an integer
number = "Five" Now a string
```
- Ruby : Also dynamically typed, allowing variables to change types.
```ruby
number = 10
number = "Ten"
```

4. Untyped Languages
Untyped languages, or typeless languages, do not have explicit types for variables. This category is
somewhat rare, as most modern languages have some form of typing system.

- Examples:
- Assembly Language : At the hardware level, most assembly languages do not have the concept of
types; they work directly with memory addresses and registers.
- Early Versions of BASIC : Some early dialects of BASIC were effectively untyped, allowing any kind of
data to be assigned to variables without enforcing type constraints.

5. Gradually Typed Languages


Gradually typed languages allow mixing statically and dynamically typed code. This provides the flexibility
of dynamic typing with the safety of static typing where needed.

- Examples:
- TypeScript : A superset of JavaScript that allows optional static typing. You can choose to add type
annotations or not.
```typescript
let number: number = 5; // Statically typed
let text = "Hello"; // Inferred type, dynamically typed
```
- Python (with type hints) : While Python is dynamically typed, recent versions allow for optional type
hints.
```python
def add(x: int, y: int) -> int:
return x + y
```
Conclusion
Each type system has its advantages and trade-offs. Strongly typed and statically typed languages
emphasize safety and predictability, while weakly typed and dynamically typed languages offer more
flexibility and simplicity. The choice between them depends on the specific needs of a project and the
preferences of the development team.

What Does It Mean to Be Strongly Typed?

In a strongly typed language like Java, every variable and expression has a type that is explicitly defined
and enforced at compile-time. This means that once a variable is declared to be of a certain type, it cannot
be assigned a value of another type without an explicit conversion. For example, you cannot assign an
integer to a variable declared as a string without converting the integer to a string first.

Example:

```java
int number = 5;
String text = "Hello";
// This would cause a compile-time error
text = number; // Incompatible types: int cannot be converted to String
```

Benefits (Feature) of Being Strongly Typed

1. Error Prevention:
- Strong typing helps catch type-related errors at compile time, reducing the likelihood of runtime errors.
This makes the code more robust and reliable.

2. Code Clarity:
- Explicit type declarations make the code more readable and easier to understand, as the types of
variables and expressions are clear.

3. Better Tool Support:


- Strongly typed languages benefit from better IDE support, including features like autocompletion,
refactoring, and static analysis. This can increase developer productivity.

4. Memory Safety:
- By enforcing type rules, Java reduces the risk of memory corruption that can occur in languages with
weaker typing systems.

5. Optimization:
- Since types are known at compile-time, the Java compiler can make optimizations that improve the
performance of the generated bytecode.

Potential Drawbacks
While being strongly typed is generally seen as a feature, it can introduce some complexity and verbosity,
especially in large projects or when dealing with generic data structures.

1. Verbosity:
- The need to explicitly declare types can make the code more verbose. This is particularly noticeable
when working with complex data types or when type inference would be more convenient.

2. Flexibility:
- Some developers argue that strongly typed languages are less flexible than dynamically typed
languages, where types are determined at runtime. In dynamically typed languages, you can write more
generic and reusable code with fewer type constraints.

3. Learning Curve:
- Beginners might find the strict type rules of Java to be a bit challenging initially, especially if they are
coming from a loosely typed language like JavaScript or Python.

Conclusion

Java's strong typing is largely seen as a beneficial feature because it enhances code safety, reliability, and
maintainability. However, it can be perceived as a drawback in scenarios where flexibility and brevity are
prioritized over strict type enforcement. Ultimately, the strong typing in Java contributes to its robustness
and is one of the reasons why Java is favored for large-scale, enterprise-level applications.

Java is a strongly typed and statically typed language, combining features that emphasize both safety
and predictability. Here's how Java fits within the broader landscape of typed languages:

Java as a Strongly Typed Language


- Strongly Typed : Java enforces strict type checking, meaning that variables must be used according to
their declared types. For instance, you cannot assign a floating-point value to an integer variable without
explicitly casting it. This prevents many common programming errors and enhances code safety.
```java
int number = 10;
// number = 10.5; // Error: incompatible types
number = (int) 10.5; // Explicit casting
```

Java as a Statically Typed Language


- Statically Typed : In Java, the type of a variable is known and checked at compile-time. This allows the
Java compiler to catch type-related errors early, before the code is even executed. As a result, Java
programs are generally more robust and less prone to certain types of runtime errors.
```java
String text = "Hello";
// text = 10; // Error: incompatible types
```

Where Java Stands


- Safety and Predictability : Java's strong and static typing ensures that variables and expressions are
used consistently, reducing the likelihood of bugs related to unexpected type conversions or operations.
- Performance : Static typing can also lead to performance optimizations, as the compiler has more
information about the types being used and can generate more efficient bytecode.
- Flexibility Trade-off : While Java's type system increases safety and performance, it may reduce some
flexibility compared to dynamically or weakly typed languages. Developers must explicitly declare types and
often perform type casting, which can be seen as more verbose and rigid.
Comparison with Other Typed Languages

Weakly Typed Languages : Unlike Java, languages like JavaScript or PHP are weakly typed, allowing
implicit type conversions, which can lead to unexpected behavior. For example, adding a string and a
number in JavaScript results in string concatenation, not an error.
- Dynamically Typed Languages : Java contrasts with languages like Python or Ruby, which are
dynamically typed, meaning that type checks occur at runtime rather than compile-time. This allows for
more flexible code but can introduce runtime errors that would be caught at compile-time in Java.
- Gradually Typed Languages : Languages like TypeScript (a superset of JavaScript) offer a middle
ground, allowing both dynamic and static typing. Java, however, remains fully statically typed, without the
flexibility to mix typing styles.

Conclusion
Java's combination of strong and static typing is a key feature that contributes to its reliability, making it a
popular choice for building large-scale, mission-critical applications where type safety and performance are
priorities. However, this comes at the cost of some flexibility and ease of use compared to more
dynamically or weakly typed languages.

Format specifiers in Java are used in conjunction with the `printf` or `String.format` methods to format
strings. They allow you to specify how different types of data should be formatted and displayed. Here's a
brief overview of common format specifiers and examples:

### Common Format Specifiers

1. **`%d`**: Formats an integer.


2. **`%f`**: Formats a floating-point number.
3. **`%s`**: Formats a string.
4. **`%c`**: Formats a character.
5. **`%b`**: Formats a boolean.
6. **`%x`**: Formats an integer as a hexadecimal.
7. **`%%`**: Prints a literal `%` character.

### Examples

1. **Integer (`%d`)**:
```java
int number = 42;
System.out.printf("The number is %d%n", number);
```
**Output**: `The number is 42`

2. **Floating-Point (`%f`)**:
```java
double price = 123.456;
System.out.printf("The price is %.2f%n", price);
```
**Output**: `The price is 123.46`

3. **String (`%s`)**:
```java
String name = "Alice";
System.out.printf("Hello, %s!%n", name);
```
**Output**: `Hello, Alice!`

4. **Character (`%c`)**:
```java
char grade = 'A';
System.out.printf("Your grade is %c%n", grade);
```
**Output**: `Your grade is A`

5. **Boolean (`%b`)**:
```java
boolean isPassed = true;
System.out.printf("Pass status: %b%n", isPassed);
```
**Output**: `Pass status: true`

6. **Hexadecimal (`%x`)**:
```java
int hex = 255;
System.out.printf("Hexadecimal value: %x%n", hex);
```
**Output**: `Hexadecimal value: ff`

7. **Literal Percent (`%%`)**:


```java
System.out.printf("Discount: 20%%%n");
```
**Output**: `Discount: 20%`

### Additional Formatting Options


- **Width**: You can specify a minimum width, e.g., `%5d` for an integer.
- **Precision**: For floating-point numbers, you can specify the number of decimal places, e.g., `%.2f`.
- **Flags**: You can add flags such as `-` for left-justification, `+` for including a sign, and `0` for padding
with zeros.

### Example with Multiple Specifiers


```java
String name = "John";
int age = 30;
double balance = 1234.567;
System.out.printf("Name: %s, Age: %d, Balance: $%.2f%n", name, age, balance);
```
**Output**: `Name: John, Age: 30, Balance: $1234.57`

These format specifiers give you fine control over how data is represented in strings, making it easier to
create well-formatted output in your Java programs.

Flags in format specifiers in Java are additional options that modify the output format. They are used within
the format string to control alignment, padding, sign display, and other formatting details. Flags are
specified immediately after the `%` symbol and before the format specifier (e.g., `%d`, `%f`, etc.).

### Common Flags

1. **`-` (Left Justify)**:


- By default, the output is right-justified. The `-` flag left-justifies the output within the specified width.
- Example: `% -10d` means the integer will be left-aligned within a 10-character field.

2. **`+` (Include Sign)**:


- Forces a plus (`+`) or minus (`-`) sign to be included for numeric values.
- Example: `%+d` will display `+42` for the number `42`.

3. **`0` (Zero Padding)**:


- Pads the output with zeros instead of spaces, filling the specified width.
- Example: `%05d` will display `00042` if the integer is `42`.

4. **` `(Space for Positive Numbers)**:


- Leaves a space before positive numbers. Negative numbers already have a minus sign, so this flag is
useful to align positive and negative numbers.
- Example: `% d` will display ` 42` for `42` and `-42` for `-42`.

5. **`,` (Grouping Separator)**:


- Adds a comma as a thousands separator for numeric values.
- Example: `%,d` will display `1,000` for `1000`.

6. **`(` (Enclose Negative Numbers in Parentheses)**:


- Displays negative numbers in parentheses instead of with a minus sign.
- Example: `%(d` will display `(42)` for `-42`.

7. **`#` (Alternate Form)**:


- For octal and hexadecimal values, `#` adds a prefix (`0` for octal and `0x` for hexadecimal).
- For floating-point numbers, it ensures the output always contains a decimal point, even if there are no
digits after it.
- Example: `%#x` for `255` will display `0xff`.

### Examples with Flags

1. **Left Justify (`-`)**:


```java
int number = 42;
System.out.printf("Left justified: %-10d.%n", number);
```
**Output**: `Left justified: 42 .`

2. **Include Sign (`+`)**:


```java
int number = 42;
System.out.printf("With sign: %+d%n", number);
```
**Output**: `With sign: +42`

3. **Zero Padding (`0`)**:


```java
int number = 42;
System.out.printf("Zero padded: %05d%n", number);
```
**Output**: `Zero padded: 00042`

4. **Space for Positive Numbers (` `)**:


```java
int number = 42;
System.out.printf("Space for positive: % d%n", number);
```
**Output**: `Space for positive: 42`

5. **Grouping Separator (`,`)**:


```java
int largeNumber = 1000000;
System.out.printf("With grouping: %,d%n", largeNumber);
```
**Output**: `With grouping: 1,000,000`

6. **Enclose Negative Numbers (`(`)**:


```java
int negativeNumber = -42;
System.out.printf("Enclosed negative: %(d%n", negativeNumber);
```
**Output**: `Enclosed negative: (42)`

7. **Alternate Form (`#`)**:


```java
int hexNumber = 255;
System.out.printf("Hex with prefix: %#x%n", hexNumber);
```
**Output**: `Hex with prefix: 0xff`

### Combining Flags

You can combine multiple flags in a single format specifier, for example:
```java
int number = 42;
System.out.printf("Combined: %+08d%n", number);
```
**Output**: `Combined: +0000042`

Here, the `+`, `0`, and `8` flags are combined to display the number `42` with a sign, padded with zeros to a
total width of 8 characters.

Flags provide flexibility in formatting output, allowing you to create custom formats that suit your needs.

Java Tokens, Data types, variables


Comments in Java
In a program, comments are like indents one makes, they are used so that it is easier for someone who isn’t familiar
with the language to be able to understand the code. It will also make the job easier for you, as a coder, to find
errors in the code since you will be easily able to find the location of the bug. Comments are ignored by the compiler
while compiling a code, which makes the job more complex in the long run when they have to go through so much
code to find one line.
In Java there are three types of comments:
1. Single-line comments.
2. Multi-line comments.
3. Documentation comments.
A. Single-line comments
A beginner-level programmer uses mostly single-line comments for describing the code functionality. It’s the easiest
typed comments.
Syntax:
//Comments here( Text in this line only is considered as comment )
Examples in an actual code
Example:
//Comments here( Text in this line only is considered as comment )
class Scomment
{
public static void main(String args[])
{
System.out.println("Single line comment above");
}
}
Output:
Single line comment above
B. Multi-line Comments:
To describe a full method in a code or a complex snippet single line comments can be tedious to write since we have
to give ‘//’ at every line. So to overcome this multi-line comments can be used.
Syntax:
/ Comment starts
continues
continues
.
.
Comment ends /
Example:
 Java
Java
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
}
}
Output:
Multi line comments below
We can also accomplish single line comments by using the above syntax as shown below:
/ Comment line 1 /
C. Documentation Comments:
This type of comment is used generally when writing code for a project/software package, since it helps to generate
a documentation page for reference, which can be used for getting information about methods present, its
parameters, etc. For example, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto-
generated documentation page that is generated by using documentation comments and a javadoc tool for
processing the comments.
Syntax:
/ Comment start

tags are used in order to specify a parameter


or method or heading
HTML tags can also be used
such as <h1>

comment ends /
 Java
Java
import java.io. ;
class GFG {
public static void main (String[] args) {
/
comment line 1
comment line 2
/
}
}

Keywords
in Java are reserved words that have a predefined meaning in the language and cannot be used for naming variables,
methods, classes, or other identifiers. They form the basic syntax and structure of Java programs. Here’s a list of
commonly used keywords in Java:

### 1. Access Modifiers:


- `public`: Access from any other class.
- `protected`: Access within the same package and subclasses.
- `private`: Access within the same class only.

### 2. Class, Method, and Variable Modifiers:


- `abstract`: Declares an abstract class or method.
- `static`: Indicates that a method or variable belongs to the class, rather than instances of the class.
- `final`: Defines a constant or prevents a method from being overridden or a class from being subclassed.
- `synchronized`: Ensures that a method can be accessed by only one thread at a time.
- `volatile`: Indicates that a variable may be changed unexpectedly in a multithreading environment.
- `transient`: Prevents a variable from being serialized.

### 3. Control Flow Statements:


- `if`: Introduces a conditional statement.
- `else`: Specifies an alternative block of code if the `if` condition is false.
- `switch`: Introduces a block of code that can be executed based on the value of a variable.
- `case`: Defines a branch in a `switch` statement.
- `default`: Specifies a block of code to be executed if no `case` matches in a `switch` statement.
- `while`: Introduces a loop that executes as long as a condition is true.
- `do`: Introduces a loop that executes at least once before checking a condition.
- `for`: Introduces a loop with initialization, condition-checking, and increment/decrement.
- `break`: Exits from a loop or `switch` statement.
- `continue`: Skips the current iteration of a loop and proceeds to the next iteration.
- `return`: Exits from a method and optionally returns a value.
- `try`: Introduces a block of code that might throw an exception.
- `catch`: Defines a block of code to handle exceptions.
- `finally`: Defines a block of code that executes after `try` and `catch`, regardless of whether an exception was
thrown or not.
- `throw`: Used to explicitly throw an exception.
- `throws`: Declares that a method can throw exceptions.

### 4. Object-Oriented Programming Keywords:


- `class`: Defines a new class.
- `interface`: Defines a new interface.
- `extends`: Indicates that a class is inheriting from a superclass.
- `implements`: Indicates that a class is implementing an interface.
- `new`: Creates new objects.
- `this`: Refers to the current object instance.
- `super`: Refers to the superclass of the current object.
- `instanceof`: Tests whether an object is an instance of a specific class or interface.

### 5. Primitive Data Types:


- `int`: Represents integer values.
- `byte`: Represents 8-bit signed integers.
- `short`: Represents 16-bit signed integers.
- `long`: Represents 64-bit signed integers.
- `float`: Represents single-precision floating-point numbers.
- `double`: Represents double-precision floating-point numbers.
- `char`: Represents a single 16-bit Unicode character.
- `boolean`: Represents true or false values.

### 6. Other Useful Keywords:


- `void`: Indicates that a method does not return any value.
- `null`: Represents the absence of a value or an object.
- `package`: Defines a namespace for classes.
- `import`: Includes other Java packages or classes in your code.
- `enum`: Defines a fixed set of constants.

### 7. Special Purpose Keywords:


- `assert`: Used for debugging purposes to make an assertion.
- `native`: Indicates that a method is implemented in native code using JNI (Java Native Interface).
- `strictfp`: Restricts floating-point calculations to ensure portability.
- `goto`: Reserved but not used in Java.
- `const`: Reserved but not used in Java (use `final` instead).

### Note:
- Keywords are case-sensitive, so `Public` is not the same as `public`.
- The keywords `goto` and `const` are reserved but not used in Java, meaning they cannot be used as identifiers
even though they have no functionality.

These keywords form the foundation of writing Java programs, and understanding them is essential for any Java
developer.

Identifiers in Java
Identifiers in Java are the names given to various programming elements such as variables, methods, classes,
packages, and interfaces. They are used to uniquely identify these elements within the code.

### Examples of Identifiers:


- Variable names: `age`, `totalAmount`
- Class names: `Person`, `Main`
- Method names: `calculateTotal()`, `printDetails()`
- Constants: `MAX_VALUE`, `PI`

### Rules for Naming Identifiers in Java:

1. Allowed Characters:
- An identifier can contain letters (uppercase `A-Z` and lowercase `a-z`), digits (`0-9`), underscore (`_`), and
dollar sign (`$`).
- Examples: `name`, `myVariable`, `MAX_VALUE`, `price$`, `total_amount`

2. Starting Character:
- An identifier must begin with a letter (either uppercase or lowercase), an underscore (`_`), or a dollar sign (`$`).
- Identifiers cannot start with a digit.
- Examples: `myVariable`, `_tempValue`, `$data`

3. No Spaces Allowed:
- Identifiers cannot contain spaces.
- Incorrect Example: `my variable` (This is invalid)

4. Case Sensitivity:
- Identifiers are case-sensitive . This means `age`, `Age`, and `AGE` are considered three different identifiers.
- Examples: `total`, `Total`, `TOTAL` (all are different)

5. Keywords Not Allowed:


- Identifiers cannot be the same as Java keywords (reserved words) like `int`, `class`, `static`, `if`, etc.
- Incorrect Example: `int` (Invalid, because `int` is a keyword)

6. No Length Limit:
- There is no limit on the length of an identifier, but it’s a good practice to keep them reasonably short and
meaningful.
- Example: `totalAmountInAccount` (valid, but long)

7. No Special Characters:
- Special characters like `!`, `@`, `#`, `%`, `^`, `&`, ` `, etc., are not allowed in identifiers.
- Incorrect Example: `total%value` (Invalid, `%` is not allowed)

8. Underscore and Dollar Sign:


- The underscore (`_`) and dollar sign (`$`) are legal, but typically the dollar sign is not used unless it's automatically
generated (e.g., by some compilers or tools). The underscore is often used in naming constants or to separate words.
- Example: `final_value`, `$temp`

### Best Practices for Naming Identifiers:

1. Meaningful Names:
- Choose descriptive names that convey the purpose of the variable, method, or class.
- Good Example: `totalPrice`, `calculateArea()`
- Bad Example: `tp`, `ca()`

2. Camel Case for Variables and Methods:


- Use camelCase for variable and method names where the first word is lowercase, and each subsequent word
starts with an uppercase letter.
- Example: `totalAmount`, `getUserName()`

3. Pascal Case for Class Names:


- Use PascalCase for class names where each word starts with an uppercase letter.
- Example: `Person`, `MainClass`

4. Uppercase for Constants:


- Use all uppercase letters with underscores for constants.
- Example: `MAX_VALUE`, `PI`

### Summary:
Identifiers in Java are crucial as they give names to the various elements in your code. Following the rules and best
practices ensures that your code is readable, maintainable, and free from syntax errors.

Naming Conventions of the Different Identifiers


The following table shows the popular conventions used for the different identifiers.
Type, Naming Rules, Examples
Class, It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms., public class Employee
{
//code snippet
}
Interface, It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms., interface Printable
{
//code snippet
}
Method, It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as
actionPerformed()., class Employee
{
// method
void draw()
{
//code snippet
}
}
Variable, It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as
firstName, lastName.
Avoid using one-character variables such as x, y, z., class Employee
{
// variable
int id;
//code snippet
}

Java literals
literals are fixed values that are directly represented in the code. They are the basic building blocks for
representing data in Java programs. Here’s a detailed explanation of different types of Java literals:

1. Integer Literals:
 Integer literals are used to represent whole numbers without a fractional part.
 Decimal (Base 10) : The most common form, written as a sequence of digits without any prefix.
 Example: `int x = 100;`
 Octal (Base 8) : Uses digits from 0 to 7 and is prefixed with `0`.
 Example: `int x = 0123;` // Equivalent to 83 in decimal.

 Hexadecimal (Base 16) : Uses digits from 0 to 9 and letters `a` to `f` (or `A` to `F`), prefixed with `0x` or `0X`.
 Example: `int x = 0x1A3F;` // Equivalent to 6719 in decimal.

 Binary (Base 2) : Uses digits `0` and `1`, prefixed with `0b` or `0B`.
 Example: `int x = 0b1010;` // Equivalent to 10 in decimal.

 Underscore in Numeric Literals : Java 7 introduced the use of underscores to make numeric literals more
readable.
 Example: `int x = 1_000_000;` // Equivalent to 1000000.
 : An integer literal without a suffix is `int` by default. If it exceeds `int` size, an error occurs unless you add
the `L` or `l` suffix to make it `long`.
 - Example: `long bigNumber = 10000000000L;`
 Type Inference with `var`: Java 10 introduced `var` for local variables, where the type is inferred from the
literal.
 - Example: `var number = 10;` // `number` is inferred as `int`.

2. Floating-Point Literals:
Floating-point literals represent decimal numbers that have a fractional part.

 Standard Notation : A number with a decimal point.


 Example: `double d = 3.14159;`

 Scientific Notation : Represents large or small numbers using an exponent, denoted by `e` or `E`.
 - Example: `double d = 2.5e3;` // Equivalent to 2.5 10^3 or 2500.0.

 Float Type Suffix : By default, floating-point literals are of type `double`. To specify a `float` literal, append `f`
or `F` to the literal.
 Example: `float f = 3.14f;`

3. Character Literals:
 Character literals represent a single 16-bit Unicode character, enclosed in single quotes (`' '`).
 Single Character : Represents any single character.
 Example: `char c = 'A';`

 Escape Sequences : Special characters that are represented by a backslash (`\`) followed by a character.
- Examples:
- `\n`: Newline
- `\t`: Tab
- `\b`: Backspace
- `\'`: Single quote
- `\"`: Double quote
- `\\`: Backslash
- `\r`: Carriage return
- `\f`: Form feed
- `\uXXXX`: Unicode character (e.g., `\u0041` represents 'A').

4. String Literals:
 String literals represent a sequence of characters enclosed in double quotes (`" "`).

- Simple Strings : A sequence of characters.


- Example: `String s = "Hello, World!";`
- Escape Sequences in Strings : Similar to character literals, escape sequences can be used within
strings.
- Example: `String s = "Line 1\nLine 2";` // Produces:
 ```
 Line 1
 Line 2
 ```
Concatenation : Strings can be concatenated using the `+` operator.
- Example: `String s = "Hello, " + "World!";`
5. Boolean Literals:
Boolean literals represent one of two values: `true` or `false`.
Usage : Used in control flow statements and conditions.
Example: `boolean isJavaFun = true;`

6. Null Literal:
The `null` literal represents the absence of a reference to any object.
Usage : Can be assigned to any reference type (objects, arrays, etc.) to indicate that the reference variable points
to nothing. Example: `String s = null;`

7. Null Literal in Arrays:


- Example: `int[] arr = null;` // Indicates that `arr` doesn't point to any array.

8. Class Literals:
Class literals represent the class or interface itself, rather than an instance of it.
Usage : Used with the `.class` syntax. Example: `Class c = String.class;`

9. Literals in Enumerations:
Enumerations (enums) are special classes in Java that represent a group of constants.
Enum Literal : Each value in an enum is a literal.
- Example:
```java
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Day day = Day.MONDAY;

Operators

Operator Type Operator Description Example


Arithmetic
+ Addition int sum = a + b;
Operators
- Subtraction int difference = a - b;
* Multiplication int product = a *b;
Division (integer division truncates the decimal
/ int quotient = a / b;
part)
% Modulus (remainder of division) int remainder = a % b;
Unary Operators + Unary plus (often redundant) int positive = +a;
- Unary minus (negation) int negative = -a;
++ Increment (pre and post) ++a, a++
-- Decrement (pre and post) --a, a--
! Logical NOT boolean isFalse = !isTrue;
Assignment
= Simple assignment a = b;
Operators
+= Add and assign a += b; // a = a + b;
-= Subtract and assign a -= b; // a = a - b;
= Multiply and assign a = b; // a = a b;
/= Divide and assign a /= b; // a = a / b;
%= Modulus and assign a %= b; // a = a % b;
Relational Operators == Equal to boolean isEqual = (a == b);
!= Not equal to boolean isNotEqual = (a != b);
> Greater than boolean isGreater = (a > b);
< Less than boolean isLess = (a < b);
boolean isGreaterOrEqual = (a >=
>= Greater than or equal to
b);
<= Less than or equal to boolean isLessOrEqual = (a <= b);
boolean result = (a > b) && (c >
Logical Operators && Logical AND (both operands must be true)
d);
` `
! Logical NOT (inverts the boolean value) boolean result = !(a > b);
Bitwise Operators & Bitwise AND (operates on individual bits) int result = a & b;
Bitwise OR (operates on
` `
individual bits)
^ Bitwise XOR (exclusive OR) int result = a ^ b;
~ Bitwise Complement (inverts all bits) int result = ~a;
Operator Type Operator Description Example
<< Left Shift (shifts bits to the left, filling with zeros) int result = a << 2;
Right Shift (shifts bits to the right, preserving the
>> int result = a >> 2;
sign)
Unsigned Right Shift (shifts bits to the right,
>>> int result = a >>> 2;
filling with zeros)
Ternary Operator ?: Conditional (shorthand for if-else) int result = (a > b) ? a : b;
Checks if an object is an instance of a specific boolean isString = obj instanceof
Instanceof Operator instanceof
class or subclass String;
Type Cast Operator (type) Casts a variable from one type to another int a = (int) 3.14;
Special Operators new Creates a new instance of an object MyClass obj = new MyClass();
Accesses a member (field or method) of a class
. obj.method();
or object
[] Array access (accesses an element of an array) int element = array[0];
String String message = "Hello, " +
+ Concatenates two strings
Concatenation "World!";
+= Concatenates and assigns message += "World!";

Separators in Java:

Separator Symbol Purpose Example


Group expressions, method parameters, control flow
Parentheses () System.out.println("Hello");
statements
Braces {} Define blocks of code (methods, classes, loops) if (x > 0) { ... }
Brackets [] Define arrays, access array elements int[] numbers = {1, 2, 3};
Semicolon ; End of statements int x = 10;
Comma , Separate items in lists (parameters, array elements) void myMethod(int a, int b);
Period . Access class/object members, package names System.out.println("Hello");
Colon : Used in ternary operator, enhanced for loop int result = (x > 0) ? x : -x;
Double Colon :: Method reference (Java 8 and later) MyClass::methodName
These separators are essential in defining the structure and flow of Java programs, ensuring that the code
is organized and can be easily parsed by the Java compiler.
Java Programming Structure
Data Types
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use.
That is why we need to declare variable's type and name.
There are 8 types of primitive data types:

Type Description Default Size Example Literals Range of values


boolean true or false false 8 bits true, false true, false
twos-complement
byte 0 8 bits (none) -128 to 127
integer
characters representation of ASCII
16 ‘a’, ‘\u0041’, ‘\101’, ‘\\’,
char Unicode character \u0000 values
bits ‘\’, ‘\n’, ‘β’
0 to 255
twos-complement 16
short 0 (none) -32,768 to 32,767
integer bits
-2,147,483,648
twos-complement 32
int 0 -2,-1,0,1,2 to
intger bits
2,147,483,647
-9,223,372,036,854,775,808
twos-complement 64
long 0 -2L,-1L,0L,1L,2L to
integer bits
9,223,372,036,854,775,807
IEEE 754 floating 32 1.23e100f , -1.23e-
float 0.0 upto 7 decimal digits
point bits 100f , .3f ,3.14F
IEEE 754 floating 64 1.23456e300d , -123456e-
double 0.0 upto 16 decimal digits
point bits 300d , 1e1d

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
It doesn’t occupy any main memory storage space because it uses “flip-flops” for storing one bit of
information
Default value: false
Example:
1. Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data
type.
Example:
1. byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example:
1. short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648
(-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
Example:
1. int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is
- 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The
long data type is used when you need a range of values more than those provided by int.
Example:
1. long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its default
value is 0.0F.
Example:
1. float f1 = 234.5f
ADVERTISEMENT
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.
Example:
1. double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\
uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
1. char letterA = 'A'
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode
system. To get detail explanation about Unicode visit next page.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of
the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
o ASCII (American Standard Code for Information Interchange) for the United States.
o ISO 8859-1 for Western European Language.
o KOI-8 for Russian.
o GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Default value: (white space )
Default values are applicable for class level variables but not for local variables

Non-Primitive Data Type or Reference Data Types


The Reference Data Types will contain a memory address of variable values because the reference types
won’t store the variable value directly in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a string in Java
is, that the string is designed to hold a sequence of characters in a single variable whereas, a character
array is a collection of separate char-type entities. Unlike C/C++, Java strings are not terminated with a null
character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2. Class
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:
1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded
by the keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :
1. State : It is represented by the attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by the methods of an object. It also reflects the response of an object to
other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an interface are by
default abstract (only method signature, no body).
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class implementing
Player must be able to (or must implement) move(). So it specifies a set of methods that the class
has to implement.
 If a class implements an interface and does not provide method bodies for all functions specified in
the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface . If a class implements this interface, then it can be
used to sort a collection.
5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. The following are some important points about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Since arrays are objects in Java, we can find their length using member length. This is different from
C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable .

Java Variables

 Variables in Java are used to store data that can be referenced and manipulated within a program.
They are essential for creating dynamic and functional code. Here's an overview of Java variables:
 What is a Variable?
 A variable in Java is a container that holds data that can be used and modified throughout a program.
 Each variable has a name (identifier), type, and value.
 Types of Variables
 Java variables are categorized based on their scope and usage
 Variables in Java must be declared with a specific data type, which determines the type and size of data
they can store.

Local Variables
A variable defined within a block or method or constructor is called a local variable.
 The Local variable is created at the time of declaration and destroyed after exiting from the block or
when the call returns from the function.
 The scope of these variables exists only within the block in which the variables are declared, i.e., we
can access these variables only within that block.
 Initialization of the local variable is mandatory before using it in the defined scope.
- Example:
public void display() {
int age = 25; // Local variable
System.out.println(age);
}
```
Instance Variables (Non-Static Fields):
Instance variables are non-static variables and are declared in a class outside of any method, constructor,
or block.
 As instance variables are declared in a class, these variables are created when an object of the class
is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not specify any
access specifier, then the default access specifier will be used.
 Initialization of an instance variable is not mandatory. Its default value is dependent on the data
type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes
like Integer it is null, etc.
 Instance variables can be accessed only by creating objects.
 We initialize instance variables using constructors while creating an object. We can also
use instance blocks to initialize the instance variables.

Static Variables (Class Variables):


Static variables are also known as class variables.
 These variables are declared similarly to instance variables. The difference is that static variables
are declared using the static keyword within a class outside of any method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static variable per class, irrespective of
how many objects we create.
 Static variables are created at the start of program execution and destroyed automatically when
execution ends.
 Initialization of a static variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.
 If we access a static variable like an instance variable (through an object), the compiler will show a
warning message, which won’t halt the program. The compiler will replace the object name with
the class name automatically.
 If we access a static variable without the class name, the compiler will automatically append the
class name. But for accessing the static variable of a different class, we must mention the class
name as 2 different classes might have a static variable with the same name.
 Static variables cannot be declared locally inside an instance method.
 Static blocks can be used to initialize static variables.

Variable Declaration and Initialization


- Declaration: Specifying the variable's type and name.
int number;
String name;
- Initialization: Assigning a value to the variable.
int number = 10;
String name = "Alice";
- Combined Declaration and Initialization:
int age = 25;
boolean isValid = true;
Variable Naming Rules
 Variable names are case-sensitive.
 They must begin with a letter, dollar sign (`$`), or underscore (`_`).
 Names cannot start with a digit.
 They cannot be Java reserved keywords (like `int`, `class`, etc.).
 It’s recommended to use meaningful names that describe the variable's purpose.
 Variables in Java must be declared with a specific data type, which determines the type and size of data
they can store.
Best Practices
 Always use descriptive variable names for better code readability.
 Initialize variables before use to avoid unexpected errors.
 Use static variables judiciously, as they are shared across all instances of a class.
Scope of Variables
 Local Variables: Scope is limited to the block of code in which they are declared.
 Instance Variables: Scope is within the class, accessible by all methods of the class (through the
object).
 Static Variables: Scope is the entire class, shared among all instances of the class.
 Final Variables :Declared using the `final` keyword to make the variable constant (i.e., its value
cannot be changed once initialized).

You might also like