0% found this document useful (0 votes)
2 views53 pages

Introduction To Java Language - Chapter 2

The document provides an introduction to the Java programming language, covering its history, features, and differences from C and C++. Java is a high-level, object-oriented, platform-independent language that allows developers to write code once and run it anywhere. It highlights Java's advantages, such as simplicity, security, and robustness, as well as its disadvantages, including performance issues and memory consumption.

Uploaded by

monkeymon11057
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views53 pages

Introduction To Java Language - Chapter 2

The document provides an introduction to the Java programming language, covering its history, features, and differences from C and C++. Java is a high-level, object-oriented, platform-independent language that allows developers to write code once and run it anywhere. It highlights Java's advantages, such as simplicity, security, and robustness, as well as its disadvantages, including performance issues and memory consumption.

Uploaded by

monkeymon11057
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Chapter – 2

Introduction to Java Language

Introduction to Java Language: Java History, Features, Overview, Difference between C, C+ +


and Java, Java Environment- JDK, JVM, JRE and API, Java Program Structure, Java Tokens,
Implementing a Java Program, Command Line Arguments.

Introduction to Java Language

Java is a class-based object-oriented simple programming language. However, we cannot


consider it to be fully object-oriented as it supports primitive datatypes. It is a general-purpose,
high-level programming language that helps programmers and developers to write code once
and run it anywhere.

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 popular high-level, object-oriented programming language that was originally


developed by Sun Microsystems and released in 1995. Currently, Java is owned by Oracle, and
more than 3 billion devices run Java. Java runs on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX. Today Java is being used to develop numerous
types of software applications, including desktop apps, mobile apps, web apps, games, and
much more.

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.

Annapoorna. M.S Assistant Professor BGS FGC


2

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.

• 1990-A team of Sun Microsystems programmers decided to develop a special software to


manipulate consumer electronic devices. The team headed by James Gosling
• 1991-The team studied various languages present at that time, viz., C and C++ and
announced the new language to be “Oak”.
• 1992-The team at Sun known as Green Project demonstrated the application of their new
language. For example, to control a list of home appliances using a hand device with the
tiny touchscreen.
• 1993-The World Wide Web came to the internet and transformed the text-based Internet
into the graphical rich environment. The Green Project team came up with an idea of
developing Web applets (tiny programs) that could run on all types of computers connected
to the internet.
• 1994-The team developed a web browser called “HotJava” to locate and run applet
programs on the internet. This made it immensely popular amongst the internet users.
• 1995-Oak was renamed as “Java”, due to some legal snags. Java is a name, no acronym.
• 1996-Java programming was established as the leader for internet programming and also
as a general-purpose object-oriented programming language. Sun releases Java
Development Kit 1.0.
• 1997-Sun releases Java Development Kit 1.1 (JDK 1.1)
• 1998-Sun releases the Java 2 with version 1.2 of the Software Development Kit (SD K 1.2)
• 1999-Sun releases Java 2 platform, Standard Edition (J2SE) and Enterprise Edition (J2EE)
• 2000-Release ofJ2SE with SDK 1.3.
• 2002-The release of J2SE with SDK 1.4.
• 2004-The release of J2SE with JDK 5.0 (instead of JDK 1.5), known as J2SE 5.0.
• 2006- The release of Java SE 6.
• 2011- The release of Java SE 7.
• 2014- The release of Java SE 8.
• 2017- The release of Java SE 9.

Annapoorna. M.S Assistant Professor BGS FGC


3

Features of Java Programming 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.

Java (Programming Language)

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.

• There is no need to remove unreferenced objects explicitly as there is an


Automatic Garbage Collection in Java.

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.

Annapoorna. M.S Assistant Professor BGS FGC


4

3) Secure

Security is one of the biggest concern in programming language as these programming


languages are used to develop some of the critical and sensitive applications that needs to be
secured such as banking applications. Java is more secure than C/C++ as does not allow
developers to create pointers, thus it becomes impossible to access a variable from outside if
it’s not been initialized.

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.

4) Object-Oriented Programming language

Object oriented programming is a way of organizing programs as collection of objects, each of


which represents an instance of a class.

4 main concepts of Object Oriented programming are:

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.

Annapoorna. M.S Assistant Professor BGS FGC


5

6) Distributed

Using java programming language we can create distributed applications. RMI(Remote


Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed
applications in java.

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

Java supports multithreading. Multithreading is a Java feature that allows concurrent


execution of two or more parts of a program for maximum utilisation of CPU.

Java (Programming Language)

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++.

Annapoorna. M.S Assistant Professor BGS FGC


6

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.

Annapoorna. M.S Assistant Professor BGS FGC


7

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.

7) High-level programming language

Because Java is a human-readable language, it is considered a high-level programming


language. Moreover, Java is a very simple yet easy language to be maintained through its
syntax, which is similar to C++ but in the most straightforward manner. We have been learning
about Java, and sometimes Java can be used effectively for securing our career.

8) Portable

As discussed earlier, Java is the platform-independent language; it is the most portable


language since it’s introduced. No matter what platform it is, java code can be run on any
platform, thus making it the portable language of all time. With this advantage, we have come
to know that Java is a platform-independent language and a portable language.

Annapoorna. M.S Assistant Professor BGS FGC


8

9) Automatic garbage collection

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++.

Annapoorna. M.S Assistant Professor BGS FGC


9

4. Less machine interactive

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.

5. Unattractive looks and feel of GUI

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.

7. Verbose and complex codes

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.

Application of Java Programming Language

• Mobile Applications

• Desktop GUI Applications

• Web-based Applications

• Enterprise Applications

• Scientific Applications

Annapoorna. M.S Assistant Professor BGS FGC


10

• Gaming Applications

• Big Data technologies

• 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.

2) Desktop GUI Applications

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.

Annapoorna. M.S Assistant Professor BGS FGC


11

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.

7) Big Data technologies

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:

Java EE platform is designed to help developers create large-scale, multi-tiered, scalable,


reliable, and secure network applications. These applications are designed to solve the
problems encountered by large enterprises. The features that make enterprise applications
powerful, like security and reliability, often make these applications complex. The Java EE
platform reduces the complexity of enterprise application development by providing a
development model, API, and runtime environment that allow developers to concentrate on
functionality.

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.

Annapoorna. M.S Assistant Professor BGS FGC


12

10) Cloud-Based Applications:

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.

Difference between C, C+ + and Java

COMPARISON C C++ Java


PARAMETER
Developed by Dennis M. Ritchie created the C Bjarne Stroustrup James Gosling
programming language in 1972. created C++ in 1979 at created Java while
Bell Labs. It was working for Sun
created as a C language Microsystems.
extension. Oracle is now the
owner of it.
Programming model C is a procedural programming Both procedural and Java is an object-
language object-oriented oriented
programming are programming
supported by it. language.
Type of language As it connects the gaps between C++ is a high-level Due to the fact that
machine-level and high-level language. Java code is
languages, C is a middle-level converted into
language. machine language
via a compiler or
interpreter, Java is
a high-level
language.
Compilation and C is not understood; it is just C++ cannot be Java can be
Interpretation compiled. interpreted; it can only interpreted as well
be compiled. as compiled.

Annapoorna. M.S Assistant Professor BGS FGC


13

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.

Annapoorna. M.S Assistant Professor BGS FGC


14

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.

Annapoorna. M.S Assistant Professor BGS FGC


15

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

How Does Java Work?

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.

Annapoorna. M.S Assistant Professor BGS FGC


16

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.

How Java Architecture Works

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.

2. Loading and Verification


The JVM loads the bytecode into memory and performs verification to ensure its integrity
and security. It checks for errors, such as type mismatches and access violations, to prevent
potential runtime issues.

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.

Annapoorna. M.S Assistant Professor BGS FGC


17

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.

Components of Java Architecture

1. Java Development Kit (JDK)


The JDK is a software development kit that includes tools, libraries, and documentation
for developing Java applications. It provides compilers, debuggers, and other utilities
essential for writing, compiling, and running Java code.
It is a software package that is used to create Java applications and applets. It includes the
JRE along with several tools that are required for development. These tools include a
compiler (javac), which is used to convert source code into bytecode, an interpreter/loader
(java) for running programs, an archiver (jar) for bundling files, and a documentation
generator (Javadoc). The JDK provides everything that is needed by a developer for
writing, compiling, and running Java programs.

2. Java Virtual Machine (JVM)


The JVM is a key component of the Java architecture. It is responsible for executing Java
bytecode, which is the compiled form of Java source code. The JVM abstracts the
underlying hardware and operating system, providing a platform-independent runtime
environment.
Java applications work on the feature called “Write Once Run Anywhere” because of the
ability to run the code on any platform. This is done by the JVM. The JVM is a platform
component in Java that consists of an environment for executing programs in Java. The
JVM is responsible for interpreting bytecode into machine code.

Annapoorna. M.S Assistant Professor BGS FGC


18

3. Java Runtime Environment (JRE)


The JRE includes the JVM along with the necessary libraries and resources required to
run Java applications. It provides the runtime environment for executing Java programs,
without the need for the development tools provided by the JDK.
The JRE (Java Runtime Environment) provides the environment that is needed to run
Java programs. It includes everything that is required to run your Java code, such as the
JVM and important libraries. When you run a Java program, the JRE combines your code
with the libraries. After that, it starts the JVM to execute the code. Although JRE is a part
of the JDK, it can be downloaded and used separately if you only need to run Java
programs and not use it for development.

4. Java Class Libraries


Java comes with an extensive set of class libraries, known as the Java Class Library (JCL).
These libraries contain pre-defined classes and methods that developers can leverage to
build applications. The JCL covers a wide range of functionalities, including input/output
operations, networking, data structures, and graphical user interfaces.

5. Java Application Programming Interfaces (APIs)


Java APIs provide a set of classes, interfaces, and protocols that define how programmers
can interact with the Java platform. The APIs offer a standardized way to access various
functionalities, such as database connectivity, web services, XML processing, and more.
They allow developers to leverage existing code and simplify application development.

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).

Annapoorna. M.S Assistant Professor BGS FGC


19

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.

Components of the JDK

1. Java Compiler
The JDK includes the Java compiler (javac), which translates Java source code into
bytecode that can be executed by the JVM.

2. Java Virtual Machine (JVM)


The JVM is a key component of the JDK. It provides an environment for executing Java
applications by interpreting bytecode or just-in-time (JIT) compiling it into machine code.

3. Java Runtime Environment (JRE)


The JDK includes the JRE, which is necessary for running Java applications. It contains
the JVM and other runtime libraries required for executing Java programs.

Annapoorna. M.S Assistant Professor BGS FGC


20

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.

Java Virtual Machine (JVM) Architecture:


The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The feature
states that we can write our code once and use it anywhere or on any operating system. Our
Java program can run any of the platforms only because of the Java Virtual Machine. It is a
Java platform component that gives us an environment to execute java programs. JVM's main
task is to convert byte code into machine code. JVM, first of all, loads the code into memory
and verifies it. After that, it executes the code and provides a runtime environment. Java Virtual
Machine (JVM) has its own architecture, which is given below:

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.

3 Primary Sections of JVM


JVM contains three primary sections:
1. Class Loaders
2. Memory Area
3. Execution Engine

Annapoorna. M.S Assistant Professor BGS FGC


21

There are four phases of JVM


• Load Code
• Verify Code
• Execute Code
• Provide Runtime Environment

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.

3 Phases of Class Loading


1) Loading
Loading phase involves accepting the binary representation (bytecode) of a class or interface
with a specific name, and generating the original class or interface from that. The JVM uses
the [Link]() method for loading the class into memory.

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.

Annapoorna. M.S Assistant Professor BGS FGC


22

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.

3 Class Loaders in Java


The class loaders load the compiled class file. Class loader system contains 3 types of class
loaders.
1. Bootstrap class Loader (BCL)
2. Extension class Loader (ECL)
3. Application class Loader (ACL)
1. Bootstrap class loader
Bootstrap class Loader is responsible for loading all core java API classes. These are all
classes that exist inside [Link] which are available in all JVMs by default. Bootstrap class
Loader loads classes from bootstrap class path. However, it’s implementation is in native
languages(C, C++) but not in java.
Bootstrap Class Path is JDK/JRE/lib

2. Extension class loader


Extension Class Loader is a child class of Bootstrap class loader which is responsible for
loading all classes from the extension class path in java. However, it’s implementation is in
java only. The Extension Class Path is : JDK/JRE/lib/ext

3. Application class loader


Application Class Loader is a child class of Extension class loader which is responsible for
loading classes from application class-path. Its implementation is also in java. The Application
class path is our environment class path.

Annapoorna. M.S Assistant Professor BGS FGC


23

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.

Annapoorna. M.S Assistant Professor BGS FGC


24

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

Annapoorna. M.S Assistant Professor BGS FGC


25

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.

Java Native Interface


Java supports native codes through JNI interface. Native methods are useful for system calls
and other issues related to memory management and performance issues. JNI is a framework
that will be used to interface the native applications. It will enable java application to call and
to be called by native applications.

Native Method Libraries


These native method libraries contain native methods. We will see some uses why we need to
use native libraries. Our system hardware may have some special capabilities. To use those
special qualities for our application we need native methods. Some Native methods provide
extra speed. For memory management also some native methods will be designed. Usually,
native methods will be written in c or c++. That’s all about Java Virtual Machine (JVM).

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

Annapoorna. M.S Assistant Professor BGS FGC


26

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.

Understanding the Java Runtime Environment (JRE)


The Java Runtime Environment (JRE) is a software package provided by Oracle Corporation
that enables the execution of Java applications. It includes the necessary runtime libraries, Java
Virtual Machine (JVM), and other components required to run Java programs. The JRE ensures
platform independence by providing an environment where Java applications can run
consistently across different operating systems and architectures.

Components of the Java Runtime Environment


The JRE consists of several components, including:

1. Java Virtual Machine (JVM)


The JVM is the heart of the JRE. It is responsible for executing Java bytecode, which is the
compiled form of Java programs. The JVM interprets the bytecode and provides a runtime
environment for Java applications to run.

2. Java Class Library


The Java Class Library is a collection of pre-compiled classes and packages that provide a wide
range of functionality to Java applications. It includes standard classes, data structures, utilities,
and APIs for tasks such as file I/O, networking, database access, user interface development,
and more.

3. Java Runtime Environment Configuration Files


The JRE contains configuration files that control various runtime settings, such as memory
allocation, security policies, and class loading behaviour. These files can be customized to suit
specific application requirements.

Annapoorna. M.S Assistant Professor BGS FGC


27

Functionality of the Java Runtime Environment


The JRE provides the following key functionalities:

1) Java Application Execution


The JRE allows Java applications to be executed on any platform that supports the JRE. This
platform independence is one of the key strengths of Java.

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.

Significance of the Java Runtime Environment


The JRE plays a crucial role in Java application execution and enables the widespread adoption
of Java as a programming language. It allows developers to write code once and run it
anywhere, simplifying the development and deployment process. The JRE's robustness,
platform independence, memory management, and security features make it a reliable and
trusted environment for running Java applications.

Why Do We Need JRE in Java?


When you write a Java program and compile it using the Java compiler (javac), the source code
is converted into bytecode. This bytecode is not understood directly by the operating system.
To overcome this limitation, the Java Runtime Environment (JRE) provides the required
runtime environment to load, verify, and execute Java bytecode securely.

Annapoorna. M.S Assistant Professor BGS FGC


28

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.

Annapoorna. M.S Assistant Professor BGS FGC


29

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.

Annapoorna. M.S Assistant Professor BGS FGC


30

A typical structure of a Java program contains the following elements:


o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviours
1. Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To write
the statements in the documentation section, we use comments. The comments may be single-
line, multi-line, and documentation comments.

Annapoorna. M.S Assistant Professor BGS FGC


31

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

Annapoorna. M.S Assistant Professor BGS FGC


32

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. }

6. Class Variables and Constants


In this section, we define variables and constants that are to be used later in the program. In a
Java program, the variables and constants are defined just after the class definition. The
variables and constants store values of the parameters. It is used during the execution of the
program. We can also decide and define the scope of variables by using the modifiers. It defines
the life of the variables. For example:
1. class Student //class definition
2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }

Annapoorna. M.S Assistant Professor BGS FGC


33

7. Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because the
execution of all Java programs starts from the main() method. In other words, it is an entry
point of the class. It must be inside the class. Inside the main method, we create objects and
call the methods. We use the following statement to define the main() method:
1. public static void main(String args[])
2. {
3. }

• A package is a collection of classes, interfaces and sub-packages. A sub package


contains collection of classes, interfaces and sub-sub packages etc. [Link].*; package
is imported by default and this package is known as default package.
• Class is keyword used for developing user defined data type and every java program
must start with a concept of class.
• "ClassName" represent a java valid variable name treated as a name of the class each
and every class name in java is treated as user-defined data type.
• Data member represents either instance or static they will be selected based on the
name of the class.
• User-defined methods represent either instance or static they are meant for performing
the operations either once or each and every time.
• Each and every java program starts execution from the main () method. And hence main
() method is known as program driver.
• Since main () method of java is not returning any value and hence its return type must
be void.

Annapoorna. M.S Assistant Professor BGS FGC


34

• 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.

Main() Method in Java


main() method is starting execution block of a java program or any java program start their
execution from main method. If any class contain main() method known as main class.
Syntax of main() method:
Syntax
public static void main(String args[])
{
.......
.......
}

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.

Annapoorna. M.S Assistant Professor BGS FGC


35

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.

Annapoorna. M.S Assistant Professor BGS FGC


36

Example of override main() method


public class mainclass
{
public static void main(String[] args)
{
[Link]("Execution starts from Main()");
}
void main(int args)
{
[Link]("Override main()");
}
double main(int i, double d)
{
[Link]("Override main()");
return d;
}
}
Output
Execution starts from Main()
Why main Method is Declared Static ?
Because object is not required to call static method if main() is non-static method, then JVM
create object first then call main() method due to that face the problem of extra memory
allocation.
[Link]() in Java
In java language print() and println() are the predefined non-static method of printStream
class used to display value or message either in the same line or line by line respectively.
PrintStream class is having fixed object reference in the System class (existing as a static
properties) so that either print() or println() method can be called with following syntax..

Annapoorna. M.S Assistant Professor BGS FGC


37

Syntax
[Link]("--------------");
[Link]("------------");

/* "out" is Object reference of printStream class


existing in system class as a static property. */
Example
class PrintStream
{
println() //-----------> non-static
{
........
}
print() //-----------> non-static
{
........
........
}
}

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

Annapoorna. M.S Assistant Professor BGS FGC


38

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

Types of Tokens in Java


Let’s discuss the different types of Java tokens with examples:

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.

Annapoorna. M.S Assistant Professor BGS FGC


39

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

Annapoorna. M.S Assistant Professor BGS FGC


40

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

Annapoorna. M.S Assistant Professor BGS FGC


41

boolean isPassed = true; // Boolean literal

[Link]("Number: " + num);


[Link]("Pi: " + pi);
[Link]("Grade: " + grade);
[Link]("Greeting: " + greeting);
[Link]("Passed: " + isPassed);
}
}
Types of Literals in Java
There are five types of Literals on Java:
1. Integer Literals
Integer Literals in Java refer to fixed values used in the code, representing whole numbers.
They can be written in various number systems such as decimal, hexadecimal, octal, and binary.
Decimal Integer Literals are sequences of decimal digits (0-9) and are the most common way
to represent integers. Examples include values like 6, 453, or 34789.
Hexadecimal Integer Literals use a sequence of hexadecimal digits (0-9, A-F) to represent
values. These numbers are prefixed with 0x or 0X to indicate that they are in base 16. Examples
include 0x56ab, 0X6AF2, etc.
Octal Integer Literals are sequences of digits from 0 to 7 and are prefixed with a 0 to denote
base 8. Examples of octal literals include 07122, 04, and 043526.
Binary Integer Literals consist of binary digits (0 and 1) and are prefixed with 0b or 0B to
indicate base 2. Examples include 0b0111001, 0b101, and 0b1000.

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 '#'.

Annapoorna. M.S Assistant Professor BGS FGC


42

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 << , >> , >>>

Annapoorna. M.S Assistant Professor BGS FGC


43

public class OperatorExample {


public static void main(String[] args) {
int a = 10;
int b = 20;

int sum = a + b; // Addition operator


boolean isGreater = a > b; // Comparison operator
boolean isEqual = a == b; // Comparison operator

[Link]("Sum: " + sum); // 30


[Link]("Is a greater than b? " + isGreater); // false
[Link]("Is a equal to b? " + isEqual); // false
}
}
5. Separators (Delimiters)
Separators in Java, also called delimiters, are characters that structure Java code: parentheses
(), braces {}, brackets [], semicolon ;, comma ,, and dot .. They group statements, define blocks,
index arrays, terminate statements, separate parameters, and access members. Proper use of
separators ensures the compiler can parse program boundaries and relationships correctly.
• Period (.): It is used to separate the package name from the sub-packages and the class.
Also, it is used to separate a variable or method from a reference variable.
• Comma (,): It is basically used to separate two values, statements, and parameters.
• Parentheses (): We use it to call functions and parse the parameters.
• Curly braces {}: Whenever we want to start or end a block of code, we use curly braces.
• Assignment operator (=): We use it to assign a variable and a constant.
• Semicolon (;): It separates the two statements of the code.
Example:
public class SeparatorDemo {
public static void main(String[] args) {
int[] nums = {1, 2, 3}; // {} and [] as separators
for (int i = 0; i < [Link]; i++) { // () and ; separate loop parts
[Link](nums[i]); // . accesses member, ; ends statement
}

Annapoorna. M.S Assistant Professor BGS FGC


44

Example ex = new Example("Java", 8); // , separates arguments


[Link]([Link]()); // . member access
}
}

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

1) Java Program to Print Hello World


public class HelloWorld {
public static void main(String[] args){
[Link]("\n Hello World ");
}
}
2) Java Program to Print Hello World Multiple Times
public class Example {

public static void main(String[] args)


{
int i;
for(i = 0; i < 3; i++)
{
[Link]("\n Hello World ");
}
}
}

Annapoorna. M.S Assistant Professor BGS FGC


45

3) Java Program to Get Input from User

package RemainingSimplePrograms;

import [Link];

public class UserInputs1 {

private static Scanner sc;

public static void main(String[] args) {


sc = new Scanner([Link]);

[Link]("Please Enter Integer Value = ");


int x = [Link]();
[Link]("User Entered Integer Value = " + x);

[Link]("\nPlease Enter Double Value = ");


double y = [Link]();
[Link]("User Entered Double Value = " + y);

[Link]("\nPlease Enter Float Value = ");


float z = [Link]();
[Link]("User Entered Float Value = " + z);
}
}
4) Java Program to Print an Integer

package SimpleNumberPrograms;

import [Link];

public class PrintInteger2 {


private static Scanner sc;

public static void main(String[] args) {


int number;
sc = new Scanner([Link]);

[Link]("Please Enter the integer Value = ");


number = [Link]();
[Link]("\nThe integer value you have entered = " + number);
}
}

Annapoorna. M.S Assistant Professor BGS FGC


46

5) Java Program to Read Integer Value from the Standard Input

package RemainingSimplePrograms;

import [Link];

public class ReadInteger1 {

private static Scanner sc;

public static void main(String[] args) {


sc = new Scanner([Link]);

[Link]("Enter Any Integer Value = ");

int num = [Link]();


[Link]();

[Link]("Given Integer Value = " + num);

}
}
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);
}
}

Annapoorna. M.S Assistant Professor BGS FGC


47

7) Java Program to Find largest of Two Numbers

import [Link];

public class LargestofTwo {


private static Scanner sc;
public static void main(String[] args)
{
int number1, number2;
sc = new Scanner([Link]);

[Link](" Please Enter the First Number : ");


number1 = [Link]();

[Link](" Please Enter the Second Number : ");


number2 = [Link]();

if(number1 > number2)


{
[Link]("\n The Largest Number = " + number1);
}
else if (number2 > number1)
{
[Link]("\n The Largest Number = " + number2);
}
else
{
[Link]("\n Both are Equal");
}
}
}

8) Java Program to Create a Simple Calculator

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;

Annapoorna. M.S Assistant Professor BGS FGC


48

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);
}
}

9) Java Program to Find Square root of a Number

import [Link];
public class SqrtofNumber1 {
private static Scanner sc;
public static void main(String[] args)
{
double number, squareRoot;
sc = new Scanner([Link]);

[Link](" Please Enter any Number : ");


number = [Link]();

squareRoot = [Link](number);

[Link]("\n The Square of a Given Number " + number + " = " + squareRoot);
}
}
10) Java Even Odd Program

package SimpleNumberPrograms;

import [Link];

public class EvenorOddUsingIf {


private static Scanner sc;

public static void main(String[] args) {

Annapoorna. M.S Assistant Professor BGS FGC


49

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.

Syntax for Compile and Run CMD programs


Compile By -> Javac [Link]
Run By -> Java Mainclass value1 value2
value3
javac [Link]
java Mainclass value1 value2 value3.........
Command Line Arguments

Annapoorna. M.S Assistant Professor BGS FGC


50

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

Annapoorna. M.S Assistant Professor BGS FGC


51

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.

Annapoorna. M.S Assistant Professor BGS FGC


52

To pass command line arguments in Java, follow these steps:


1. Write your Java program and save it with the .java extension in your local system.
2. Open the command prompt (cmd) and navigate to the directory where you saved your
program.
3. Compile your program using the command javac [Link]. This will convert
the .java file to a .class file.
4. Write the run command java filename and continue the command with all the inputs you
want to give to your code.
5. After writing all your inputs, run the command to execute your program.
The command line arguments given to the program are bundled and supplied to the main
function parameter even before the invoking of the main function. These inputs are stored in a
string array since Java deals with strings when performing I/O [Link] inputs are
distinguished by the blank space ' ' between them. The command line reads one character at a
time and stores it. When it encounters a space, it saves the already collected text as an input
value and repeats the process until all characters are read.
Simple Example of Command-line Argument in Java
public class cmdArgs {

public static void main(String[] args) {


[Link](
"The number of command line inputs entered are " + [Link]
);
for (int i = 0; i < [Link]; i++) [Link](
"input " + i + " is " + args[i]
);
}
}
Output: Here, after our execution command the following text is given:
$ javac [Link]
$ java cmdArgs apple banana mango graes orange
The number of command line inputs entered is 5
input 1 is apple
input 2 is banana
input 3 is mango
input 4 is grapes
input 5 is orange
$

Annapoorna. M.S Assistant Professor BGS FGC


53

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.

Annapoorna. M.S Assistant Professor BGS FGC

You might also like