Java Notes
Java Notes
Java Notes
INTRODUCTION TO JAVA 3
Features of Java 6
Applications of java 8
JRE 20
TYPED LANGUAGES 22
Comments in Java 28
Keywords 29
Identifiers in Java 31
Java literals 33
Operators 35
Separators in Java: 36
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.
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
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.
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
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
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.
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`.
(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
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.
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!
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.
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.
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.
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.
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
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.
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.
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:
- 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
```
- 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";
```
- 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.
- 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.
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
```
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.
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:
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:
### 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`
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.).
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.
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:
### 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.
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)
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)
1. Meaningful Names:
- Choose descriptive names that convey the purpose of the variable, method, or class.
- Good Example: `totalPrice`, `calculateArea()`
- Bad Example: `tp`, `ca()`
### 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.
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.
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 (`" "`).
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;`
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
Separators in Java:
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.