Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Introduction To Java

Uploaded by

spyderalpha7295
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Introduction To Java

Uploaded by

spyderalpha7295
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Introduction to Java

Java is a class-based, object-oriented programming language that


is designed to have as few implementation dependencies as
possible. It is intended to let application developers write
once, and run anywhere (WORA), meaning that compiled Java code
can run on all platforms that support Java without the need for
recompilation. Java was first released in 1995 and is widely
used for developing applications for desktop, web, and mobile
devices. Java is known for its simplicity, robustness, and
security features, making it a popular choice for enterprise-
level applications.
JAVA was developed by James Gosling at Sun Microsystems Inc in
the year 1995 and later acquired by Oracle Corporation. It is
a simple programming language. Java makes writing, compiling,
and debugging programming easy. It helps to create reusable code
and modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few
implementation dependencies as possible. A general-purpose
programming language made for developers to write once run
anywhere that is compiled Java code can run on all platforms
that support Java. Java applications are compiled to byte code
that can run on any Java Virtual Machine. The syntax of Java is
similar to c/c++.

Primary/Main Features of Java

1. Platform Independent: Compiler converts source code to


bytecode and then the JVM executes the bytecode generated by
the compiler. This bytecode can run on any platform be it
Windows, Linux, or macOS which means if we compile a program on
Windows, then we can run it on Linux and vice versa. Each
operating system has a different JVM, but the output produced
by all the OS is the same after the execution of the bytecode.
That is why we call java a platform-independent language.
2. Object-Oriented Programming Language: Organizing the program
in the terms of a collection of objects is a way of object-
oriented programming, each of which represents an instance of
the class.
The four main concepts of Object-Oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
3. Simple: Java is one of the simple languages as it does not
have complex features like pointers, operator overloading,
multiple inheritances, and Explicit memory allocation.
4. Robust: Java language is robust which means reliable. It is
developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy
to detect by another programming language. The main features of
java that make it robust are garbage collection, Exception
Handling, and memory allocation.
5. Secure: In java, we don’t have pointers, so we cannot access
out-of-bound arrays i.e it shows ArrayIndexOutOfBound
Exception if we try to do so. That’s why several security flaws
like stack corruption or buffer overflow are impossible to
exploit in Java. Also, java programs run in an environment that
is independent of the os(operating system) environment which
makes java programs more secure.
6. Distributed: We can create distributed applications using
the java programming language. Remote Method Invocation and
Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily
distributed on one or more systems that are connected to each
other through an internet connection.
7. Multithreading: Java supports multithreading. It is a Java
feature that allows concurrent execution of two or more parts
of a program for maximum utilization of the CPU.
8. Portable: As we know, java code written on one machine can
be run on another machine. The platform-independent feature of
java in which its platform-independent bytecode can be taken to
any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way
that it reduces overhead during the runtime and at some times
java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those
methods that are called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented
gives us the flexibility to add classes, new methods to
existing classes, and even create new classes through sub-
classes. Java even supports functions written in other languages
such as C, C++ which are referred to as native methods.
11. Sandbox Execution: Java programs run in a separate space
that allows user to execute their applications without affecting
the underlying system with help of a bytecode verifier. Bytecode
verifier also provides additional security as its role is to
check the code for any violation of access.
12. Write Once Run Anywhere: As discussed above java application
generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It
provides ease t architecture-neutral ease as bytecode is not
dependent on any machine architecture. It is the primary reason
java is used in the enterprising IT industry globally worldwide.
13. Power of compilation and interpretation: Most languages are
designed with the purpose of either they are compiled language
or they are interpreted language. But java integrates arising
enormous power as Java compiler compiles the source code to
bytecode and JVM executes this bytecode to machine OS-dependent
executable code.

Applications of Java
Top 10 Applications of Java in Real World
Java is the Queen of programming languages. It beholds the pride
of the most
its 25th anniversary on 23rd May 2020 and is continuously
updating to cope with the latest technological advancements. It
is surprising to note that at present around three billion
devices use Java for development. Java has an amazing design
that incorporates the flexibility to run on any machine. It has
been a major component in the development of a plethora of
applications and the advancement of major technologies.
Java has become the most robust programming language because of
its amazing features. Some of its features are platform
independence, high performance, Object orientation, support for
automatic garbage management, and many more. In this blog, we
will discuss the Top 10 Applications of Java in the real world
in a detailed manner.
• Desktop GUI Applications
• Mobile Applications
• Artificial intelligence
• Web applications
• Big Data technology
• Gaming applications
• Business applications
• Embedded systems
• Cloud applications
• Scientific applications
So let’s get started.
1. Desktop GUI Applications

Desktop applications can be flawlessly designed using Java. APIs


like Swing, Abstract Windowing Toolkit (AWT), and JavaFX provide
a modern way to develop GUI applications. The use of java in
desktop applications offers some fantastic benefits like ease of
learning, visual feedback, simultaneous display of multiple
instances, and many more.

2. Mobile Applications

Java is a cross-platform framework that is used to build


applications that run across smartphones and other small-screen
devices. As per a survey it is observed that Java is the second
most widely used language for mobile application development.
Mobile applications that are created using Java include some
popular ones like Netflix, Twitter, Spotify, and many more.
The reason why Java is used to build mobile apps are:
• Helps to write simple code
• Cross-platform functioning
• High compatibility with Kotlin
• High security

3. Artificial Intelligence

Java is one of the best languages for AI projects. Its


infrastructure is well embedded with intelligent software to
enhance AI programming. It has amazing features like better
interaction with users, ease of debugging, easy-to-code
features, standard widget tools, and a lot more. The use of Java
just brings perfection to the Artificial Intelligence process.

4. Web Applications

Java is just perfect for developing web applications because of


its ability to interact with a large number of systems. It allows
us to create dynamic web applications that interact with
interfaces. The presence of JSP, web servers, spring, and
Hibernate provides feasibility in the web development process.
There are several advantages of using Java for web development:
• Presence of a wide range of APIs
• Excellent IDEs and tools
• Reusability of code
• Enhanced security features
and many more.

5. Big Data Technology

It is a software utility designed to analyze and extract


information from complex data structures. It is widely used in
other technologies like deep learning, Machine learning, and
Artificial learning. Java is a viewpoint of Big data. Java is
commonly used in ETL applications like Apatar, Apache Camel, and
Apache Kafka which are used to extract complex information.
Further use of Java provides distinguished features like
automatic garbage selection and stack provision system. All these
provide it an edge over other technology and hence Java is widely
used in Big Data Technology.

6. Gaming Applications

Java has proved to be the most desirable option for game


development because of the presence of a wide variety of open-
source frameworks. Popular games like Mission Impossible III,
Minecraft, and Asphalt 6 are developed in Java. It supports
Dalvik Virtual Machine and jMonkeyEngine which provides an ace
in building 2 Dimensional and 3 Dimensional android games.

7. Business Applications

Java helps us to develop robust applications for business


requirements. It can be used to develop from small-scale
applications to big enterprise solutions. The language is
constantly growing and updating to fulfill the latest business
demands. It offers enhanced features like:
• Flexible integration
• Powerful performance in the management of big
enterprise workload
• Cross-platform compatibility
And many more. All these amazing features make Java the most
suited solution for enterprise development.

8. Embedded Systems

It refers to the combination of small units that combine to


perform the collective function for larger systems. Java has
proved to be the best solution to address increasing Software
complexity. Today a large number of developers use Java in
embedded systems. Java has a wide variety of libraries to
simplify developers’ lives. These can be simply reused by
embedded applications which enhances productivity to great
extent. Further, the presence of Object-Oriented Programming
makes it easier to develop embedded systems even with minimal
experience. All these features of Java make it easier for
developers to manage complex systems.

9. Cloud Applications

Cloud Computing refers to the on-demand access to computer


resources without direct management by the user. Java has carved
its way into cloud applications. It provides a solution for IT
infrastructure at an affordable cost. Further, it serves as a
platform for creating cloud servers and applications.

10. Scientific Applications

Java has enhanced security features which makes it the best


option for the development of scientific applications. It has
served as a powerful tool in coding complex mathematical
operations. The programs are designed in a highly secure and
efficient manner. Some of the most widely used applications like
MATLAB use Java as a component of the core system.
Java is present in every field of software development. There
are even more applications of Java such as distributed
applications, enterprise applications, IoT technology, and many
more that are still to be explored. There are a lot of programming
languages but Java continues to be the first preference for the
majority of developers.

History of Java


Java is an Object-Oriented programming language developed
by James Gosling in the early 1990s. The team initiated this
project to develop a language for digital devices such as set-
top boxes, television, etc. Originally C++ was considered to be
used in the project but the idea was rejected for several
reasons(For instance C++ required more memory). Gosling
endeavoured to alter and expand C++ however before long
surrendered that for making another stage called Green. James
Gosling and his team called their project “Greentalk” and its
file extension was .gt and later became to known as “OAK”.
Why “Oak”?
The name Oak was used by Gosling after an oak tree that
remained outside his office. Also, Oak is an image of
solidarity and picked as a national tree of numerous nations
like the U.S.A., France, Germany, Romania, etc. But they had to
later rename it as “JAVA” as it was already a trademark by Oak
Technologies. “JAVA” Gosling and his team did a brainstorm
session and after the session, they came up with several names
such as JAVA, DNA, SILK, RUBY, etc. Java name was decided after
much discussion since it was so unique. The name Java
originates from a sort of espresso bean, Java. Gosling came up
with this name while having a coffee near his office. Java was
created on the principles like Robust, Portable, Platform
Independent, High Performance, Multithread, etc. and was called
one of the Ten Best Products of 1995 by the TIME MAGAZINE.
Currently, Java is used in internet programming, mobile
devices, games, e-business solutions, etc.
The Java language has experienced a few changes since JDK
1.0 just as various augmentations of classes and packages to
the standard library. In Addition to the language changes,
considerably more sensational changes have been made to the
Java Class Library throughout the years, which has developed
from a couple of hundred classes in JDK 1.0 to more than three
thousand in J2SE 5.History of various Java versions:
Version Release Date Major changes

JDK Beta 1995

The Very first version was


released on January 23, 1996.
JDK 1.0 January 1996
The principal stable variant,
JDK 1.0.2, is called Java 1.

Was released on February 19,


1997. There were many
JDK 1.1 February 1997 additions in JDK 1.1 as
compared to version 1.0 such
as
Version Release Date Major changes

• A broad retooling of
the AWT occasion show
• Inner classes added to
the language
• JavaBeans
• JDBC
• RMI

“Play area” was the codename


which was given to this form
and was released on 8th
December 1998. Its real
expansion included: strictfp
keyword
• the Swing graphical
API was coordinated
into the centre
J2SE 1.2 December 1998 classes
• Sun’s JVM was
outfitted with a JIT
compiler out of the
blue
• Java module
• Java IDL, an IDL usage
for CORBA
interoperability
• Collections system

Codename- “KESTREL” Release


Date- 8th May 2000 Additions:
• HotSpot JVM included
• Java Naming and
J2SE 1.3 May 2000 Directory Interface
• JPDA
• JavaSound
• Synthetic proxy
classes

Codename- “Merlin” Release


J2SE 1.4 February 2002
Date- 6th February 2002
Version Release Date Major changes

Additions: Library
improvements
• Regular expressions
modelled after Perl
regular expressions
• The image I/O API for
reading and writing
images in formats like
JPEG and PNG
• Integrated XML parser
and XSLT processor
(JAXP) (specified in
JSR 5 and JSR 63)
• Preferences API
(java.util.prefs)
Public Support and security
updates for this version
ended in October 2008.

Codename- “Tiger” Release


Date- “30th September 2004”
Originally numbered as 1.5
which is still used as its
internal version. Added
J2SE 5.0 September 2004 several new language features
such as:
• for-each loop
• Generics
• Autoboxing
• Var-args

Codename- “Mustang” Released


Date- 11th December 2006
Packaged with a database
supervisor and encourages the
utilization of scripting
JAVA SE 6 December 2006
languages with the JVM.
Replaced the name J2SE with
java SE and dropped the .0
from the version number.
Additions:
Version Release Date Major changes

• Upgrade of JAXB to
version 2.0: Including
integration of a StAX
parser.
• Support for pluggable
annotations (JSR 269).
• JDBC 4.0 support (JSR
221)

Codename- “Dolphin” Release


Date- 7th July 2011 Added
small language changes
including strings in the
switch. The JVM was extended
with support for dynamic
JAVA SE 7 July 2011 languages. Additions:
• Compressed 64-bit
pointers.
• Binary Integer
Literals.
• Upstream updates to
XML and Unicode.

Released Date- 18th March


2014 Language level support
for lambda expressions and
JAVA SE 8 March 2014
default methods and a new
date and time API inspired by
Joda Time.

Release Date: 21st September


2017 Project Jigsaw:
designing and implementing a
JAVA SE 9 September 2017 standard, a module system for
the Java SE platform, and to
apply that system to the
platform itself and the JDK.

Released Date- 20th March


JAVA SE 10 March 2018
Addition:
Version Release Date Major changes

• Additional Unicode
language-tag
extensions
• Root certificates
• Thread-local
handshakes
• Heap allocation on
alternative memory
devices
• Remove the native-
header generation tool
– javah.
• Consolidate the JDK
forest into a single
repository.

Released Date- 25th


September, 2018 Additions-
• Dynamic class-file
constants
• Epsilon: a no-op
garbage collector
• The local-variable
JAVA SE 11 September 2018 syntax for lambda
parameters
• Low-overhead heap
profiling
• HTTP client (standard)
• Transport Layer
Security (TLS) 1.3
• Flight recorder

Released Date- 19th March


2019 Additions-
• Shenandoah: A Low-
Pause-Time Garbage
JAVA SE 12 March 2019 Collector
(Experimental)
• Microbenchmark Suite
• Switch Expressions
(Preview)
Version Release Date Major changes

• JVM Constants API


• One AArch64 Port, Not
Two
• Default CDS Archives

Released Date – 17th


September 2019
Additions-
• Text Blocks (Multiline
JAVA SE 13 September 2019
strings).
• Switch Expressions.
• Enhanced Thread-local
handshakes.

Released Date – 17th March


2020
Additions-
• Records (new class
type for data
JAVA SE 14 March 2020
modeling).
• Pattern Matching for
instanceof.
• Helpful
NullPointerExceptions.

Released Date – 15th


September 2020
Additions-
• Sealed Classes.
JAVA SE 15 September 2020
• Hidden Classes.
• Foreign Function and
Memory API
(Incubator).

Released Date – 16th March


2021
JAVA SE 16 March 2021 Additions-
• Records (preview
feature).
Version Release Date Major changes

• Pattern Matching for


switch (preview
feature).
• Unix Domain Socket
Channel (Incubator).

Released Date – 14th


September 2021
Additions-
• Sealed Classes
(finalized).
• Pattern Matching for
JAVA SE 17 September 2021 instanceof
(finalized).
• Strong encapsulation
of JDK internals by
default.
• New macOS rendering
pipeline.

Comments in Java


In a program, comments are like indents one makes, they are used
so that it is easier for someone who isn’t familiar with the
language to be able to understand the code. It will also make
the job easier for you, as a coder, to find errors in the code
since you will be easily able to find the location of the bug.
Comments are ignored by the compiler while compiling a code,
which makes the job more complex in the long run when they have
to go through so much code to find one line.

In Java there are three types of comments:

1. Single-line comments.
2. Multi-line comments.
3. Documentation comments.
A. Single-line comments
A beginner-level programmer uses mostly single-line comments for
describing the code functionality. It’s the easiest typed
comments.
Syntax:
//Comments here( Text in this line only is considered as
comment )
Example:

// Java program to show single line comments

class Scomment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}

Output:
Single line comment above
B. Multi-line Comments:
To describe a full method in a code or a complex snippet single
line comments can be tedious to write since we have to give
‘//’ at every line. So to overcome this multi-line comments can
be used.
Syntax:
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Example:
• Java
//Java program to show multi line comments
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}

Output:
Multi line comments below
We can also accomplish single line comments by using the above
syntax as shown below:
/*Comment line 1*/
C. Documentation Comments:
This type of comment is used generally when writing code for a
project/software package, since it helps to generate a
documentation page for reference, which can be used for getting
information about methods present, its parameters, etc. For
example, http://docs.oracle.com/javase/7/docs/api/java/util/Sca
nner.html is an auto-generated documentation page that is
generated by using documentation comments and a javadoc tool
for processing the comments.
Syntax:
/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/

/*package whatever //do not write package name here */


import java.io.*;

class GFG {
public static void main (String[] args) {
/**
comment line 1
comment line 2
*/
}
}

Literals in java
Literal: Any constant value which can be assigned to the
variable is called literal/constant.
In simple words, Literals in Java is a synthetic representation
of boolean, numeric, character, or string data. It is a medium
of expressing particular values in the program, such as an
integer variable named ‘’/count is assigned an integer value in
the following statement.
// Here 100 is a constant/literal.
int x = 100;

Integral literals

For Integral data types (byte, short, int, long), we can


specify literals in 4 ways:-
Decimal literals (Base 10): In this form, the allowed digits
are 0-9.
int x = 101;
Octal literals (Base 8): In this form, the allowed digits are
0-7.
// The octal number should be prefix with 0.
int x = 0146;
Hexa-decimal literals (Base 16): In this form, the allowed
digits are 0-9, and characters are a-f. We can use both
uppercase and lowercase characters as we know that java is a
case-sensitive programming language, but here java is not case-
sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
Binary literals: From 1.7 onward, we can specify literal value
even in binary form also, allowed digits are 0 and 1. Literals
value should be prefixed with 0b or 0B.
int x = 0b1111;
Example:
• Java

// Java program to illustrate the // application of char


literals public class Test { public static void main(String[]
args) { // single character literal within single quote char ch
= ‘a’; // It is an Integer literal with octal form char b =
0789; // Unicode representation char c = ‘\u0061’;
System.out.println(ch); System.out.println(b);
System.out.println(c); // Escape character literal
System.out.println(“\” is a symbol”); } }

Output
101
64
64206
15
Note : By default, every literal is of int type, we can specify
explicitly as long type by suffixed with l or L. There is no
way to specify byte and short literals explicitly but
indirectly we can specify. Whenever we are assigning integral
literal to the byte variable and if the value is within the
range of byte then the compiler treats it automatically as byte
literals.

Floating-Point literal

For Floating-point data types, we can specify literals in only


decimal form, and we cant specify in octal and Hexadecimal
forms.
Decimal literals(Base 10): In this form, the allowed digits are
0-9.
double d = 123.456;

• Java

// Java program to illustrate the // application of String


literals public class Test { public static void main(String[]
args) { String s = “Hello”; // If we assign without “” then it
treats // as a variable and causes compiler error String s1 =
Hello; System.out.println(s); System.out.println(s1); } }

Output
101.230
123.222
Error: malformed floating point literal
Note: By default, every floating-point literal is of double
type, and hence we cant assign directly to the float variable.
But we can specify floating-point literal as float type by
suffixed with f or F. We can specify explicitly floating-point
literal as double type by suffixed with d or D. Of course this
convention is not required.

Char literals

For char data types, we can specify literals in 4 ways:


Single quote: We can specify literal to a char data type as a
single character within the single quote.
char ch = 'a';
Char literal as Integral literal: we can specify char literal
as integral literal, which represents the Unicode value of the
character, and that integral literal can be specified either in
Decimal, Octal, and Hexadecimal forms. But the allowed range is
0 to 65535.
char ch = 062;
Unicode Representation: We can specify char literals in Unicode
representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal
numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as
char literals.
char ch = '\n';
Example:
• Java

// Java program to illustrate the

// application of char literals

public class Test {

public static void main(String[] args)

// single character literal within single quote

char ch = 'a';

// It is an Integer literal with octal form

char b = 0789;

// Unicode representation

char c = '\u0061';

System.out.println(ch);

System.out.println(b);
System.out.println(c);

// Escape character literal

System.out.println("\" is a symbol");

Output
a
error:Integer number too large
a
" is a symbol

String literals

Any sequence of characters within double quotes is treated as


String literals.
String s = "Hello";
String literals may not contain unescaped newline or linefeed
characters. However, the Java compiler will evaluate compile-
time expressions, so the following String expression results in
a string with three lines of text:
Example:
String text = "This is a String literal\n"
+ "which spans not one and not two\n"
+ "but three lines of text.\n";

• Java

// Java program to illustrate the behaviour of // char literals


and integer literals when // we are performing addition public
class Test { public static void main(String[] args) { // ASCII
value of 0 is 48 int first = ‘0’; // ASCII value of 7 is 55 int
second = ‘7’; System.out.println(“Geeks!” + first + ‘2’ +
second); } }

Output
Hello
error: cannot find symbol
symbol: variable Hello
location: class Test

Boolean literals

Only two values are allowed for Boolean literals, i.e., true
and false.
boolean b = true;

• Java

Output
true
false
error: incompatible types: int cannot be converted to boolean
error: incompatible types: int cannot be converted to boolean
Note: When we are performing concatenation operations, then the
values in brackets are concatenated first. Then the values are
concatenated from the left to the right. We should be careful
when we are mixing character literals and integers in String
concatenation operations and this type of operation are known
as Mixed Mode operation.
• Java

// Java program to illustrate the behaviour of


// char literals and integer literals when

// we are performing addition

public class Test {

public static void main(String[] args)

// ASCII value of 0 is 48

int first = '0';

// ASCII value of 7 is 55

int second = '7';

System.out.println("Geeks!" + first +

'2' + second);

Output
Geeks!48255
Explanation: Whenever we are performing addition between a
string and integer, the overall result is converted into a
string. The above program evaluation is done in the following
way:
"Geeks!" + first + '2' + second
"Geeks! " + 48 + '2' + 55
"Geeks!48" + '2' + 55
"Geeks!482" + 55
"Geeks!48255"

Keywords in java

Java Identifiers


In Java, identifiers are used for identification purposes. Java
Identifiers can be a class name, method name, variable name, or
label.
Example of Java Identifiers
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5 identifiers namely :
• Test: class name.
• main: method name.
• String: predefined class name.
• args: variable name.
• a: variable name.
Rules For Defining Java Identifiers
There are certain rules for defining a valid Java identifier.
These rules must be followed, otherwise, we get a compile-time
error. These rules are also valid for other languages like C,
and C++.
• The only allowed characters for identifiers are all
alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar
sign) and ‘_‘ (underscore).For example “geek@” is not a
valid Java identifier as it contains a ‘@’ a special
character.
• Identifiers should not start with digits([0-9]). For
example “123geeks” is not a valid Java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but
it is advisable to use an optimum length of 4 – 15
letters only.
• Reserved Words can’t be used as an identifier. For
example “int while = 20;” is an invalid statement as a
while is a reserved word. There are 53 reserved words
in Java.
Examples of valid identifiers :
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123

Examples of invalid identifiers :


My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

Reserved Words in Java


Any programming language reserves some words to represent
functionalities defined by that language. These words are
called reserved words. They can be briefly categorized into two
parts: keywords(50) and literals(3). Keywords define
functionalities and literals define value. Identifiers are used
by symbol tables in various analyzing phases(like lexical,
syntax, and semantic) of a compiler architecture.

abstract continue for protected transient

Assert Default Goto public Try

Boolean Do If Static throws

break double implements strictfp Package


abstract continue for protected transient

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

class finally long throw Date

const float Native This while

Note: The keywords const and goto are reserved, even though
they are not currently used. In place of const, the final
keyword is used. Some keywords like strictfp are included in
later versions of Java.

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:

AD
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 javatpoint 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 o


nly
2. import java.util.*; //it imports all the class of the java
.util package
AD
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 sam
e
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 palindrom
e.");
33. }
34. }

Output:

Java Variables
Read

Practice

Video


In Java, Variables are the data containers that save the data
values during Java program execution. Every Variable in Java is
assigned a data type that designates the type and quantity of
value it can hold. A variable is a memory location name for the
data.
Variables in Java
Java variable is a name given to a memory location. It is the
basic unit of storage in a program.
• The value stored in a variable can be changed during
program execution.
• Variables in Java are only a name given to a memory
location. All the operations done on the variable
affect that memory location.
• In Java, all variables must be declared before use.
How to Declare Variables in Java?
We can declare variables in Java as pictorially depicted below
as a visual aid.
From the image, it can be easily perceived that while declaring
a variable, we need to take care of two things that are:
1. datatype: Type of data that can be stored in this
variable.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It
can be assigned values in two ways:
• Variable Initialization
• Assigning value by taking input
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as
follows:
• datatype: Type of data that can be stored in this
variable.
• variable_name: Name given to the variable.
• value: It is the initial value stored in the variable.
Illustrations:
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
// Declaring and initializing character variable
char var = 'h';
Types of Variables in Java
Now let us discuss different types of variables which are
listed as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
Let us discuss the traits of every type of variable listed here
in detail.
1. Local Variables
A variable defined within a block or method or constructor is
called a local variable.
• These variables are created when the block is entered,
or the function is called and destroyed after exiting
from the block or when the call returns from the
function.
• The scope of these variables exists only within the
block in which the variables are declared, i.e., we can
access these variables only within that block.
• Initialization of the local variable is mandatory
before using it in the defined scope.
Time Complexity of the Method:
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
• Java

// Java Program to implement

// Local Variables

import java.io.*;

class GFG {

public static void main(String[] args)

// Declared a Local Variable

int var = 10;


// This variable is local to this main method only

System.out.println("Local Variable: " + var);

Output
Local Variable: 10

Example :
• Java

package a;

public class LocalVariable {

public static void main(String[] args)

// x is a local variable

int x = 10;

// message is also a local

// variable
String message = "Hello, world!";

System.out.println("x = " + x);

System.out.println("message = " + message);

if (x > 5) {

// result is a

// local variable

String result = "x is greater than 5";

System.out.println(result);

// Uncommenting the line below will result in a

// compile-time error System.out.println(result);

for (int i = 0; i < 3; i++) {

String loopMessage

= "Iteration "

+ i; // loopMessage is a local variable


System.out.println(loopMessage);

// Uncommenting the line below will result in a

// compile-time error

// System.out.println(loopMessage);

Output :
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables
Instance variables are non-static variables and are declared in
a class outside of any method, constructor, or block.
• As instance variables are declared in a class, these
variables are created when an object of the class is
created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers
for instance variables. If we do not specify any access
specifier, then the default access specifier will be
used.
• Initialization of an instance variable is not
mandatory. Its default value is dependent on the data
type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for
Wrapper classes like Integer it is null, etc.
• Instance variables can be accessed only by creating
objects.
• We initialize instance variables
using constructors while creating an object. We can
also use instance blocks to initialize the instance
variables.
The complexity of the method:
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
• Java

// Java Program to demonstrate

// Instance Variables

import java.io.*;

class GFG {

// Declared Instance Variable

public String geek;

public int i;

public Integer I;

public GFG()

// Default Constructor

// initializing Instance Variable


this.geek = "Shubham Jain";

// Main Method

public static void main(String[] args)

// Object Creation

GFG name = new GFG();

// Displaying O/P

System.out.println("Geek name is: " + name.geek);

System.out.println("Default value for int is "

+ name.i);

// toString() called internally

System.out.println("Default value for Integer is "

+ name.I);

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

// Static variables

import java.io.*;

class GFG {

// Declared static variable

public static String geek = "Shubham Jain";

public static void main(String[] args)

// geek variable can be accessed without object

// creation Displaying O/P GFG.geek --> using the

// static variable

System.out.println("Geek Name is : " + GFG.geek);

// static int c=0;

// above line,when uncommented,


// will throw an error as static variables cannot be

// declared locally.

Output
Geek Name is : Shubham Jain
Differences Between the Instance Variables and the Static
Variables
Now let us discuss the differences between the Instance
variables and the Static variables:
• Each object will have its own copy of an instance
variable, whereas we can only have one copy of a static
variable per class, irrespective of how many objects we
create. Thus, static variables are good
for memory management.
• Changes made in an instance variable using one object
will not be reflected in other objects as each object
has its own copy of the instance variable. In the case
of a static variable, changes will be reflected in
other objects as static variables are common to all
objects of a class.
• We can access instance variables through object
references, and static variables can be accessed
directly using the class name.
• Instance variables are created when an object is
created with the use of the keyword ‘new’ and destroyed
when the object is destroyed. Static variables are
created when the program starts and destroyed when the
program stops.
Syntax: Static and instance variables
class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}
Conclusion
The Important points to remember in the articles are mentioned
below:
• Variables in Java is a data container that saves the
data values during Java program execution.
• There are three types of variables in Java Local
variables, static variables, and instance variables.
FAQs on Variables in Java
Q1. What are variables in Java?
Variables are the containers in Java that can store data values
inside them.
Q2. What are the 3 types of variables in Java?
There are three types of variables in Java are mentioned below:
1. Local Variables
2. Static Variables
3. Instance Variables
Q3. How to declare variables in Java examples?
We can declare variables in java with syntax as mentioned
below:
data_type variable_name;
Example:
// Integer datatype with var1 name
int var1;
Java Data Types


Java is statically typed and also a strongly typed language
because, in Java, each type of data (such as integer, character,
hexadecimal, packed decimal, and so forth) is predefined as part
of the programming language and all constants or variables
defined for a given program must be described with one of the
Java data types.
Data Types in Java
Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories
in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short,
byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as
String, Array, etc.
Primitive Data Types in Java
Primitive data are only single values and have no special
capabilities. There are 8 primitive data types. They are
depicted below in tabular format below as follows:
Descript Defau Siz Example
Type ion lt e Literals Range of values

boole true or 1 true,


false true, false
an false bit false

twos-
8
compleme
0 bit (none) -128 to 127
nt
s
byte integer
Descript Defau Siz Example
Type ion lt e Literals Range of values

‘a’,
‘\u0041’, characters
Unicode 16
\u000 ‘\101’, representation of
characte bit
0 ‘\\’, ASCII values
r s
‘\’, 0 to 255
char ‘\n’, ‘β’

twos-
16
compleme
0 bit (none) -32,768 to 32,767
nt
s
short integer

twos-
32 -2,147,483,648
compleme -2,-
0 bit to
nt 1,0,1,2
s 2,147,483,647
int intger

-
twos- 9,223,372,036,854,7
64 -2L,-
compleme 75,808
0 bit 1L,0L,1L,
nt to
s 2L
integer 9,223,372,036,854,7
long
75,807

1.23e100f
IEEE 754 32 , -1.23e-
floating 0.0 bit 100f , upto 7 decimal
float point s .3f digits
,3.14F

IEEE 754 64 1.23456e3


doubl floating 0.0 bit upto 16 decimal
00d , -
e point s digits
123456e-
Descript Defau Siz Example
Type ion lt e Literals Range of values

300d ,
1e1d

Let us discuss and implement each one of the following data


types that are as follows:
1. Boolean Data Type
Boolean data type represents only one bit of information either
true or false which is intended to represent the two truth
values of logic and Boolean algebra, but the size of the
boolean data type is virtual machine-dependent. Values of type
boolean are not converted implicitly or explicitly (with casts)
to any other type. But the programmer can easily write
conversion code.
Syntax:
boolean booleanVar;

Size: Virtual machine dependent


2. Byte Data Type
The byte data type is an 8-bit signed two’s complement integer.
The byte data type is useful for saving memory in large arrays.
Syntax:
byte byteVar;

Size: 1 byte (8 bits)


3. Short Data Type
The short data type is a 16-bit signed two’s complement
integer. Similar to byte, use a short to save memory in large
arrays, in situations where the memory savings actually
matters.
Syntax:
short shortVar;

Size: 2 bytes (16 bits)


4. Integer Data Type
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;

Size: 4 bytes ( 32 bits )


Remember: In Java SE 8 and later, we can use the int data type
to represent an unsigned 32-bit integer, which has a value in
the range [0, 232-1]. Use the Integer class to use the int data
type as an unsigned integer.
5. Long Data Type
The range of a long is quite large. The long data type is a
64-bit two’s complement integer and is useful for those
occasions where an int type is not large enough to hold the
desired value. The size of the Long Datatype is 8 bytes (64
bits).
Syntax:
long longVar;

Remember: In Java SE 8 and later, you can use the long data
type to represent an unsigned 64-bit long, which has a minimum
value of 0 and a maximum value of 264-1. The Long class also
contains methods like comparing Unsigned, divide Unsigned, etc
to support arithmetic operations for unsigned long.
6. Float Data Type
The float data type is a single-precision 32-bit IEEE 754
floating-point. Use a float (instead of double) if you need to
save memory in large arrays of floating-point numbers. The size
of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;

7. Double Data Type


The double data type is a double-precision 64-bit IEEE 754
floating-point. For decimal values, this data type is generally
the default choice. The size of the double data type is 8 bytes
or 64 bits.
Syntax:
double doubleVar;

Note: Both float and double data types were designed especially
for scientific calculations, where approximation errors are
acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal
class instead.
It is recommended to go through rounding off errors in java.
8. Char Data Type
The char data type is a single 16-bit Unicode character with
the size of 2 bytes (16 bits).
Syntax:
char charVar;

Why is the Size of char 2 bytes in Java?


So, other languages like C/C++ use only ASCII characters, and
to represent all ASCII characters 8 bits is enough. But Java
uses the Unicode system not the ASCII code System and to
represent the Unicode system 8 bits is not enough to represent
all characters so Java uses 2 bytes for
characters. Unicode defines a fully international character set
that can represent most of the world’s written languages. It is
a unification of dozens of character sets, such as Latin,
Greek, Cyrillic, Katakana, Arabic, and many more.
Example:
• Java

// Java Program to Demonstrate Char Primitive Data Type

// Class

class GFG {

// Main driver method

public static void main(String args[])

// Creating and initializing custom character


char a = 'G';

// Integer data type is generally

// used for numeric values

int i = 89;

// use byte and short

// if memory is a constraint

byte b = 4;

// this will give error as number is

// larger than byte range

// byte b1 = 7888888955;

short s = 56;

// this will give error as number is

// larger than short range

// short s1 = 87878787878;
// by default fraction value

// is double in java

double d = 4.355453532;

// for float use 'f' as suffix as standard

float f = 4.7333434f;

// need to hold big range of numbers then we need

// this data type

long l = 12121;

System.out.println("char: " + a);

System.out.println("integer: " + i);

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("long: " + l);


}

Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Non-Primitive Data Type or Reference Data Types


The Reference Data Types will contain a memory address of
variable values because the reference types won’t store the
variable value directly in memory. They are strings, objects,
arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference
between a character array and a string in Java is, that the
string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate
char-type entities. Unlike C/C++, Java strings are not
terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;

Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");

2. Class
A class is a user-defined blueprint or prototype from which
objects are created. It represents the set of properties or
methods that are common to all objects of one type. In general,
class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
Refer to access specifiers for classes or interfaces in
Java
2. Class name: The name should begin with an initial
letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent
(superclass), if any, preceded by the keyword extends.
A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of
interfaces implemented by the class, if any, preceded
by the keyword implements. A class can implement more
than one interface.
5. Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and
represents real-life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods.
An object consists of :
1. State: It is represented by the attributes of an
object. It also reflects the properties of an object.
2. Behavior: It is represented by the methods of an
object. It also reflects the response of an object to
other objects.
3. Identity: It gives a unique name to an object and
enables one object to interact with other objects.
4. Interface
Like a class, an interface can have methods and variables, but
the methods declared in an interface are by default abstract
(only method signature, no body).
• Interfaces specify what a class must do and not how. It
is the blueprint of the class.
• An Interface is about capabilities like a Player may be
an interface and any class implementing Player must be
able to (or must implement) move(). So it specifies a
set of methods that the class has to implement.
• If a class implements an interface and does not provide
method bodies for all functions specified in the
interface, then the class must be declared abstract.
• A Java library example is Comparator Interface. If a
class implements this interface, then it can be used to
sort a collection.
5. Array
An Array is a group of like-typed variables that are referred
to by a common name. Arrays in Java work differently than they
do in C/C++. The following are some important points about Java
arrays.
• In Java, all arrays are dynamically allocated.
(discussed below)
• Since arrays are objects in Java, we can find their
length using member length. This is different from
C/C++ where we find length using size.
• A Java array variable can also be declared like other
variables with [] after the data type.
• The variables in the array are ordered and each has an
index beginning with 0.
• Java array can also be used as a static field, a local
variable, or a method parameter.
• The size of an array must be specified by an int value
and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the
interfaces Cloneable and java.io.Serializable.
FAQs of Data Types in Java
1. What are Data Types in Java?
Data types are of different sizes and values that can be stored
in the variable that is made as per convenience and
circumstances to cover up all test cases.
2. What are the 8 Data Types that use in Java?
There are 8 main primitive data types in java as mentioned
below:
• boolean
• byte
• char
• short
• int
• long
• float
• double
3. Which is a Primitive Type in Java?
Primitive data types are the types in java that can store a
single value and do not provide any special capability.
4. Why char uses 2 bytes in Java and what is \u0000?
Char uses 2 bytes in java because it uses the Unicode system
rather than the ASCII system. “\u000” is the lowest range of
the Unicode system.

You might also like