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

Java - Unit-1

Java

Uploaded by

rajnijain3600
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 views21 pages

Java - Unit-1

Java

Uploaded by

rajnijain3600
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/ 21

Java

Java is a general purpose object oriented programming language developed by sun Microsoft system of USA
in 1991. Originally called Oak by jamesGosling, one of the inventors of the language, java was designed for
the development of the software for consumer electronic devices like TV, VCR and such other electronic
machines.

The goal had a strong impact on the development team to make the language simple, portable and high
reliable. The java team included the existing languages like c and C++ had limitation in term of both
reliability and portability. However they modeled their new language java on c and c++ but remove a number
of features of c and c++ that were considered as source of problem and thus made java a really simple,
reliable, portable and powerful language.

What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of
them are as follows:
• Desktop Applications such as acrobat reader, media player, antivirus, etc.
• Web Applications such as irctc.co.in, javatpoint.com, etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games, etc.

Why Use Java?


• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in the world.
• It is easy to learn and simple to use.
• It is open-source and free.
• It is secure, fast and powerful.
• It has a huge community support (tens of millions of developers).
• Java is an object oriented language which gives a clear structure to programs and allows code to be
reused, lowering development costs.
• As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa.

Imran Ahmed Ansari.


Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used
for creating enterprise applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.

Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of
the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)


It is a micro platform that is dedicated to mobile applications.

4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.

History of Java Programming Language


Here are important landmarks from the history of the Java language:

• The Java language was initially called OAK.


• Originally, it was developed for handling portable devices and set-top boxes. Oak was a massive
failure.

Imran Ahmed Ansari.


• In 1995, Sun changed the name to “Java” and modified the language to take advantage of the
burgeoning www (World Wide Web) development business.
• Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of three key Sun
software assets: Java, MySQL, and Solaris.

History of Java
The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the
Green Team. Java team members (also known as Green Team), initiated this project to develop a language
for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following
are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?

7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The
suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and
fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique,
most of the team members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems(which is now a subsidiary of Oracle
Corporation) and released in 1995.

Imran Ahmed Ansari.


11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in
Java.

Java Versions

List of some important milestones in the development of java:

Year Development

1990 Sun Microsoftsystem decided to develop special software that could be used to
manipulate consumer electronic device.

1991 After exploring the possibility of using the most popular object oriented
language C++ the team announced a new language named Oak.

1992 The Team known as Green Project team by sun demonstrated the application
of their new language to control a list of home application using a hand held
device with tiny touch-sensitive screen.

1993 The world Wide Web (WWW) appeared on the the internet and transformed
the text based internet to a graphical-rich-environment.

1994 The team developed a web browser called “Hotjava” to locate and run applet
program on the internet.

1995 Oak was renamed “java” due to some legal snags.java is just a name and is not
an acronym.

Here is a brief history of all the Java versions with its release date.

Java Versions Release Date


JDK Alpha and Beta 1995
JDK 1.0 23rd Jan 1996
JDK 1.1 19th Feb 1997
J2SE 1.2 8th Dec 1998
J2SE 1.3 8th May 2000
J2SE 1.4 6th Feb 2002
J2SE 5.0 30th Sep 2004
Java SE 6 11th Dec 2006
Java SE 7 28th July 2011
Java SE 8 18th Mar 2014
Java SE 9 21st Sep 2017
Java SE 10 20th Mar 2018
JAVA SE 11 25th Sep 2018
JAVA SE 12 19th Mar 2019

Imran Ahmed Ansari.


JAVA SE 13 17th Sep 2019
JAVA SE 14 17th Mar 2020
JAVA SE 15 15th Sep 2020 (latest Java Version)

C++ vs Java
KEY DIFFERENCE:
• C++ uses only compiler, whereas Java uses compiler and interpreter both.
• C++ supports both operator overloading & method overloading whereas Java only supports method
overloading.
• C++ supports manual object management with the help of new and delete keywords whereas Java
has built-in automatic garbage collection.
• C++ supports structures whereas Java doesn’t supports structures.
• C++ supports unions while Java doesn’t support unions.

COMPARISON
INDEX C++ JAVA
PARAMETER
C++ was developed by Bjarne
Java was developed by James Gosling
Developed / Founded Stroustrup at Bell Labs in 1979. It
1 at Sun Microsystems. Now, it is
by was developed as an extension of
owned by Oracle.
the C language.
It has support for both procedural
Java has support only for object
2 Programming model programming and object oriented
oriented programming models.
programming.
C++ is platform dependent. It is Java is platform independent. It is
3 Platform dependence based on the concept of Write Once based on the concept of Write Once
Compile Anywhere. Run Anywhere.
C++ supports features like operator Java does not support features like
4 Features supported overloading, Goto statements, operator overloading, Goto statements,
structures, pointers, unions, etc. structures, pointers, unions, etc.
Compilation and C ++ is only compiled and cannot Java can be both compiled and
5
Interpretation be interpreted. interpreted.
Java, on the other hand, has more
C++ has very limited libraries with diverse libraries with a lot of support
Library and Code low level functionalities. C++ for code reusability. In Java, only calls
6
reusability support allows direct calls to native system through the Java Native Interface and
libraries. recently Java Native Access are
allowed.
In C++, memory management is In Java, memory management is
7 Memory Management
manual. System controlled.
C++ is pretty consistent between In Java, semantics differs for primitive
8 Type semantics
primitive and object types. and object types.
In C++, both global and namespace
9 Global Scope Java has no support for global scope.
scopes are supported.
Access control and In C++, a flexible model with In Java, the model is cumbersome and
10
object protection constant protection is available. encourages weak encapsulation.
Call by Value and C++ supports both call by value Java supports call by value only. There
11
Call by reference and call by reference. is no call by reference in java.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
12 for threads. It relies on third-party
libraries for thread support.
Hardware C++ is nearer to hardware. Java is not so interactive with
13
hardware.

Imran Ahmed Ansari.


No backward compatibility with any
Compatibility with Compatible with C source code,
14 previous language. The syntax is
other languages except some exceptional cases.
influenced by C/C++.
C++ has scope resolution operator (:
:) which is used to define a method No scope resolution operator (: :) in Java.
Scope resolution outside of a class and to access a The method definitions have to occur
15
operator global variable within from the scope within a class, so there is no need for
where a local variable also exists with scope resolution.
the same name.

Java V/S internet and WWW


Java and Internet: Java is strongly associated with the Internet. Internet users can use Java to create applet
programs and run them locally using a "Java-enabled browser" such as HotJava. They can also use a Java-
enabled browser to download an applet located on a computer anywhere in the Internet and run it on his
local computer. In fact, Java applets have made the Internet a true extension of the storage system of the
local computer.
Internet users can also setup their websites containing java applets that could be used by other remote users
of Internet. This feature made Java most popular programming language for Internet.
Java and World Wide Web: World Wide Web (WWW) is an open-ended information retrieval system
designed to be used in the Internet's distributed environment. This system contains Web pages that provide
both information and controls. Web system is open-ended and we can navigate to a new document in any
direction. This is made possible with the help of a language called Hypertext Markup Language (HTML).
Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents
worldwide.
Java was meant to be used in distributed
environments such as Internet. Since,
both the Web and Java share the same
philosophy, Java could be easily
incorporated into the Web system.
Before Java, the World Wide Web was
limited to the display of still images and
texts. However, the incorporation of
Java into Web pages has made it capable
of supporting animation, graphics,
games, and a wide range of special
effects.

Features of Java
The primary objective of Java
programming language creation was to
make it portable, simple and secure
programming language. Apart from this,
there are also some excellent features
which play an important role in the
popularity of this language. The features
of Java are also known as Java
buzzwords.
A list of the most important features of
the Java language is given below.

• Simple
• Object-Oriented
• Portable

Imran Ahmed Ansari.


• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic Garbage Collection
in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a
write once, run anywhere language. A platform is the
hardware or software environment in which a program
runs.
There are two types of platforms software-based and
hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the
sense that it is a software-based platform that runs on top of
other hardware-based platforms. It has two components:

• Runtime Environment
• API(Application Programming Interface)

Java code can be executed on multiple platforms, for


example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into

Imran Ahmed Ansari.


bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox

• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
• Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.

Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java
robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.

Imran Ahmed Ansari.


High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language
that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.

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.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.

Components Of Java Programming Language


A Java Programmer writes a program in a human-readable language called Source Code. Therefore, the CPU
or Chips never understand the source code written in any programming language.
These computers or chips understand only one thing, which is called machine language or code. These
machine codes run at the CPU level. Therefore, it would be different machine codes for other models of
CPU.
However, you need to worry about the machine code, as programming is all about the source code. The
machine understands this source code and translates them into machine understandable code, which is an
executable code.
All these functionalities happen inside the following 3 Java platform components:

Java Environment:
Java environment included a large number of development tools and Hundreds of classes and methods. The
development tools are part of the system known as Java Development Kit(JDK) and the classes and method
are part of the java standard library (JSL) also known as the Application programming Interface(API).

Java Development kit (JDK)


JDK is a software development environment used for making applets and Java applications. The full form of
JDK is Java Development Kit. Java developers can use it on Windows, macOS, Solaris, and Linux. JDK
helps them to code and run Java programs. It is possible to install more than one JDK version on the same
computer.

Why use JDK?


Here are the main reasons for using JDK:
• JDK contains tools required to write Java programs and JRE to execute them.

Imran Ahmed Ansari.


• It includes a compiler, Java application launcher, Appletviewer, etc.
• Compiler converts code written in Java into byte code.
• Java application launcher opens a JRE, loads the necessary class, and executes its main method.

The java development kit comes with a collection of tools that are used for developing and running java
program. They include:
Appletviewer: Enabled us to run java applets.
Java: Java interpreter which run applet and application by reading and interpreting
bytecode files.
Javac: The java compiler, which translate java source code to byte code files that the
interpreter can understand.
Javadoc: Creates HTML-format documentation from java source code files.
Javah: Produce header files for use with native methods.
Javap: java disassembler which enables us to convert bytecode file into a program
description.
Jdb: java debugger, which helps us to find errors in our programs.

Application program Interface (API):


The standard library (or API) includes hundreds of classes and methods grouped into several functional
packages .Most commonly used packages are:
Language Support Packages (.lang): A collection of classes and methods required for implementing basic
features of java.
Utilities Packages (.util): A collection of classes to provide utility functions such as date and time
functions.
Input/Output Packages (.io): A collection of classes required for input/output manipulation.
Networking Packages (.net):A collection of classes for communicating with other computer via internet.

AWT packages(.awt): The Abstract window tool kit packages contains classes that implements plateform-
independent graphical user interface.
Applet packages(.Applet):this includea set of classes that allow us to create java applets.

Java Virtual Machine (JVM):


Java Virtual Machine (JVM) is an engine that provides a runtime environment to drive the Java Code or
applications. It converts Java bytecode into machine language. JVM is a part of the Java Run Environment
(JRE). In other programming languages, the compiler produces machine code for a particular system.
However, the Java compiler produces code for a Virtual Machine known as Java Virtual Machine.
All languages translate source code into machine code for a specific computer. Java compiler also
does the same thing. Then how does java achieve architecture neutrality? The answer is that the java
compiler produces an intermediate code known as byte code for a machine that does not exist. This machine
is called the java virtual machine and it exists only inside the computer memory .it is a simulated computer
within the computer and does all major functions of a real computer. The figure define the process of
compiling a java program into bytecode which is also referred to as virtual machine code.

Fig: Process of Compilation


The virtual machine code is not machine specific. The machine specific code is generated by the java
interpreter by acting as an intermediary between virtual machine and the real machine as shown as figure.

Imran Ahmed Ansari.


Java Runtime Environment (JRE)
JRE is a piece of software that is designed to run other software. It contains the class libraries, loader class,
and JVM. In simple terms, if you want to run a Java program, you need JRE. If you are not a programmer,
you don’t need to install JDK, but just JRE to run Java programs.

Why use JRE?


Here are the main reasons of using JRE:

• JRE contains class libraries, JVM, and other supporting files. It does not include any tool for Java
development like a debugger, compiler, etc.
• It uses important package classes like math, swing, util, lang, awt, and runtime libraries.
• If you have to run Java applets, then JRE must be installed in your system.

Java Program Structure


Java programming language is platform-independent
and a secure programming language. With a wide
variety of applications, Java programming
language has been in demand for the last two decades.
The out-of-the-box features help java stand apart. In
this article, we will understand the structure of
a java program in detail. Following are the topics
discussed in this blog:

• Documentation Section
• Package Statement
• Import Statement
• Interface Section
• Class Definition
• Main Method Class

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.
• Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For
example:
/*It is an example of
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
/**It is an example of documentation comment*/

Imran Ahmed Ansari.


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:
• package javatpoint; //where javatpoint is the package name
• 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:
• import java.util.Scanner; //it imports the Scanner class only
• 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:
interface car
{
void start();
void stop();
}

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:
class Student //class definition
{
}

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:
public static void main(String args[])
{
}
For example:
public class Student //class definition

Imran Ahmed Ansari.


{
public static void main(String args[])
{
//statements
}
}

Token:
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as
follows:

• Keywords
• Identifiers
• Constants
• Special Symbols
• Operators
Keywords:
Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is
not allowed. Java language supports following keywords:

Abstract assert Boolean break byte case


Catch char class const continue default
do double else enum exports extends
final finally float for goto if
implements import instanceof int interface long
module native new open opens package
private protected provides public requires return
short static strictfp super switch synchronized
this throw throws to transient transitive
try uses void volatile while with

Identifiers in Java
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name,
method name, package name, constant name, and more. However, In Java, There are some reserved words
that cannot be used as an identifier.
A Java identifier is a name given to a package, class, interface, method, or variable. It allows a programmer
to refer to the item from other places in the program.
In programming languages, identifiers are used for identification purposes. In Java, an identifier can be a
class name, method name, variable name, or label. For example:
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.

Imran Ahmed Ansari.


Rules for defining Java Identifiers
There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we get
compile-time error. These rules are also valid for other languages like C, C++.
• The only allowed characters for identifiers are all alphanumeric characters ([A-Z],[a-z],[0-9]),
‘$‘(dollar sign) and ‘_‘ (underscore).For example “java@” is not a valid java identifier as it contain
‘@’ special character.
• Identifiers should not start with digits ([0-9]). For example “123java” is a 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 while is a reserved word. There are 53 reserved words in Java.

Java Constant
Constant is a value that cannot be changed after assigning it. Java does not directly support the constants.
There is an alternative way to define the constants in Java by using the non-access modifiers static and final.
Constants are also like normal variables. But, the only difference is, their values cannot be modified by the program
once they are defined. Constants refer to fixed values. They are also called as literals.

How to declare constant in Java?


In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-
access modifiers. According to the Java naming convention the identifier name must be in capital letters.
Static and Final Modifiers
• The purpose to use the static modifier is to manage the memory.
• It also allows the variable to be available without loading any instance of the class in which it is
defined.
• The final modifier represents that the value of the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
Final data_type variable_name;

Special Symbols: The following special symbols are used in Java having some special meaning and thus, cannot be
used for some other purpose.
[] () {}, ; * =
Brackets []: Opening and closing brackets are used as array element reference. These indicate single and
multidimensional subscripts.
Parentheses (): These special symbols are used to indicate function calls and function parameters.
Braces {}: These opening and ending curly braces marks the start and end of a block of code containing more than one
executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters in function calls.
Semicolon : It is an operator that essentially invokes something called an initialization list.
asterick (*): It is used to create pointer variable.
Assignment operator: It is used to assign values

Variable:A variable is an identifier that denotes a storage location use to store a data value.
Variable in Java is a data container that saves the data values during Java program execution. Every variable
is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory
location name of the data.
A 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.
• A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location.

Imran Ahmed Ansari.


• In Java, all the variables must be declared before use.

Syntax:
Datatype variable1, variable2…
Int a,
Float b,c;
int data=50;//Here data is variable

Rules:
• They must not begin with a digit.
• Uppercase and lowercase are distinct.
• It should not be a keyword.
• White space is not allowed.
• Variable names can be of any length.

Assignment of Variable:
Datatype variable =value;
Int a=10;
Example:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

Types of Variables in Java


Now let us discuss different types of variables which are listed as follows:
• Local Variables
• Instance Variables
• Static Variables

Local Variables
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and an initial value
should be assigned before the first use.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
O/P: Puppy age is: 7

Imran Ahmed Ansari.


Instance Variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap, a slot for each instance variable value is created.
• Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object's state that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class. Normally, it is
recommended to make these variables private (access level). However, visibility for subclasses can
be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers, the default value is 0, for Booleans it is false,
and for object references it is null. Values can be assigned during the declaration or within the
constructor.
• Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using
the fully qualified name. ObjectReference.VariableName.

public class A
{ static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Static Variables
Static variables are also known as Class variables.
• These variables are declared similarly as instance variables. The difference is that static variables are
declared using the static keyword within a class outside 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 Static Variable is not mandatory. Its default value is 0
• If we access the static variable like the Instance variable (through an object), the compiler will show
the warning message, which won’t halt the program. The compiler will replace the object name with
the class name automatically.
• If we access the static variable without the class name, the compiler will automatically append the
class name.
import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}}

Imran Ahmed Ansari.


Data Types in Java
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals, or characters in these variables.
There are two data types available in Java −
• Primitive Data Types
• Reference/Object Data Types

Java has two categories of data:


• Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
• Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Imran Ahmed Ansari.


Java Control Statements
Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in
which they appear. However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth
flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

1) If Statement:
if(condition) public class Student {
{ public static void main(String[] args) {
statement 1; //executes when condition is true int x = 10;
} int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

2) if-else statement
if(condition) { public class Student {
statement 1; //executes when condition is true public static void main(String[] args) {
int x = 10;
} int y = 12;
else{ if(x+y < 10) {
statement 2; //executes when condition is fals System.out.println("x + y is less than 10");
e } else {
} System.out.println("x + y is greater than 20");
}
}
}

3) if-else-if ladder:
if(condition 1) { public class Student {
statement 1; //executes when condition 1 is true public static void main(String[] args) {
} String city = "Delhi";
else if(condition 2) { if(city == "Meerut") {
statement 2; //executes when condition 2 is true System.out.println("city is meerut");
} }else if (city == "Noida") {
else { System.out.println("city is noida");
statement 2; //executes when all the conditions ar }else if(city == "Agra") {
e false System.out.println("city is agra");
} }else {
System.out.println(city);
}
}
}

Imran Ahmed Ansari.


4) Nested if-statement
if(condition 1) { public class Student {
statement 1; //executes when condition 1 is true public static void main(String[] args) {
if(condition 2) { String address = "Delhi, India";
statement 2; //executes when condition 2 is true
} if(address.endsWith("India")) {
else{ if(address.contains("Meerut")) {
statement 2; //executes when condition 2 is false System.out.println("Your city is Meerut");
} }else if(address.contains("Noida")) {
} System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India
");
}
} }
Switch Statement:
switch (expression){ public class Student implements Cloneable {
case value1: public static void main(String[] args) {
statement1; int num = 2;
break; switch (num){
. case 0:
. System.out.println("number is 0");
. break;
case valueN: case 1:
statementN; System.out.println("number is 1");
break; break;
default: default:
default statement; System.out.println(num);
} }
} }
Loop statement

For Loop
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

public class ForExample {


public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}

Imran Ahmed Ansari.


MORE TECHNICAL INFORMATION
What will I get when I download Java software from java.com?

The Java Runtime Environment (JRE) version 8 is what you get when you download Java software from java.com.

The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform
libraries. The JRE is the runtime portion of Java software, which is all you need to run Java WebStart applications
from a supported web browser. It doesn’t come with development tools, though – these tools are part of the Java
Development Kit (JDK).

What is Java Plug-in software?

The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows some applications
written in the Java programming language to launch via some browsers. The Java Plug-in software is not a standalone
program and cannot be installed separately.

I have heard the terms Java Virtual Machine and JVM. Is this Java software?

The Java Virtual Machine is only one part of Java software that is involved in running an application. The Java Virtual
Machine is built right into your Java software download, part of the JRE and helps run Java applications.

1. Question: Is it better to learn C++ or Java?

Answer: For beginners, it is better to learn C++ as the syntax of C++ is easier compared to
Java and there is extensive support for standard data structures like stack, queue, etc. in
C++. However, for more experienced coders, Java is a great programming language to
know about as Java is used in a lot of big companies like Amazon, Google, etc. and
therefore, would help the developers a lot.

2. Question: Is C++ powerful than Java?

Answer: We cannot say that one language is more powerful than the other until the criteria
for judgement is mentioned. In other words, in terms of performance, C++ is the winner.
However, in terms of flexibility of usage, Java is definitely better.

3. Question: Why is C++ used?

Answer: C++ is a semi object oriented programming language which is great for beginners
to learn about the basics or fundamentals of object oriented programming. Also, in areas
like Gaming engines and High Frequency Trading, etc. high performance is of utmost
importance and hence, C++ is the preferred language in these fields.

Imran Ahmed Ansari.


4. Question: Is C++ a dying language?

Answer: To a certain extent, the answer to this question is Yes. Java and JavaScript had
taken over a few years back and Python seems to dominate the present (and future
perhaps). However, we have to also take into consideration the fact that C++ is still
amongst the top five most popular languages. The fact that C++ usage is more domain-
oriented, does not necessarily mean it is dying.

5. Question: Which is better for beginners? C++ or Java?

Answer: In order to answer this question, one’s interests need to be taken into account. If a
beginner wants to make projects on the system side, or make projects related to gaming
engines, etc. and if making high performance and fast systems is a priority, C++ is
definitely a better choice for those kinds of beginners compared to Java. However, Java
offers way more features and easy to use libraries than C++ and therefore, is preferred in
the domain of Software Development by a lot of developers. So, to build feature rich
applications with ease, a beginner can go ahead and choose Java over C++.

6. Question: What is the main key difference between C++ and Java?

Answer: The main difference between C++ and Java is that C++ is only a compiled
language while Java is both compiled and interpreted. The C++ compiler converts the
source code into machine code and therefore, it is platform dependent. However, Java
source code is converted into bytecode by its compiler and following that, the Java
interpreter executes this bytecode at runtime and produces output. The fact that Java is
interpreted is the reason as to why it is platform independent.

Imran Ahmed Ansari.

You might also like