Introduction To Java Language - Chapter 2
Introduction To Java Language - Chapter 2
Chapter – 2
Java is considered both a compiled and interpreted language. This is because Java source code
is first compiled to bytecode, which is then interpreted by the Java Virtual Machine. The Java
Virtual Machine interprets the bytecode and converts it to platform-specific machine code.
Hence, Java is also called a platform-independent programming language.
What is Java?
Java is a general-purpose programming language intended to let programmers Write Once, Run
Anywhere (WORA). This means that compiled Java code can run on all platforms that support
Java without the need to recompile.
Java History
Java programming language was developed by Sun Microsystems of the USA in 1991, it was
originally called Oak by James Gosling, who was one of the inventors of the language. The
main goal for the developers was to make the language highly reliable, portable and simple.
The team for the development of Java language included Patrick Naughton, who discovered
that the existing languages such as C and C++ had some major drawbacks in terms of reliability
and portability. They modelled the new language Java on C and C++ while removing some
features which they considered as constraints. This made Java a really simple, portable and
powerful language. There is a chronicle of events that occurred during the whole course of
development of the Java language.
Java is one of widely used and popular programming language. Java is packed with full of
features, yet it still maintains the simplicity and flexibility that allows a developer to quickly
learn and start working on java projects with ease. The flexibility of writing a java code on one
machine and running it on several other machine makes it a popular choice
in programming world.
On top of that, the regular updates make it safe and stable choice for the projects that intend to
run for a longer period of time. The features of Java are also known as Java BuzzWords.
1) Simple
Java is a very simple programming language, it is easy to learn, read and write in Java. The
syntax of Java is clean and easy to understand.
Here’s why java is simple programming language compared to other popular programming
language:
• Java syntax is similar to C/C++ so it is easier to learn java if one is familiar with C or C++.
However java doesn’t use the complex features of C and C++ such as Pointers, go to
statements, preprocessors/ header files, multiple inheritance, operator overloading etc.
2) Platform Independent
Java is a platform independent language. Compiler(javac) converts source code (.java file) to
the byte code(.class file). JVM executes the bytecode produced by compiler. This byte code
can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that
is compiled on windows can run on Linux and vice-versa.
Each operating system has different JVM, however the output they produce after execution of
bytecode is same across all operating systems. That is why we call java as platform independent
language.
3) Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security
flaws like stack corruption or buffer overflow is impossible to exploit in Java.
a) Abstraction
b) Encapsulation
c) Inheritance
d) Polymorphism
5) Robust
Robust means reliable. Java programming language is developed in a way that puts a lot of
emphasis on early checking for possible errors, that’s why java compiler is able to detect errors
that are not easy to detect in other programming languages. The main features of java that
makes it robust are:
1. Garbage collection,
2. Exception Handling
3. Memory allocation.
6) Distributed
In simple words: The java programs can be distributed on more than one systems that are
connected to each other using internet connection. Objects on one JVM (java virtual machine)
can execute procedures on a remote JVM.
7) Multithreading
8) Portable
As discussed above, java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that makes java
code portable.
9) Architectural Neutral
As we know Java is a platform independent language, which means program written and
compiled on one machine can run on any other machine having different operating system.
Java follows the principle of “Write once run anywhere“
Compiler converts the java file into byte-code and this byte code is machine independent, java
virtual machine can easily translate this byte code into machine specific code. This makes java
architectural neutral programming language.
10) Dynamic
Java is a dynamic programming language. OOPs allows developers to add new classes to the
existing packages, add new methods to the existing classes as well as modifying the method
without changing the original method code by using the concept of method overriding.
All these features make java dynamic. It also allows classes to be loaded on demand. It also
supports functions from its native languages such as C and C++.
12. Performance
Java is significantly faster than other traditional interpreted programming languages. Compiled
java code which is known as byte code is like a machine code, that allows a faster execution.
Java uses Just in Time compiler which can execute the code on demand, this allows to execute
only the method that is being called, which makes it faster and efficient.
Also, java uses the concept of multithreading, which allows concurrent execution of several
parts of the code at the same time. This provides high performance.
Advantages of JAVA :
1) Simple
Unlike other programming languages, Java is the language that is easy to learn and
understand. The syntax of the Java language is based upon C++, and it uses automatic
garbage collection, which means there is no need for unreferenced objects from memory.
Java programming language can be read and written quickly because it has removed
features like explicit pointers, operator overloading, and more. However, Java is being used
and taught in numerous schools and colleges across the planet due to its simplicity.
2) Object-oriented
We all know that amongst other programming languages, Java is known as the most object-
oriented language because it’s more practical than other programming languages. For example,
anything stored in Java is the object responsible for taking care of data and behaviour
altogether. It further uses object-oriented concepts such as objects, class, inheritance,
encapsulation, polymorphism, and abstraction. Hence, this programming language can be
known as the object-oriented language.
3) Secured
Java doesn’t use any explicit pointers; it’s the safest and most secure programming language
for more than 20 years. The programming of Java is done under the virtual machine sandbox.
It provides the class loader, which is used in the loading of the class to JVM dynamically. Java
separates the class from the local file system from those which are imported to the network.
4) Robust
Java uses a strong memory system; hence it is the most robust programming language. Through
java code, exceptions can also be handled within the java program. To make java code stronger,
type checking can be used. Java doesn’t provide explicit pointers to avoid the programmer
accessing the memory directly from the java code. Due to its unique storage system, Java is
used in many big firms and organizations with ease.
5) Platform independent
After compiling java code for once, the need of compiling it, again and again, becomes 0; hence
it can efficiently run on several platforms. Java can be run anywhere and anytime, and during
the compilation of the java code, the byte code will be converted and makes the java platform-
independent programming language. No other programming language is a platform-
independent language other than Java.
6) Multithreaded
Java programming language is based on the multi-threaded environment where a big task can
be divided into smaller tasks or smaller threads and then runs separately. When the
multithreading function is going on in the java program, providing memory becomes 0. That
means countless tasks can be performed at the same time after dividing them into smaller
threads.
8) Portable
The java virtual machine manages the automatic garbage collection or memory management.
When the objects stored in the Java are of no use, and it does not refer to any other object, it
will be removed automatically by the automatic garbage collection.
10) Stability
The programs run by Java compose more stability than other programming languages.
However, the new update in Java will be introduced shortly with more advanced features and
functions. Java programming language is the preferred choice of many specialists to work
with.
Disadvantages of Java
1. Performance
If we compare Java with C, C++, and other programming languages in performance, Java’s
performance is comparatively slower. This is because it needs to be interpreted during its
runtime. On the other hand, the C++ programming language can be compiled on any operating
system from binary and therefore results in faster performance. Thus, Java has a disadvantage
over its performance with other languages.
2. Memory consumption
Since the Java language runs on top of the virtual machine, it consumes more memory than
you think. Meanwhile, other programming languages don’t consume ample memory; that is
why they are suitable for business, institution, individual, and more. The memory of the java
language manages from garbage collection, and when it runs, it affects the overall performance
of the web application.
3. Cost
Because Java requires higher processing and memory, it is a bit costly language compared to
various other programming languages. Hence, it’s not suitable and affordable to work with Java
because it needs a better hardware system which is very expensive. That’s why if complicated
programming needs to be done, it’s best to switch to other programming languages like C and
C++.
When we talk about the interaction of Java with machines, it lacks its performance. This is
because Java makes the machine less viable for the software, which needs to run quickly and
directly with the machine. Also, there are no explicit pointers in Java which makes Java a more
interactive language.
To create a complex UI, no graphical interface is perfect or suitable in Java. Although there are
many GUIs available, there are a lot of inconsistencies with them. A popular framework like
swing, SWT, JavaFX, JSF is there in Java for developing UI, but no one is stable for creating
the complicated UI. And if you want to choose one, you need to perform a lot of research.
6. No backup facility
The main focus of Java always lies in storage; hence it’s not suitable for data backup. This is
one of the essential java drawbacks, making it lose interest and rating amongst the users.
That’s why if you are looking for data backup along with high storage facility, go for various
other programming languages like C and C++. Because after Java, if any programming
language is best, it’s C or C++ only.
Although Java is the most readable and understandable programming language, the java codes
are verbose. It means that it has many words and difficult sentences for reading and
understanding. Through this, the java code becomes less readable. Therefore, Java mainly
focuses on being manageable, but at the same time, it compromises with long and difficult java
codes.
• Mobile Applications
• Web-based Applications
• Enterprise Applications
• Scientific Applications
• Gaming Applications
• Business Applications
• Distributed Applications
• Cloud-based Applications
1) Mobile Applications
Java is considered as the official programming language for mobile app development. It is
compatible with software such as Android Studio and Kotlin. Now you must be wondering
why only Java? The reason is that it can run on Java Virtual Machine(JVM), whereas Android
uses DVK(Dalvik Virtual Machine) to execute class files. These files are further bundled as
Android application Package(APK). With Java and its OOPs principles, it provides better
security and ease of simplicity with Android.
All desktop applications can easily be developed in Java. Java also provides GUI development
capability through various means mainly Abstract Windowing Toolkit (AWT), Swing and
JavaFX. While AWT holds a number of pre-assembled components like menu, list, button.
Swing is a GUI widget toolkit, it provides certain advanced elements like trees, scroll panes,
tables, tabbed panel, and lists.
3) Web-based Applications
Java is also used to develop web applications. It provides a vast support for web applications
through Servlets, Struts or JSPs. With the help of these technologies, you can develop any kind
of web application that you require. The easy coding and high security offered by this
programming language allow the development of a large number of applications for health,
social security, education, and insurance.
4) Enterprise Applications
Java is the first choice of many software developers for writing applications and Java Enterprise
Edition (Java EE) is a very popular platform that provides API and runtime environment for
scripting. It also includes network applications and web-services. JavaEE is also considered as
the backbone for a variety of banking applications which have Java running on the UI to back
server end.
5) Scientific Applications
Software developers see Java is the weapon of choice when it comes to coding the scientific
calculations and mathematical operations. These programs are designed to be highly secure
and lighting fast. they support a higher degree of portability and offer low maintenance. Some
of the most powerful applications like the MATLAB use Java for interacting user interface as
well as part of the core system.
6) Gaming Applications
Java has the support of the open-source most powerful 3D-Engine, the jMonkeyEngine that
has the unparalleled capability when it comes to the designing of 3D games. However, it does
cause an occasional latency issue for games as garbage collection cycles can cause noticeable
pauses. This issue will be solved in the newer versions of JVMs.
Java is the reason why the leading Big Data technologies like Hadoop have become a reality
and also the most powerful programming languages like Scala are existing. It is crystal clear
that Java is the backbone when it comes to developing Big Data using Java.
8) Business Applications:
9) Distributed Applications:
Distributed applications have several common requirements that arise specifically because of
their distributed nature and of the dynamic nature of the system and platforms they operate
on. Java offers options to realize these applications. The Jini (Java Intelligent Networking
Infrastructure) represents an infrastructure to provide, register, and find distributed services
based on its specification. One integral part of Jini is JavaSpaces, a mechanism that supports
distribution, persistence, and migration of objects in a network.
Cloud computing means on-demand delivery of IT resources via the internet with pay-as-you-
go pricing. It provides a solution for IT infrastructure at a low cost. Java provides you with
features that can help you build applications meaning that it can be used in the SaaS, IaaS and
PaaS development. It can serve the companies to build their applications remotely or help
companies share data with others, whatever the requirement.
Memory Allocation Functions like malloc(), calloc(), Using the 'new' Java supports
etc. can be used to allocate keyword, memory memory allocation
memory in C programs. allocation is through the usage
accomplished in C++. of the "new"
keyword.
Memory Programmers explicitly C++ builds on C but Java does not use
Manipulation manipulate memory. adds many new basic pointers but instead
types; however, they relies on automatic
are not designed to memory
form meaningful data management
structures like numbers through garbage
or strings easily. collection.
Object-Oriented Not supported for object-oriented C++ supports object- Java is fully object-
Programming (OOP) programming. oriented concepts like oriented, using
classes and multiple classes and objects
objects, similar to as the fundamental
BCPL. building blocks of
the program.
Platform Dependence C code needs to be recompiled Like C, C++ is Java's philosophy
and modified for each platform platform-dependent is "write once, run
or OS. and requires anywhere," using
recompilation for bytecode that
different OS. works across
platforms with
JVM.
Compilation Process Uses a compiler to translate code Uses a compiler to Compiles code into
directly to machine code. generate architecture- .class files
dependent binary files containing
or machine code. bytecode for
execution on the
JVM.
File Extensions Uses .c for source files. Uses .cpp for C++ Uses .java for
source files. source files.
Pointers Directly uses pointers to Uses pointers like C Does not use
manipulate memory locations. but adds additional pointers for
memory management memory access to
mechanisms, such as improve security
references. and simplify
memory
management.
Memory Access It cannot easily connect with More flexible in Relies on JVM's
Flexibility memory insertions (such as connecting to memory memory
complex data structures). via various types, such management and
as pointers and garbage collection
references. rather than direct
memory handling.
Number of Keywords It has 32 keywords for its Uses 60 keywords, Combines the
functionality. adding more features, paradigms of C and
such as support for C++ with 52
objects and classes. keywords designed
for simpler
implementation.
Java Environment
Architecture of Java
The architecture of the Java programming language showcases how a program is compiled
and executed when written in Java.
Definition
The Java architecture consists of the Java virtual machine component, the Java runtime
environment component, and the Java development kit component. These components
help bring together the process of interpretation and compilation in the Java program
execution process
The working of Java defines the process by which Java programs are written, compiled,
and executed. The above image provides a visual representation of the step-by-step
execution of a Java program. The detailed explanation of how Java works is given below:
1. Source Code: The first step in the architecture of Java involves writing the source code.
You can do this using a text editor or an IDE, which is responsible for defining the logic
and architecture of the program.
2. Java Compiler: The Java compiler then converts the source code into a platform-
independent bytecode. That can be executed by any device having a compatible JVM.
3. Bytecode: Bytecode is a compiled Java code that is platform-independent. It runs on
any device having a compatible JVM. This feature makes Java a platform-independent
language.
4. Java Virtual Machine (JVM): The Java Virtual Machine (JVM) is responsible for
converting the bytecode into machine code. This allows Java programs to run on any
platform. This supports the “Write Once, Run Anywhere” feature in Java.
5. Operating System (OS): The JVM hands over the machine code to the operating
system. After that, it interacts with the hardware for the execution of tasks in the source
code.
1. Compilation
Java source code is written in plain text files with a .java extension. The code is then
compiled using the Java compiler (javac), which converts it into bytecode (.class files).
The bytecode is platform-independent and can be executed on any system that has a
compatible JVM.
3. Execution
The JVM executes the bytecode line by line using its internal interpreter or just-in-time
(JIT) compiler. The interpreter translates bytecode into machine instructions on-the-fly,
while the JIT compiler dynamically compiles frequently executed bytecode into native
machine code for improved performance.
4. Memory Management
Java employs automatic memory management through the JVM's garbage collector. The
garbage collector tracks objects in memory and frees up resources for objects that are no
longer in use, relieving developers from manual memory management tasks.
5. Library Utilization
Developers leverage the Java Class Libraries and APIs to access pre-built functionality
and implement desired features in their applications. These libraries provide a vast array
of tools, utilities, and frameworks to simplify development tasks and enhance productivity.
JDK Architecture:
What is JDK?
The Java Development Kit (JDK) is basically a software development environment that is
provided by Oracle and other vendors who are responsible for building Java applications. It
consists of a package of tools that are necessary for developing, debugging, and running
programs in Java. For writing a Java application, the JDK is the first component to be installed.
Unlike Java Runtime Environment (JRE), which is used to run Java programs, the JDK
provides everything that is required for development, from writing the source code to
converting it to bytecode and then executing it on the Java Virtual Machine (JVM).
The Java Development Kit (JDK) is a software development environment that provides tools,
libraries, and components for developing Java applications. In this article, we will explore the
JDK, understand its components, and discuss its importance in Java development. We will also
cover the installation process and provide an overview of some key features.
Understanding the Java Development Kit (JDK)
The JDK is a bundle of software tools and resources necessary for developing Java
applications. It includes a set of libraries, a Java Virtual Machine (JVM), and various
development tools such as compilers, debuggers, and documentation. The JDK is available for
multiple platforms, including Windows, macOS, and Linux.
1. Java Compiler
The JDK includes the Java compiler (javac), which translates Java source code into
bytecode that can be executed by the JVM.
4. Development Tools
The JDK provides various development tools, such as the Java Debugger (jdb) for
debugging, the Javadoc tool for generating documentation, and the Java Archive (JAR)
tool for packaging Java applications.
5. Libraries
The JDK includes a vast collection of standard Java libraries (also known as the Java Class
Library or Java API). These libraries provide pre-built functionality for common tasks,
such as file handling, networking, and database access.
JVM Architecture
JVM is an abstract machine that provides the environment in which Java bytecode is executed.
The falling figure represents the architecture of the JVM.
1) Class Loaders
When we compile a source (.java) file, it gets converted into byte code as a .class file.
Furthermore, when we try to use this class in our program, the class loader loads it into the
main memory. Normally the class that contains the main () method is the first class to be loaded
into the memory. The class loading process happens in three phases.
2) Linking
Once a class is loaded into the memory, it undergoes the linking process. Linking a class or
interface involves combining the different elements and dependencies of the program together.
As the name suggests making required links with each other.
3) Initialization
This is the final stage of class loading. Initialization involves executing the initialization code
of the class or interface. This can include calling the class’s constructor, executing the static
block, and assigning values to all the static variables.
The explanation of the architecture of the JVM with reference to the above image is given
below:
• Class Loader: It is a part of the Java Virtual Machine (JVM) that loads the class files into
memory. When you run a Java program, the class loader is the first component that loads
the required classes so that the program can start to execute.
• Method area: It is one of the memory areas in the JVM where information related to
classes is stored. The information includes static variables, static blocks, static methods,
and instance methods.
• Heap: A heap is basically a memory location that is created when the JVM starts running.
After the Java program starts running, the size of the heap can grow or shrink depending
on the memory needs of the application.
• Stack: Stack in JVM is also called the thread stack. It is a part of the JVM memory that is
created for each individual thread when it starts running. It is used by that thread for
storing important data such as local variables, temporary results, and information that is
needed to call methods and return from them. Each thread consists of its own separate
JVM stack. Furthermore, Each stack frame has three parts : local variable array, operand
stack and frame data.
Local Variable Array : It contains values of local variables & method parameters.
Operand Stack : JVM uses it as workspace, some instruction push the values to it &
some pop from it & some other to performs arithmetic operations.
Frame Data : It contains all symbolic references related to the method. It also contains
reference of exception related to method.
• PC Registers – Each thread will have separate PC Registers; to hold the address of current
executing instruction once the instruction is executed the PC register will be updated with
the next instruction. PC Register keeps a record of the current instruction executing at any
moment. That is like a pointer to the current instruction in a sequence of instructions in a
program. Once the instruction is executed, the PC register is updated with the next
instruction. If the currently executing method is ‘native’, then the value of the program
counter register will be undefined.
• Native Method Stack: It is a part of the JVM memory that is responsible for handling all
the native methods used in a Java application. Native methods are the methods written in
languages like C or C++ instead of Java. The native stack keeps a track of those methods
during the time of execution.
2) Execution Engine: It is the central part of the JVM. Its main task is to execute the byte
code and execute the Java classes. The execution engine has three main components used
for executing Java classes.
• Interpreter
• JIT compiler
• Garbage collector
a) Interpreter: It converts the byte code into native code and executes. It sequentially
executes the code. The interpreter interprets continuously and even the same method
multiple times. This reduces the performance of the system, and to solve this, the JIT
compiler is introduced.
b) JIT compiler:
JIT compiler: The Just-In-Time (JIT) compiler is a part of the runtime environment. It helps
in improving the performance of Java applications by compiling bytecodes to machine code
at run time. The JIT compiler is enabled by default. When a method is compiled, the JVM
calls the compiled code of that method directly. The JIT compiler compiles the bytecode of
that method into machine code, compiling it “just in time” to run.
c) Garbage collector: The Garbage Collector in the JVM is responsible for finding and
removing the unused or unwanted objects from the memory. The working process involves
keeping track of all the objects in the heap space of the JVM and getting rid of those that
are not used by the program anymore. The process of garbage collection consists of two
main steps:
a. Mark: In this step, the garbage collector checks the objects that are still being used by the
program and the ones that are not.
b. Sweep: In this step, it clears out the objects that are not used. This helps to free up the
memory for future use.
JRE Architecture
Java is a versatile and popular programming language used for developing a wide range of
applications. To run Java programs, the Java Runtime Environment (JRE) is essential. In this
article, we will explore the Java Runtime Environment, its components, functionalities, and its
significance in Java application execution.
The Java Runtime Environment (JRE) is a software environment in which Java program
executes. It is a core component of the Java platform that provides all the necessary components
required for executing Java applications on any system, regardless of operating system and
underlying hardware. In simple terms, the JRE allows a computer system to run Java programs.
Java Runtime Environment (JRE) is a part of the Java Development Kit (JDK). It provides the
runtime environment required to execute compiled Java bytecode does not include
development tools such as the Java compiler, so it cannot be used to develop Java applications.
2) Memory Management
The JRE manages memory allocation and deallocation, ensuring efficient utilization of system
resources. It includes automatic memory management through garbage collection, which frees
up memory occupied by objects no longer in use.
3) Platform Integration
The JRE integrates with the underlying operating system to provide a consistent runtime
environment for Java applications. It abstracts the differences between operating systems,
allowing Java programs to run seamlessly across platforms.
4) Security
The JRE includes security features that protect against unauthorized access, data breaches, and
malicious code execution. It provides mechanisms for sandboxing, access control, and
encryption to ensure the safety and integrity of Java applications.
Without JRE:
• Java programs cannot run.
• The JVM cannot execute bytecode.
• Core Java libraries will not be available.
The Java Runtime Environment (JRE) is a runtime software environment that contains the Java
Virtual Machine (JVM) and essential core Java class libraries required to run Java programs on
any operating system.
If your computer system already has an up-to-date Java Development Kit (JDK) installed, you
do not need to install anything again. The JDK includes the JRE, which provides the runtime
support required to run Java programs, including those executed within Eclipse or other Java
IDEs.
Components of Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) consists of the following main components:
• Java Virtual Machine (JVM)
• Class Loader Subsystem
• Bytecode Verifier
• Execution Engine
o Interpreter
o Just-In-Time (JIT) compiler
• Garbage Collector
• Runtime Data Areas
o Heap
o Stack
o Method Area
o PC Register
o Native Method Stack
• Core Java Class Libraries (Java API)
• Java Native Interface (JNI) & Native Libraries
Working of JRE
Once we write any source code, we have to save it with the .java extension. Next we compile
our program using the "javac" command in command prompt (no need in any IDE). It translates
the code to the bytecode which is platform-independent. When we compile our program it will
generate a .class which has the bytecode for the equivalent java file. And that bytecode is
executed on any platform having the JRE. The workflow is explained below.
Class Loader- It loads the various classes dynamically in the JVM (Java Virtual Machine),
which are essential for executing the program. After JVM started following three class loader
are used:
Bootstrap class loader
Extension class loader
System class loader
Byte code verifier- It verifies the bytecode during the run time so that the code doesn't make
any disturbance for the interpreter. The codes are interpreted, only if it passes the tests of the
bytecode verifier that check the formatting and for illegal code.
Interpreter- When class loaded and code gets verified, then it reads the assembly code line by
line and process the following two functions:
• It executes the Byte Code.
• Make appropriate calls to the integrated hardware.
API
Java API acts as an intermediary in Java applications, connecting components within the
programming stack. It enables developers to utilize prebuilt Java components and facilitates
integration with external resources, streamlining development. Additionally, Java API enables
task automation and machine-to-machine interactions to save time and improve efficiency.
Java API is an application programming interface (API) that functions within software built
using the Java software programming language. It’s a deep technology that plays a critical but
hard-to-see role in Java applications. This page explains how Java API works, who uses it, and
why.
Java Program Structure
Java is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a wide
variety of applications. So, before diving in depth, it is necessary to understand the basic
structure of Java program in detail. In this section, we have discussed the basic structure of a
Java program. At the end of this section, you will able to develop the Hello world Java program,
easily.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
1. //First Java Program
o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:
1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
1. /**It is an example of documentation comment*/
2. Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can be only
one package statement in a Java program. It must be defined before any class and interface
declaration. It is necessary because a Java class can be placed in different packages and
directories based on the module they are used. For all these classes package belongs to a single
parent directory. We use the keyword package to declare the package name. For example:
1. package javatpoint; //where javatpoint is the package name
2. package [Link]; //where com is the root directory and javatpoint is the subdirectory
3. Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class
of a particular package, we need to import that class. The import statement represents the class
stored in the other package. We use the import keyword to import the class. It is written before
the class declaration and after the package statement. We use the import statement in two ways,
either import a specific class or import all classes of a particular package. In a Java program,
we can use multiple import statements. For example:
1. import [Link]; //it imports the Scanner class only
2. import [Link].*; //it imports all the class of the [Link] package
4. Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the class.
It contains only constants and method declarations. Another difference is that it cannot be
instantiated. We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword. For example:
1. interface car
2. {
3. void start();
4. void stop();
5. }
5. Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. A Java program may conation more than one class definition.
We use the class keyword to define the class. The class is a blueprint of a Java program. It
contains information about user-defined methods, variables, and constants. Every Java program
has at least one class that contains the main() method. For example:
1. class Student //class definition
2. {
3. }
• Since main () method of java executes only once throughout the java program execution
and hence its nature must be static.
• Since main () method must be accessed by every java programmer and hence whose
access specifier must be public.
• Each and every main () method of java must take array of objects of String.
• Block of statements represents set of executable statements which are in term calling
user-defined methods are containing business-logic.
• The file naming conversion in the java programming is that which-ever class is
containing main () method, that class name must be given as a file name with an
extension .java.
Public
public is a keyword in a java language whenever if it is preceded by main() method the scope
is available anywhere in the java environment that means main() method can be executed from
anywhere. main() method must be accessed by every java programmer and hence whose access
specifier must be public.
Static
static is a keyword in java if it is preceded by any class properties for that memory is allocated
only once in the program. Static method are executed only once in the program. main() method
of java executes only once throughout the java program execution and hence it declare must be
static.
Void
void is a special datatype also known as no return type, whenever it is preceded by main()
method that will be never return any value to the operating system. main() method of java is
not returning any value and hence its return type must be void.
String args[]
String args[] is a String array used to hold command line arguments in the form of String
values.
In case of main() method following changes are acceptable
1. We can declare String[] in any valid form.
• String[] args
• String args[]
• String []args
2. Instance of String[] we can take var-arg String parameter is String...
Syntax
main(String[] args) --> main(String... args)
3. We can change the order of modifiers i.e Instead of
Syntax
public static we can take static public
4. Instead of args we can take any valid java identifier.
Syntax
public static void main(String a[])
We can overload main() method ?
Yes, We can overload main() method. A Java class can have any number of main() methods.
But run the java program, which class should have main() method with signature as "public
static void main(String[] args). If you do any modification to this signature, compilation will
be successful. But, not run the java program. we will get the run time error as main method not
found.
Syntax
[Link]("--------------");
[Link]("------------");
class System
{
Static PrintStream out;
Static PrintStream err;
}
Examples of SOP Statements
Example
[Link]("Hello"); // ---------> Hello
int x=10, y=20;
[Link]("x"); // ---------> x
[Link](x); // ---------> 10
[Link]("Hello"+x); // ---------> Hello10
[Link](x+y); // ---------> 30
[Link](x+y+"Hello"); // ---------> 1020Hello
Example
class Hello
{
public static void main(String arg[])
{
[Link]("Hello word");
}
Java Tokens
Tokens in Java are the smallest units of a program that have a specific meaning to the compiler.
When you write code, the Java compiler performs lexical analysis and breaks down the entire
source code into tokens before parsing it. These tokens help the compiler understand the
structure and logic of the program. The main categories of tokens include keywords, identifiers,
literals, operators, separators, and comments. Each plays a unique role in defining how the
program is written and executed.
Java tokens are the smallest units or elements of a program. We have six main tokens available
in Java:
• Identifiers
• Literals
• Operators
• Separators
• Keywords
• Comments
1. Keywords
Keywords in Java are predefined or reserved words that have special meaning to the Java
compiler. Each keyword is assigned a special task or function and cannot be changed by the
user. You cannot use keywords as variables or identifiers as they are a part of Java syntax itself.
A keyword should always be written in lowercase as Java is a case sensitive language. Java
supports various keywords, some of them are listed below:
2. Identifier
Java Identifiers are the user-defined names of variables, methods, classes, arrays, packages,
and interfaces. Once you assign an identifier in the Java program, you can use it to refer the
value associated with that identifier in later statements. There are some de facto standards
which you must follow while naming the identifiers such as:
1) Identifiers must begin with a letter, dollar sign or underscore.
2) Apart from the first character, an identifier can have any combination of characters.
3) Identifiers in Java are case sensitive.
4) Java Identifiers can be of any length.
5) Identifier name cannot contain white spaces.
6) Any identifier name must not begin with a digit but can contain digits within.
7) Most importantly, keywords can’t be used as identifiers in Java.
Example:
//Valid Identifiers
$myvariable //correct
_variable //correct
variable //correct
edu_identifier_name //correct
edu2019var //correct
//Invalid Identifiers
edu variable //error
Edu_identifier //error
&variable //error
23identifier //error
switch //error
var/edu //error
edureka's //error
Example Code using Identifiers:
public class IdentifierExample {
public static void main(String[] args) {
int age = 25; // 'age' is an identifier for a variable
String name = "John"; // 'name' is another identifier
[Link]("Age: " + age);
[Link]("Name: " + name);
}
}
3. Literals
Literals in Java are similar to normal variables but their values cannot be changed once
assigned. In other words, literals are constant variables with fixed values. These are defined by
users and can belong to any data type. Java supports five types of literals which are as follows:
1) Integer
2) Floating Point
3) Character
4) String
5) Boolean
Syntax:
final data_type variable_name;
Example:
public class LiteralExample {
public static void main(String[] args) {
int num = 100; // Integer literal
double pi = 3.14159; // Floating-point literal
char grade = 'A'; // Character literal
String greeting = "Hello"; // String literal
2. Floating-Point Literals
Floating-point literals represent numbers with decimal points or in exponential notation. These
are used for specific values, such as measurements or calculations with fractions. Float literals
are suffixed with f or F, while double literals use d or D. Examples include 3.14, -0.5, and 2.5e3
(scientific notation).
3. Character Literals
Character literals represent a single character in single quotes ('). They can include letters,
digits, symbols, or escape sequences like '\n' (newline) and '\t' (tab). These literals are useful
for handling individual characters in text processing. Examples include 'A', 'z', and '#'.
4. String Literals
String literals represent sequences of characters in double quotes ("). They are used for
handling text data, such as messages, user input, or file content. Examples include "Hello",
"Java Programming", and "12345".
5. Boolean Literals
Boolean literals represent logical values, either true or false. They are used in conditional
statements and logical operations to control program flow. For example, if (isPassed), the
variable is Passed could be assigned a Boolean literal, such as true. Examples are true and false.
6. Null Literal
There is only one value of Null Literal, that is, null.
4. Operators
An operator in Java is a special symbol that signifies the compiler to perform some specific
mathematical or non-mathematical operations on one or more operands. Java supports 8 types
of operators. Below I have listed down all the operators, along with their examples:
• Arithmetic operators
• Assignment operators
• Relational operators
• Logical operators
• Unary operators
• Ternary operators
• Shift operators
• Bitwise operators
Operator Examples
Arithmetic +,–,/,*,%
Unary ++ , – – , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);
Bitwise &,|,^,~
Shift << , >> , >>>
class Example {
private final String name; // ; ends field
private final int version; // ;
Example(String name, int version) { // () and , used here
[Link] = name; [Link] = version;
}
String getInfo() { return name + " v" + version; } // {} and ;
}
Implementing a Java Program
package RemainingSimplePrograms;
import [Link];
package SimpleNumberPrograms;
import [Link];
package RemainingSimplePrograms;
import [Link];
}
}
6) Java Program to find GCD of Two Numbers
import [Link];
public class GCDofTwo1 {
private static Scanner sc;
public static void main(String[] args)
{
int Num1, Num2, i, GCD = 0;
sc = new Scanner([Link]);
[Link](" Please Enter the First Integer Value : ");
Num1 = [Link]();
[Link](" Please Enter the Second Integer Value : ");
Num2 = [Link]();
for(i = 1; i <= Num1 && i <= Num2; i++)
{
if(Num1 % i == 0 && Num2 % i == 0){
GCD = i;
}
}
[Link]("\n GCD of " + Num1 + " and " + Num2 + " = " + GCD);
}
}
import [Link];
package SimpleNumberPrograms;
import [Link];
public class Calculator {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner([Link]);
double a, b, result;
[Link]("Please Enter any Two Numbers = ");
a = [Link]();
b = [Link]();
[Link]("Enter any Operator from +, - , /, *, % = ");
char operator = [Link]().charAt(0);
switch(operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '%':
result = a % b;
break;
default:
[Link]("You have entered incorrect operator");
return;
}
[Link]("%.2f %c %.2f = %.2f", a, operator, b, result);
}
}
import [Link];
public class SqrtofNumber1 {
private static Scanner sc;
public static void main(String[] args)
{
double number, squareRoot;
sc = new Scanner([Link]);
squareRoot = [Link](number);
[Link]("\n The Square of a Given Number " + number + " = " + squareRoot);
}
}
10) Java Even Odd Program
package SimpleNumberPrograms;
import [Link];
int Number;
sc = new Scanner([Link]);
[Link]("\n Please Enter any integer Value: ");
Number = [Link]();
if (Number % 2 == 0) {
[Link]("\n You have entered EVEN Number");
}
else {
[Link]("\n You have entered ODD Number");
}
}
}
Command Line Arguments
The command-line arguments in Java allow the programmers to pass the arguments during the
execution of a program. The users can pass the arguments during the execution by passing the
command-line arguments inside the main() method.
A command-line argument is nothing but the information that we pass after typing the name of
the Java program during the program execution. These arguments get stored as Strings in a
String array that is passed to the main() function.
The command-line argument in Java are the arguments passed to a program at the time
when you run it. They are stored in the string format and the String array is passed to the args[]
parameter of main() method
If any input value is passed through the command prompt at the time of running of the program
is known as command line argument by default every command line argument will be treated
as string value and those are stored in a string array of main() method.
class CMD
{
public static void main(String k[])
{
[Link]("no. of arguments ="+[Link]);
for(int i=0;i< [Link];i++)
{
[Link](k[i]);
}
}
}
Command line Argument is a way to provide input to Java applications through the command
line when compiling and running the program. These are the inputs provided after the execution
command when running a Java program. They are passed to the main function as strings and
stored in the args parameter.
Command line arguments are processed by the Java Virtual Machine (JVM) before the
main function is invoked. They are bundled together and supplied to the main function as an
array of strings.
Command line arguments are read as strings, and certain characters like #, %, and & may cause
errors when entered as command line arguments.
Working of Command-line Arguments
There are various ways to provide input to our program. One of these ways is to provide input
through the command line, which we also use to compile and run our program. These inputs
are passed to the main function at runtime even before our main() begins to execute. The image
below represents the two ways by which we can write our main function in Java. The
argument String[] args or String… args can be broken down as follows.
In the context of command line arguments in Java:
• String: It represents the data type of the array elements passed to the main function. In
Java, command line arguments are received as an array of strings. The String data type is
used because Java commonly uses strings for input and output operations. Each command
line argument is treated as a string, regardless of its original data type.
• args: The local name given to the array variable holds the command line arguments in
the main function. It serves as a reference to the array, allowing access to and modifying
the values stored in it. Using the args variable, the program can process and manipulate the
command line arguments as needed during runtime.
public static void main(String[] args){
// Statements
}
public static void main(String... args){
// Statements
}
The command line arguments that are given to the program are stored in these main() function
parameters.
Java programs are compiled and run by:
Compile > javac [Link]
Run > java filename
To execute our program, we need to compile the .java file using the above-stated command.
This converts our .java file to a .class file in a machine-readable language. Later, we execute
this file using the run command.
If we provide inputs following this command, the JVM (Java Virtual Machine) wraps all these
inputs together and supplies them to the main function parameter String[] args or String... args.
This process occurs even before our main() is invoked. These inputs are referred to as
command-line arguments. Since these inputs are passed to our application before its execution,
they provide us with a way to configure our application with different parameters. This
capability is particularly useful for efficient testing of our application.
The figure below gives a step-by-step walkthrough of how the command line inputs are read.
As soon as the run command gets executed, the inputs following it are read as strings into the
main function parameter. This is done in such a way that the JVM reads every string
individually when it encounters a character. As it reads a space character, it saves the string and
starts with another string. This restricts the user from entering sentences as a command line
input.