0% found this document useful (0 votes)
6 views32 pages

JAVA

Java is a programming language developed by Sun Microsystems, first released in 1995, with the latest version being Java SE 8. It is known for its platform independence, allowing code to be written once and run anywhere, and includes various configurations for different applications such as J2EE and J2ME. The document also covers essential tools, basic syntax, JVM architecture, and features of Java, emphasizing its object-oriented nature and robust performance.

Uploaded by

Vsarchana Qa
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)
6 views32 pages

JAVA

Java is a programming language developed by Sun Microsystems, first released in 1995, with the latest version being Java SE 8. It is known for its platform independence, allowing code to be written once and run anywhere, and includes various configurations for different applications such as J2EE and J2ME. The document also covers essential tools, basic syntax, JVM architecture, and features of Java, emphasizing its object-oriented nature and robust performance.

Uploaded by

Vsarchana Qa
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
You are on page 1/ 32

JAVA :

Java programming language was originally developed by Sun


Microsystems which was initiated by James Gosling and released in
1995 as core component of Sun Microsystems' Java platform (Java 1.0
[J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple
configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere

JAVA essentials :
Tools You Will Need
For performing the examples discussed in this tutorial, you will need a
Pentium 200-MHz computer with a minimum of 64 MB of RAM (128
MB of RAM recommended).
You will also need the following softwares:
Linux 7.1 or Windows xp/7/8 operating system
Java JDK 8
Microsoft Notepad or any other text editor

a – Basic Syntax

Local Environment Setup


If you are still willing to set up your environment for Java programming
language, then this section guides you on how to download and set up
Java on your machine. Following are the steps to set up the
environment.
Java SE is freely available from the link Download Java. You can
download a version based on your operating system.
Follow the instructions to download Java and run the .exe to install Java
on your machine. Once you installed Java on your machine, you will
need to set environment variables to point to correct installation
directories:

Setting Up the Path for Windows


Assuming you have installed Java in c:\Program Files\java\jdk directory:
Right-click on 'My Computer' and select 'Properties'.

Click the 'Environment variables' button under the 'Advanced' tab.

Now, alter the 'Path' variable so that it also contains the path to the
Java executable. Example, if the path is currently set to
'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD


Environment variable PATH should be set to point to where the Java
binaries have been installed. Refer to your shell documentation, if you
have trouble doing this.
Example, if you use bash as your shell, then you would add the
following line to the end of your '.bashrc: export
PATH=/path/to/java:$PATH'

Popular Java Editors


To write your Java programs, you will need a text editor. There are even
more sophisticated IDEs available in the market. But for now, you can
consider one of the following:
Notepad: On Windows machine, you can use any simple text editor
like Notepad (Recommended for this tutorial), TextPad.

Netbeans: A Java IDE that is open-source and free, which can be


downloaded from http://www.netbeans.org/index.html.

Eclipse: A Java IDE developed by the eclipse open-source community


and can be downloaded from http://www.eclipse.org/.

JAVA – Basic syntax


When we consider a Java program, it can be defined as a collection of
objects that communicate via invoking each other's methods. Let us
now briefly look into what do class, object, methods, and instance
variables mean.
Object - Objects have states and behaviors. Example: A dog has states
- color, name, breed as well as behavior such as wagging their tail,
barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/blueprint that describes


the behavior/state that the object of its type supports.

Methods - A method is basically a behavior. A class can contain many


methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance
variables. An object's state is created by the values assigned to these
instance variables.

Java – Basic Syntax

Basic Syntax :

About Java programs, it is very important to keep in mind the following


points.

Case Sensitivity - Java is case sensitive, which means identifier


Helloand hello would have different meaning in Java.

Class Names - For all class names the first letter should be in Upper
Case. If several words are used to form a name of the class, each inner
word's first letter should be in Upper Case.

Example: class MyFirstJavaClass


Method Names - All method names should start with a Lower Case
letter. If several words are used to form the name of the method, then
each inner word's first letter should be in Upper Case.

Example: public void myMethodName()


Program File Name - Name of the program file should exactly match
the class name. When saving the file, you should save it using the class
name (Remember Java is case sensitive) and append '.java' to the end
of the name (if the file name and the class name do not match, your
program will not compile). Example: Assume 'MyFirstJavaProgram' is
the class name. Then the file should be saved as
'MyFirstJavaProgram.java'

public static void main(String args[]) - Java program processing starts


from the main() method which is a mandatory part of every Java
program.
Java Identifiers
All Java components require names. Names used for classes, variables,
and methods are called identifiers.
In Java, there are several points to remember about identifiers. They
are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency
character ($) or an underscore (_).

After the first character, identifiers can have any combination of


characters.

A key word cannot be used as an identifier.

Most importantly, identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value.

Examples of illegal identifiers: 123abc, -salary.

Java Variables

Following are the types of variables in Java:


Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)

Java Arrays
Arrays are objects that store multiple variables of the same type.
However, an array itself is an object on the heap. We will look into how
to declare, construct, and initialize in the upcoming chapters.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by
using modifiers. There are two categories of modifiers:
Access Modifiers: default, public , protected, private

Non-access Modifiers: final, abstract, strictfp

Java Enums
Enums were introduced in Java 5.0. Enums restrict a variable to have
one of only a few predefined values. The values in this enumerated list
are called enums.
With the use of enums it is possible to reduce the number of bugs in
your code.
For example, if we consider an application for a fresh juice shop, it
would be possible to restrict the glass size to small, medium, and large.
This would make sure that it would not allow anyone to order any size
other than small, medium, or large.
Example
class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}
The above example will produce the following result:
Size: MEDIUM
Note: Enums can be declared as their own or inside a class. Methods,
variables, constructors can be defined inside enums as well.

Java Keywords

JVM (Java Virtual Machine) Architecture


1. Java Virtual Machine
2. Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification


that provides runtime environment in which java bytecode can be
executed.

JVMs are available for many hardware and software platforms (i.e. JVM
is platform dependent).

What is JVM

It is:
1. A specification where working of Java Virtual Machine is
specified. But implementation provider is independent to choose
the algorithm. Its implementation has been provided by Oracle
and other companies.
2. An implementation Its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is
created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture

Let's understand the internal architecture of JVM. It contains


classloader, memory area, execution engine etc.
1) Classloader

Classloader is a subsystem of JVM which is used to load class files.


Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the


super class of Extension classloader. It loads the rt.jar file which
contains all class files of Java Standard Edition like java.lang
package classes, java.net package classes, java.util package
classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap
and parent classloader of System classloader. It loades the jar files
located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the classfiles from classpath. By
default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null b
ecause it is an
11. //in-
built class which is found in rt.jar, so it is loaded by Bootstrap classloade
r
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Test it Now

Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to


create your own classloader, you need to extend the ClassLoader class.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime


constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return.

Each thread has a private JVM stack, created at the same time as
thread.

A new frame is created each time a method is invoked. A frame is


destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual


machine instruction currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance.
JIT compiles parts of the byte code that have similar functionality
at the same time, and hence reduces the amount of time needed
for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface


to communicate with another application written in another language
like C, C++, Assembly etc. Java uses JNI framework to send output to
the Console or interact with OS libraries.

Features of JAVA :
Object Oriented: In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
Platform Independent: Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-
key encryption.
Architecture-neutral: Java compiler generates an architecture-neutral
object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
Portable: Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler
in Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
Robust: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking.
Multithreaded: With Java's multithreaded feature it is possible to
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is
more rapid and analytical since the linking is an incremental and light-
weight process.
High Performance: With the use of Just-In-Time compilers, Java
enables high performance.

Distributed: Java is designed for the distributed environment of the


internet.

Dynamic: Java is considered to be more dynamic than C or C++ since


it is designed to adapt to an evolving environment. Java programs can
carry extensive amount of run-time information that can be used to
verify and resolve accesses to objects on run-time
Creation and execution of programs :
Compilation and Execution of a Java Program
Read
Discuss
Practice

Java, being a platform-independent programming language, doesn’t
work on the one-step compilation. Instead, it involves a two-step
execution, first through an OS-independent compiler; and second, in a
virtual machine (JVM) which is custom-built for every operating
system.
The two principal stages are explained below:
Principle 1: Compilation
First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine-independent encoding, known
as Bytecode. The content of each class contained in the source file is
stored in a separate ‘.class’ file. While converting the source code into
the bytecode, the compiler follows the following steps:
Step 1: Parse: Reads a set of *.java source files and maps the resulting
token sequence into AST (Abstract Syntax Tree)-Nodes.
Step 2: Enter: Enters symbols for the definitions into the symbol table.
Step 3: Process annotations: If Requested, processes annotations
found in the specified compilation units.
Step 4: Attribute: Attributes the Syntax trees. This step includes name
resolution, type checking and constant folding.
Step 5: Flow: Performs dataflow analysis on the trees from the previous
step. This includes checks for assignments and reachability.
Step 6: Desugar: Rewrites the AST and translates away some syntactic
sugar.
Step 7: Generate: Generates ‘.Class’ files.
https://www.youtube.com/watch?v=0f-Sx81bIWQ
Principle 2: Execution
The class files generated by the compiler are independent of the
machine or the OS, which allows them to be run on any system. To run,
the main class file (the class that contains the method main) is passed
to the JVM and then goes through three main stages before the final
machine code is executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Let us discuss all 3 stages.
Stage 1: Class Loader
The main class is loaded into the memory bypassing its ‘.class’ file to
the JVM, through invoking the latter. All the other classes referenced in
the program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies
that are referenced by a string name. The method definition is provided
below illustration as follows:
Illustration:
// loadClass function prototype

Class r = loadClass(String className, boolean resolveIt);

// className: name of the class to be loaded


// resolveIt: flag to decide whether any referenced class should be
loaded or not.
There are two types of class loaders
• primordial
• non-primordial
The primordial class loader is embedded into all the JVMs and is the
default class loader. A non-primordial class loader is a user-defined
class loader, which can be coded in order to customize the class-loading
process. Non-primordial class loader, if defined, is preferred over the
default one, to load classes.
Stage 2: Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be
inspected by the bytecode verifier, whose job is to check that the
instructions don’t perform damaging actions. The following are some of
the checks carried out:
• Variables are initialized before they are used.
• Method calls match the types of object references.
• Rules for accessing private data and methods are not violated.
• Local variable accesses fall within the runtime stack.
• The run-time stack does not overflow.
• If any of the above checks fail, the verifier doesn’t allow the class to
be loaded.
Stage 3: Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to
convert the loaded bytecode into machine code. When using a JIT
compiler, the hardware can execute the native code, as opposed to
having the JVM interpret the same sequence of bytecode repeatedly
and incurring the penalty of a relatively lengthy translation process.
This can lead to performance gains in the execution speed unless
methods are executed less frequently.
The process can be well-illustrated by the following diagram given
above as follows from which we landed up to the conclusion.
Conclusion: Due to the two-step execution process described above, a
java program is independent of the target operating system. However,
because of the same, the execution time is way more than a similar
program written in a compiled platform-dependent program.
Implementation:
Consider simple printing program is written somewhere on the local
directory in a machine.
• Java
// Java Program to Illustrate
Compilation and Execution

// Stages

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Print command

System.out.print("Welcome to
Geeks");

Output
Welcome to Geeks
Let us understand the real compilation and execution process.
Step 1: Let us create a file writing simple printing code in a text file and
saving it with “.java” extension.
Step 2: Open the terminal(here we are using macOS)and go to the
Desktop directory using the below command as follows.
cd /Users/mayanksolanki/GFG.java
Step 3: Let us try to compile our program with the below command
javac GFG.java
Step 4: Lastly run it with the below command as follows:
java GFG
Note: GFG.class file is created after the third step which means that
now our entire code in the java programming language is secure
encrypted as it contains only binary. In step 4 we are running that file.
Refer to the below media for ease of understanding.
Data Types in Java
Data types specify the different sizes and values that can be stored in
the variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean,


char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.

Java is a statically-typed programming language. It means,


all variables must be declared before its use. That is why we need to
declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false
conditions.

The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.

Example:

1. Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit
signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). Its minimum value is -128 and maximum value is 127.
Its default value is 0.

The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int" data
type.

Example:

1. byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive). Its minimum
value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
Example:

1. short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is
used when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of
double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values,
such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating


point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also should
never be used for precise values, such as currency. Its default value is
0.0d.

Example:

1. double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range
lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char
data type is used to store characters.

Example:

1. char letterA = 'A'


Structure of Java Program:

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.
Let's see which elements are included in the structure of a Java
program. 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 Behaviors

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.

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*/

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 com.javatpoint; //where com is the root directory and javatpoi
nt is the subdirectory

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 java.util.Scanner; //it imports the Scanner class only


2. import java.util.*; //it imports all the class of the java.util package

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

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

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

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

For example:

1. public class Student //class definition


2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }

You can read more about the Java main() method here.

Methods and behavior

In this section, we define the functionality of the program by using


the methods. The methods are the set of instructions that we want to
perform. These instructions execute at runtime and perform the
specified task. For example:

1. public class Demo //class definition


2. {
3. public static void main(String args[])
4. {
5. void display()
6. {
7. System.out.println("Welcome to javatpoint");
8. }
9. //statements
10. }
11. }

When we follow and use the above elements in a Java program, the
program looks like the following.

CheckPalindromeNumber.java

1. /*Program name: Palindrome*/


2. //Author's name: Mathew
3. /*Palindrome is number or string that will remains the same
4. When we write that in reverse order. Some example of
5. palindrome is 393, 010, madam, etc.*/
6. //imports the Scanner class of the java.util package
7. import java.util.Scanner;
8. //class definition
9. public class CheckPalindromeNumber
10. {
11. //main method
12. public static void main(String args[])
13. {
14. //variables to be used in program
15. int r, s=0, temp;
16. int x; //It is the number variable to be checked for palindrome
17. Scanner sc=new Scanner(System.in);
18. System.out.println("Enter the number to check: ");
19. //reading a number from the user
20. x=sc.nextInt();
21. //logic to check if the number id palindrome or not
22. temp=x;
23. while(x>0)
24. {
25. r=x%10; //finds remainder
26. s=(s*10)+r;
27. x=x/10;
28. }
29. if(temp==s)
30. System.out.println("The given number is palindrome.");
31. else
32. System.out.println("The given number is not palindrome.");
33. }
34. }

Output:

You might also like