[go: up one dir, main page]

0% found this document useful (0 votes)
36 views58 pages

Notes On Java August 2024

A complete summary of Java basics for beginners

Uploaded by

Íni Ø Bóñg
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)
36 views58 pages

Notes On Java August 2024

A complete summary of Java basics for beginners

Uploaded by

Íni Ø Bóñg
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/ 58

INTRODUCTION TO JAVA

What is Java?
Java is an object oriented programming language originally developed by Sun Microsystems
and officially presented at SunWorld on May 23, 1995. Java is described as being a multi-
purpose, strongly typed, class-based, and Object-Oriented Programming (OOP) language. It
became the property of Oracle in 2009, after the Oracle Company bought the Sun Company.

Goals for the Creation of Java


By design, Java has as few implementation dependencies as possible. There were five primary
goals in the creation of the Java language:
1. It must be object-oriented, simple, and familiar.
2. It must be robust and secure.
3. It must be architecture-neutral and portable.
4. It must execute with high performance.
5. It must be interpreted, threaded, and dynamic.
Object Oriented − In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Simple − Java has a clean and simple coding style, making it easy to learn. Many complex
features and low-level facilities found in C are removed in Java such as explicit pointers,
storage classes goto statements, and many more. It also provides a very useful feature of the
Garbage collection.
Familiar – The syntax of Java is similar to C and C++ making it easy for users of such to catch
on; it has the feature of commenting out the unnecessary text which makes it easy to understand
for both the programmers and the readers.
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile-time error checking and runtime checking.
Platform Independent − Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into java byte
code which is platform independent. This byte code can be distributed over the web and
interpreted by the Java Virtual Machine (JVM) on whichever platform it is being run on. Thus
it is possible for programmers to write once, run anywhere (WORA).
Secure − With Java's secure feature it enables users to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption. Fairly secure and featuring
configurable security, it allowed network- and file-access restrictions.
Architecture-neutral − Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
Portable − Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java a highly portable programming language—it is not designed for any
specific hardware or software platform. Java programs once written are translated into an
intermediate form called bytecode. The bytecode is then translated by the Java Virtual Machine
(JVM) into the native object code of the processor that the program is being executed on. JVMs
exist for several computer platforms; hence the term Write Once Run Anywhere (WORA)..
Multithreaded − With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high performance.
Distributed − Java is designed for the distributed environment of the internet.
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.

NEW☛ Bytecodes are a set of instructions that looks a lot like some machine
TERM codes, but that is not specific to any one processor.

Brief History of Java


The big demand in making people’s lives less complicated by introducing intelligence to
everyday home appliances and consumer electronics devices led Sun Microsystems to embark
on the “Green Project” which aimed to develop an embedded software that was small, fast,
efficient, easily usable and portable across different platforms for a variety of processors found
in those devices— interactive television, point of sale terminals, ATMs, set-top boxes, the
PDAs, VCRs, toasters, and the other sorts of machines. C++ was to be used but it was not
portable. So they agreed to develop a programming language for the purpose. After several
months of intense research in the Green Project by the team (comprising James Gosling – the
leader, Patrick Naughton, Mike Sheridan, Chris Warth, and Ed Frank ) a programming
language was birthed that has a syntax similar to that of C++, which they used to program a
digital remote control they made, equipped with a graphic and animated touch screen. This
remote control had the fantastic feature of controlling the entire living-room equipment. It was
programmed in the new language, completely independent of the processor it was running on,
making the remote one-of-a-kind. The team adopted the name oak for the new language. This
choice was inspired by the oak tree that stood outside the office of James Gosling. However
oak was already a registered trademark.
Unfortunately, the demand for such appliances did not turn out as what Sun Microsystem
expected. Furthermore the language was far more sophisticated than the devices it was
designed initially for. Consequently the programming team had to find another channel to
expand Java. With the advent of the Internet and the World Wide Web which were becoming
popular day-by-day, the team saw the need for web programs that should be platform-
independent, web programs which have to be able to run on any operating system irrespective
of hardware and software configuration. It required small and portable programs that could be
securely transported over the network. They, then, focused on making their programming
language available to suit such requirements. ‘Java’ became chosen as the new name of the
programming language. Java is the name of the Indonesian island where one of the finest coffee
(named java coffee) was produced. The team was fond of taking this java coffee whenever they
had their breaks during the development of the programming language. Thus, the symbol for
Java is tea cup.
So finally, May 23, 1995, Java was first released at the SunWorld Conference and was
immediately followed by Netscape (the world’s #1 browser at that time) announcing that they
will incorporate the programming language in their development. With Java-embedded web
pages, websites transformed from plain dull into interactive ones. Not only that the Web sends
information to its audience, but they are also able to accept user input. The first public release
was made in 1996. Major web browsers soon incorporated the ability to run Java applets within
web pages, and Java quickly became popular.
The designers of Java chose to use a combination of compilation and interpretation. Programs
written in Java are compiled into machine language, but it is a machine language for a
computer that doesn’t really exist. This so-called “virtual” computer is known as the Java
Virtual Machine (JVM).

What is Java used for?


Here are some important Java applications:

 It is used for developing Android Apps


 Helps you to create Enterprise Software
 Wide range of Mobile java Applications
 Scientific Computing Applications
 Use for Big Data Analytics
 Java Programming of Hardware devices
 Used for Server-Side Technologies like Apache, JBoss, GlassFish, etc.

Components of Java Programming Language


Computers or chips understand only one thing, which is called machine language or
code. These machine codes run at the CPU level. Machines are not universally the
same. Different makes and models of CPU have their peculiar designs and machine
codes are different from other models of CPU.

The program which a Programmer writes in a human-readable language – high level


language – is called Source Code. The CPU or Chips never understand the source
code written in any programming language other than the machine language for it.

However, there is no need to worry about the machine code, as programming is all
about the source code. Through the help of language translators 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 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.
 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.

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.

Why JVM?
Here are the important reasons of using JVM:

 JVM provides a platform-independent way of executing Java source code.


 It has numerous libraries, tools, and frameworks.
 Once you run a Java program, you can run on any platform and save lots of
time.
 JVM comes with JIT (Just-in-Time) compiler that converts Java source code into
low-level machine language. Hence, it runs faster than a regular application.

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.

What is Java Platform? Java platform is a collection of programs that help to develop and run
programs written in the Java programming language. Java platform includes an execution
engine, a compiler, and a set of libraries. JAVA is platform-independent language. It is not
specific to any processor or operating system.

Different Types of Java Platforms


There are four different types of Java programming language platforms:

1. Java Platform, Standard Edition (Java SE): Java SE’s API offers the Java programming
language’s core functionality. It defines all the basis of type and object to high-level classes. It
is used for networking, security, database access, graphical user interface (GUI) development,
and XML parsing.

2. Java Platform, Enterprise Edition (Java EE): The Java EE platform offers an API and
runtime environment for developing and running highly scalable, large-scale, multi-tiered,
reliable, and secure network applications.

3. Java Programming Language Platform, Micro Edition (Java ME): The Java ME
platform offers an API and a small-footprint virtual machine running Java programming
language applications on small devices, like mobile phones.

4. Java FX: JavaFX is a platform for developing rich internet applications using a lightweight
user-interface API. It user hardware-accelerated graphics and media engines that help Java take
advantage of higher-performance clients and a modern look-and-feel and high-level APIs for
connecting to networked data sources.

Parts of a Java Program


The program below (Listing 1.0) is a simple yet complete program containing the basic features
of all Java application programs.

/*
* This is a simple Java program
* Call this file Example.java
*/

public class Example // class definition header


{
public static void main( String[] args )
// A Java program begins with a call to main ().
{
System.out.println( “Hello World!!!” ); //print text
System.out.println( “Java is essential to the Web!!!” );
// print text
} // end method main
} // end class HelloWorld

Listing 1.0 HelloWorld.java

We will consider each of these features and explain them accordingly.


Comments
Comments are the descriptive parts of the program that explain what the codes are all
about, and are used for documenting a program, (that is, passing across vital information
concerning the program – such as the logic being applied, name of the program and any
other relevant information). They are special sections of text that we humans read but which
the compiler totally ignores and are therefore used to improve the program’s readability—
helping people understand the operation of the program.
There are two types of comments, depending on how you write them:
1. In-Line or End-of-Line Comment
This comment starts with two slashes, followed by the comment text which is short enough
to fit on one line. It can be placed at the beginning of a line or at the end of a line of code. The
following are examples of this type of comment from listing 1.0
// class definition header
// A Java program begins with a call to main ().
// print text

Since everything is ignored by the compiler starting from the first slash up to the end of the
line an inline comment, if it is combined with executable code, must be placed after the
executable statement and not before else the program statement will be ignored by the
compiler.
2. Block or Multi-Line Comment
The first few lines of the program are comments.
/*
* This is a simple Java program
* Call this file Example.java
*/
When your comment text is too long to fit in one line you may use the Block or Multi-
Line Comment. In this style the comments are enclosed between the “/*” and “*/”
symbols. The opening “/*” starts the comment and a closing “*/” ends it (to save time in
writing “//” for every line). Again, the compiler ignores everything between the two slashes.

Prologue is a version of a block comment that is placed at the top or very beginning of
your programs. It contains important information about the code so that every programmer
will be able to get an idea of what the program is all about just by merely glancing at it.
Usually, the prologue is enclosed in a box of asterisks and includes the following
information: filename, programmer’s name and program description. If we are to modify the
block comment above, it will look like this:
/***************************************************************
**
* This is a simple Java program
* Call this file Example.java
* Epiahe & Akpana
* This is a simple program that displays “Java is essential to
the Web” on your PC * screen
****************************************************************
*/

The Class Definition Header


The rest of the program starting with the line: public class Example, is the class
declaration. The class declaration starts with the class definition header public class
Example, followed by a pair of opening(‘{‘) and closing(‘}‘) curly brackets. Actually
the entire program is considered as a class).
Class definition header starts with the access modifier ‘public’ followed by the
‘class’ then the name of the class ‘Example’. The first two words, public and class are
what we call reserved words or keywords. Such words are used for a particular purpose as
defined by the Java language. You cannot redefine or use them to mean something else, like
making them as names for your program. The access modifier tells the Java compiler that the
class can be accessed outside the program file that it is declared in (in this case, the
information can be accessed by all other classes). If it was set to private instead of public,
then only the current class has the access to it. The keyword class tells Java that we want to
define a class using the name Example. Finally, the open curly brace “{“ indicates the
beginning of the class and has a corresponding closing brace “}” at the end of the entire
program. Always coming in pairs, braces identify groupings of code for both the programmer
and the computer.

Note: The file containing this class must be saved using the name Example.java. The
name of the file and the class name must be the same both in capitalization and sequence.
Java is very case sensitive thus example is different from Example and also different from
EXAMPLE.

Below is a list of the common keywords in Java language:

abstract assert boolean Break Byte


Case catch char Class const
continue default Do Double else
enum extends final Finally float
For goto If Implements import
instanceof int interface Long native
New package private Protected public
return short static Strictfp super
switch synchronized This Throw throws
transient try Void Volatile while

Main Method’s Heading


The next part of the program is the declaration of the main method which comes after the class
heading. Method is a subroutine in Java language. Methods are used for carrying out the desired
tasks in a Java program. Simply put methods are a list of things to do. The main method signifies
the line of code at which the program will begin executing; it is the first list of things to do. In
our example, the main method definition header has the following form:
public static void main(String args[])
Again, it starts with the access modifier “public” which is an access modifier keyword, which
indicates that everyone can access the main method. This also means that this can be accessed
by the code outside the class in which it was defined or declared.
Public is followed by the keyword “static” which implies that the method main( ) may be
called before an object of the class has been created, i.e. it denotes that the method can be
accessed immediately. The third reserved word is “void” that signifies that, in this case, the
main method will not return any value on completion of its task. (in some programs it could
return a value). These keywords public, static, and void should always be placed in the
sequenced shown.
Any information that is needed to pass to a method is received by variables specified within the
set of parentheses “(” and “)” that follow the name of the method.

Note: If no parameters are required for a given method, you still need to include the empty parentheses.
These variables are also called parameters and in our example there is only one parameter,
(String args[]), which declares a parameter named “args”, which represents any
command-line arguments that the main method takes. “String” is the argument’s type that
stores sequences of characters. The square brackets “[]” symbolizes that “args” is an array
(Arrays are collections of similar objects). Therefore String args[] says that the parameter
args is an array of objects of type strings.

Note that the parameters could have been written as String[] args.
The instructions (statements) enclosed within the curly braces will be executed once the main
method is run.

System.out.println
Our main method contains the following line:

System.out.println( “Hello World!!!” ); //print text


System.out.println( “Java is essential to the Web!!!” );
The above program contains the instruction that tells Java to display a message on the
output i.e. to the screen. The text enclosed in double quotation marks “ ” inside the
parentheses is the message to be printed out to the screen. These double quotes are in charge
of grouping the messages together. The first line prints the message Hello World!!!
followed by a carriage return i.e. a new line on the screen; again the second line outputs the
string Java is essential to the Web!!! followed by a carriage return i.e. a new
line on the screen.

“System.out.println” is a programming code that gives instructions to the


computer to print something out. Let us discuss every part of it. “System” refers to the
computer and when it becomes “System.out” it pertains to the monitor, which is the
output device of the computer system. The next word, “println” (read as “print line”) is a
built-in Java method that is in control of printing computer messages. Overall, the line of
code is what is referred to as println method call.
You simply call a method when you want to execute it.

The first letter of a method call is always in uppercase and the rest will be
in lowercase..

At the end of the line is a semi-colon “;” that signifies the end of the method call or
programming statement (it is like period in the normal English language).

All programming statements to be executed in Java end with a semicolon
‘;’

The reason that the other lines in the program do not end in a semicolon is that they are
not, technically, statements. The first closing brace “}” in the program ends main( ), and the
last “}” ends the Example class definition; it is a good practice to place a comment after the
closing curly brace. The opening and close brace are referred to as a block of code.

One last point: Remember that we said that Java is case sensitive. Forgetting this can
cause you serious problems. For example, if you accidentally type Main instead of main, or
PrintLn instead of println, the preceding program will be incorrect. Furthermore, although the
Java compiler will compile classes that do not contain a main( ) method, it has no way to
execute them. So, if you had mistyped main, the compiler would still compile your program.
However, the Java interpreter would report an error because it would be unable to find the
main( ) method.

In the above program some lines where left blank, this was done in order to make the
program readable. Furthermore, tabs (indentation) were used to within the body of a class or
methods as appropriate to spate characters and symbols. The blank spaces, tabs, and newline
characters are referred to as white spaces.
Now let us run this program and see how it works.

Compilation and Execution of Java Programs


The Java Development Kit is a tool that acts as both a compiler and an interpreter.

The latest JDK version can be downloaded from Oracle’s website -


www.oracle.com/technetwork/java/javase/downloads/index.html. Ensure that you download
the appropriate version for your computer. If you are using a 32-bit operating system, then
download the matching file name affixed with x86. Otherwise, if it is a 64-bit operating system
then download the one with x64.
Although the Java language is highly standardized, the procedures for creating, compiling, and
editing Java programs vary widely from one programming environment to another.

There are two basic approaches:

1. a command line environment, where the user types commands and the computer
responds, and
2. an integrated development environment (IDE), where the user uses the keyboard
and mouse to interact with a graphical user interface.
While there is just one common command line environment for Java programming,
there is a wide variety of IDEs.

2.6.1 Java Development Kit

The basic development system for Java programming is usually referred to as the JDK
(Java Development Kit). It is a part of J2SE, the Java 2 Platform Standard Edition. Note that
J2SE comes in two versions, a Development Kit version and a Runtime version. The Runtime
can be used to run Java programs and to view Java applets in Web pages, but it does not allow
you to compile your own Java programs. The Development Kit includes the Runtime and adds
to it the JDK which lets you compile programs. You need a JDK for use in this course. If a
JDK is installed on your computer, you can use the command line environment to compile and
run Java programs. Some IDEs depend on the JDK, so even if you plan to use an IDE for
programming, you might still need a JDK.

2.6.2 Command Line Environment

Many modern computer users find the command line environment to be pretty alien and
unintuitive. It is certainly very different from the graphical user interfaces that most people are
used to. However, it takes only a little practice to learn the basics of the command line
environment and to become productive using it.
To use a command line programming environment. In Windows, to open the Command
Prompt window where you can type in commands. Press the Windows key, and then enter
“cmd”, in the search box, as the name of the program. The Command Prompt window will
open and display a prompt e.g.

C:\Users\Epiahe>

Type in a command at the prompt and press return. The computer will carry out the command,
displaying any output in the command window, and will then redisplay the prompt so that you
can type another command. One of the central concepts in the command line environment is the
current directory which contains the files to which commands that you type apply. (The words
“directory” and “folder” mean the same thing.) Often, the name of the current directory is part of
the command prompt. You can get a list of the files in the current directory by typing in the
command dir (on Windows)

When the window first opens, the current directory is your home directory, where all
your files are stored. You can change the current directory using the cd command with the
name of the directory that you want to use. For example, to change into your Desktop
directory, type in the command cd Desktop and press return.
You should create a directory (that is, a folder) to hold your Java work. For example,
create a
directory named javawork in your home directory. You can do this using your
computer’s GUI;

another way to do it is to open a command window and enter the command mkdir
javawork.

When you want to work on programming, open a command window and enter the
command

cd javawork to change into your work directory. Of course, you can have more than one

working directory for your Java work; you can organize your files any way you like.

∗∗∗
The most basic commands for using Java on the command line are javac and java; javac
is used to compile Java source code, and java is used to run Java stand-alone applications. If a
JDK is correctly installed on your computer, it should recognize these commands when you
type them in on the command line. Try typing the commands java -version and javac -version
which should tell you which version of Java is installed. If you get a message such as
“Command not found,” then Java is not correctly installed. If the “java” command works, but
“javac” does not, it means that a Java Runtime is installed rather than a Development Kit.

The procedures for Java application and Java applets are basically the same. The major
difference is that Java applets are executed within a browser. The basic steps for compiling
and executing a Java program are:

a) Enter the source code using a text editor. He file must be saved using the file
extension .java.
b) Use the Java compiler to convert the source code to its bytecode equivalent. The
byte code will be saved in a file having the same name as the program file with an
extension .class. To compile our HelloWorld.java program, type the following
instructions at the Windows command prompt

(c:\>): javac Example.java


c) The bytecodes (.class file) will be created only if there are no compilation errors.
d) Finally use the Java interpreter to execute the application, to do this at the
Windows command prompt

(c:\>) type: java Example. (You need not type the .class extension)

e) Note: Other programs, called Integrated Development Environments (IDEs), have


been created to support the development of Java programs. IDEs combine an
editor, compiler, and other Java support tools into a single application. The
specific tools you will use to develop your programs depend on your
environment. Examples of IDEs include NetBeans, Eclipse, BlueJ etc.

SYNTAX, SEMANTICS AND PRAGMATICS


A program is a sequence of instructions that a computer can execute to perform some task.
Programming languages differ from ordinary human languages in being completely
unambiguous and very strict about what is and is not allowed in a program.

Syntax of the language refers to the rules that determine what is allowed. Syntax rules
specify the basic vocabulary of the language and how programs can be constructed using
things like loops, branches, and subroutines. A syntactically correct program is one that can
be successfully compiled or interpreted; programs that have syntax errors will be rejected
(hopefully with a useful error message that will help you fix the problem).It’s not enough to
write a program that will run—you want a program that will run and produce the correct
result! This takes us to semantics.

Semantics refers to the meaning of a program. The meaning of the program has to be right.
A semantically correct program is one that does what you want it to do. Furthermore, a
program can be syntactically and semantically correct but still be a pretty bad program.

Pragmatics. Using the language correctly is not the same as using it well. For example, a
good program has “style.” It is written in a way that will make it easy for people to read and
to understand. It follows conventions that will be familiar to other programmers. And it has
an overall design that will make sense to human readers. These conventions and designs are
paramount to a human reader, but the computer is completely oblivious to such things.
These aspects of programming are sometimes referred to as pragmatics. Pragmatics deal
with learning how to use the language feature well and with style, that will earn you the
admiration of other programmers. The layout of the program on the page, such as the use of
blank lines and indentation, is not part of the syntax or semantics of the language but vital
for readability of the code. The computer doesn’t care about layout—you could run the
entire program together on one line as far as it is concerned.

The pragmatics of naming includes style guidelines about how to choose names for things.
For example, it is customary for names of classes to begin with upper case letters, while
names of variables and of subroutines begin with lower case letters; you can avoid a lot
of confusion by following the same convention in your own programs. Most Java
programmers do not use underscores in names, although some do use them at the beginning
of the names of certain kinds of variables. When a name is made up of several words, such
as HelloWorld or interestRate, it is customary to use camel case for a name that is made
up of several words. Camel case capitalizes each word of a name that comprises multiple
words, except possibly the first.

Things are often referred to by compound names which consist of several ordinary names
separated by periods. (Compound names are also called qualified names.) You’ve already
seen an example: System.out.println. The idea here is that things in Java can contain other
things. A compound name is a kind of path to an item through one or more levels of
containment. The name System.out.println indicates that something called “System”
contains something called “out” which in turn contains something called “println”.

Non-compound names are called simple identifiers. The term identifier may be used to
refer to any name—simple or compound—that can be used to refer to something in Java.
(Note that the reserved words are not identifiers, since they can’t be used as names for
things.)

NEW☛ A class is a template for multiple objects with similar features. Classes
TERM embody all the features of a particular set of objects

THE CONCEPT OF DATA TYPES, VARIABLES AND CONSTANT.


The fundamental building blocks of programs are data and instructions. To work with data, you
need to understand variables and data types; while you need to understand control structures and
subroutines to work with instructions.
We will consider control structures in more details later but for now suffice it to say that control
structures are special instructions that can change the flow of control; there are two basic types of
control structure: loops, which allow a sequence of instructions to be repeated over and over, and
branches, which allow the computer to decide between two or more different courses of action by
testing conditions that occur as the program is running
A subroutine consists of the instructions for performing some task, grouped together as a unit and
given a name. That name can then be used as a substitute for the whole set of instructions. A built-in
subroutine is one that is already defined as part of the language and therefore automatically available
for use in any program.
Now let us go back to Data. When you write a program you, most often than not write instructions
on how the computer must manipulate data. This data, as well as the instructions that manipulate it
are held in memory. In low level languages, besides the data manipulation, you most concern
yourself the storage and retrieval. Some data values require more memory space to store than others.
Some operations cannot be performed on data of certain types, etc. Keeping track of the hardware
address of where a particular data is stored can be quite a handful of tasks, and seriously distract one
from concentrating on the program logic. Fortunately this keeping of tabs can be more efficiently
carried out by the Operating System, leaving you to concentrate on the manipulation of the data.

What is Data Types


Data are simply values which can be a letter/character, stream of letters/characters or figures that
may be integers or floating point numbers of varying sizes. No matter how large a computer
memory is, it is limited in size and its ability to hold data. In order to effectively manage memory,
there is need to categorize data according to the set of values and sizes of values it can hold. This
brings us to the concept of Data Types. In Java Data Types are defined as specifiers that allocate
different sizes and types of values that can be stored in the variable or an identifier. Data type
defines the values that a variable can take, for example if a variable has int data type, it can only take
integer values.
1. Primitive Data Types:- which include integer, character, boolean, and float
2. Non-primitive Data Types: - which include strings, arrays, classes, and interfaces (more on
these later).
Java is a statically typed language. A language is statically typed, if the data type of a variable is
known at compile time. This means that you must specify the type of the variable (Declare the
variable) before you can use it.

Primitive Data Types

Primitive Data Types are predefined and available within the Java language. Primitive values do
not share state with other primitive values. There are 8 primitive built into Java. The primitive
types are named:
byte, short, int,
long, float, double,
char, and boolean.
The first four types
hold integers (whole
numbers such as 17,
-38477, and 0). The
four integer types are distinguished by the ranges of integers they can hold. The float and
double types hold real numbers (such as 3.6 and -145.99). Again, the two real types are
distinguished by their range and accuracy. A variable of type char holds a single character
from the Unicode character set. And a variable of type boolean holds one of the two logical
values true or false. A variable of type byte holds a string of eight bits, which can represent
any of the integers between -128 and 127, inclusive. (There are 256 integers in that range;
eight bits can represent 256—two raised to the power eight—different values.) As for the
other integer types, short corresponds to two bytes (16 bits). Variables of type short have
values in the range -32768 to 32767. int corresponds to four bytes (32 bits). Variables of
type int have values in the range -2147483648 to 2147483647. long corresponds to eight
bytes (64 bits). Variables of type long have values in the range -9223372036854775808 to
9223372036854775807.

The float data type is represented in four bytes of memory, using a standard method for
encoding real numbers. The maximum value for a float is about 10 raised to the power 38. A
float can have about 7 significant digits. (So that 32.3989231134 and 32.3989234399 would
both have to be rounded off to about 32.398923 in order to be stored in a variable of type
float.) A double takes up 8 bytes, can range up to about 10 to the power 308, and has about
15 significant digits. A variable of type char occupies two bytes in memory. The value of a
char variable is a single character such as A, *, x, or a space character. The value can also be
a special character such a tab or a carriage return or one of the many Unicode characters that
come from different languages. When a character is typed into a program, it must be
surrounded by single quotes; for example: ’A’, ’*’, or ’x’. Without the quotes, A would be
an identifier and * would be a multiplication operator. The quotes are not part of the value
and are not stored in the variable; they are just a convention for naming a particular
character constant in a program.
Integer data Floating Data Textual Data Logical
types Type Type boolean (1
byte (1 float (4 char (2 byte)
byte) bytes) bytes) (true/false)
short (2 double (8
bytes) bytes)
int (4
bytes)
long (8
bytes)

Java Data Types Points to Remember:


Default
Data Type Default Value  All numeric data types are signed(+/-).
size
byte 0 1 byte  The size of data types remain the same on
all platforms (standardized)
short 0 2 bytes
 char data type in Java is 2 bytes because it
int 0 4 bytes
uses UNICODE character set. By virtue of it,
long 0L 8 bytes
Java supports internationalization. UNICODE is
float 0.0f 4 bytes a character set which covers all known scripts
double 0.0d 8 bytes and language in the world
boolean false 1 bit
char ‘\u0000’ 2 bytes
A name for a constant value is called a
LITERAL. A literal is what you have to type in a program to represent a value. ’A’ and ’*’
are literals of type char, representing the character values A and *. Certain special characters
have special literals that use a backslash, \, as an “escape character”. In particular, a tab is
represented as ’\t’, a carriage return as ’\r’, a linefeed as ’\n’, the single quote character as
’\’’, and the backslash itself as ’\\’. Note that even though you type two characters between
the quotes in ’\t’, the value represented by this literal is a single tab character.

Numeric literals are a little more complicated. But there are a number of possibilities for
expressing numbers in a Java program. First of all, we may have integers and decimal
numbers. Secondly real numbers can be represented in an exponential form such as 1.3e12
or 12.3737e-108. The “e12” and “e-108” represent powers of 10, so that 1.3e12 means 1.3
times 1012 and 12.3737e-108 means 12.3737 times 10−108. This format can be used to express
very large and very small numbers.

Any numerical literal that contains a decimal point or exponential is a literal of type
double. To make a literal of type float, you have to append an “F” or “f” to the end of the
number. For example, “1.2F” stands for 1.2 considered as a value of type float.

NOTE: The rules of Java say that you can’t assign a value of type double to a variable
of type float

Suppose therefore that x is a variable of type float then an expression like:

“x = 1.2;” will come up with a ridiculous-seeming error message

You have to say “x = 1.2F;".

Even for integer literals, there are some complications. Ordinary integers such as 177777
and -32 are literals of type byte, short, or int, depending on their size. You can make a literal
of type long by adding “L” as a suffix. For example: 17L or 728476874368L.

As another complication, Java allows octal (base-8) and hexadecimal (base-16) literals.

NOTE: Octal numbers use only the digits 0 through 7. In Java, a numeric literal that
begins with a 0 is interpreted as an octal number; for example, the literal 045
represents the number 37, not the number 45.

Note also that Hexadecimal numbers use 16 digits, the usual digits 0 through 9 and the
letters A or a, B or b, C or c, D or d, E or e, and F or f. Upper case and lower case letters can
be used interchangeably in this context. The letters represent the numbers 10 through 15. In
Java, a hexadecimal literal begins with 0x or 0X, as in 0x45 or 0xFF7A.

Hexadecimal numbers are also used in character literals to represent arbitrary Unicode
characters. A Unicode literal consists of \u followed by four hexadecimal digits. For
example, the character literal ’\u00E9’ represents the Unicode character that is an “e” with
an acute accent.

For the type boolean, there are precisely two literals: true and false. These literals are typed
without quotes, but they represent values, not variables. Boolean values occur most often as
the values of conditional expressions. For example,

rate > 0.05


is a boolean-valued expression that evaluates to true if the value of the variable rate is
greater than 0.05, and to false if the value of rate is not greater than 0.05. Of course, boolean
values can also be assigned to variables of type boolean.

Java has other types in addition to the primitive types, but all the other types represent

objects rather than “primitive” data values.

One predefined object type that is very important is the type String. A String is a sequence
of characters such as "Hello World!". The double quotes are part of the literal; they have to
be typed in the program. However, they are not part of the actual string value, which
consists of just the characters between the quotes. Within a string, special characters can be
represented using the backslash notation. Within this context, the double quote is itself a
special character.

For example, to represent the string value

I said, "Are you listening!"

with a linefeed at the end, you would have to type the string literal:

"I said, \"Are you listening!\"\n"

You can also use \t, \r, \\, and unicode sequences such as \u00E9 to represent other special
characters in string literals. Because strings are objects, their behavior in programs is
peculiar in some respects. Based on the new program code, the Scanner variable
InputVariableName was first saved into MyVariableName and then was used to display the
user-generated input to the screen Here is a simple program using some variables and
assignment statements:

/**
* This class implements a simple program that
* will compute the amount of interest that is
* earned on $17,000 invested at an interest
* rate of 0.07 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/

public class Interest {

public static void main(String[] args) {

/* Declare the variables. */

double principal; // The value of the investment.


double rate; // The annual interest rate.
double interest; // Interest earned in one year.

/* Do the computations. */
principal = 17000;
rate = 0.07;
interest = principal * rate; // Compute the interest.
principal = principal + interest;

// Compute value of investment after one year, with interest.


// (Note: The new value replaces the old value of principal.)

/* Output the results. */

System.out.print("The interest earned is $");


System.out.println(interest);
System.out.print("The value of the investment after one year is
$");
System.out.println(principal);

} // end of main()

} // end of class Interest

This program uses several subroutine call statements to display information to the user of the
program. Two different subroutines are used: System.out.print and System.out.println.

The difference between these is that System.out.println adds a linefeed after the end of the
information that it displays, while System.out.print does not. Thus, the value of interest,
which is displayed by the subroutine call “System.out.println(interest);”, follows on the
same line after the string displayed by the previous System.out.print statement. Note that the
value to be displayed by System.out.print or System.out.println is provided in parentheses
after the subroutine name. This value is called a parameter to the subroutine. A parameter
provides a subroutine with information it needs to perform its task. In a subroutine call
statement, any parameters are listed in parentheses after the subroutine name. Not all
subroutines have parameters. If there are no parameters in a subroutine call statement, the
subroutine name must be followed by an empty pair of parentheses.

What is a Variable?

Programs manipulate data that are stored in memory. A name used in this way—to refer to
data stored in memory—is called a variable. A variable can be used in a program only if it
has first been declared. When the computer executes a variable declaration, it sets aside
memory for the variable and associates the variable’s name with that memory. Hence we say
that a variable is a name created by the programmer, during the variable declaration, for a
location in memory that can hold data and not a name for the data itself. The variable refers
directly to the box and only indirectly to the data in the box. Note that the data in the box
can change during the execution of the program.

A variable is a memory location name of the data. A variable is actually a name that you declare
which is used by the computer to represent a memory location which you can then use to store or
retrieve a value. In a layman’s view, you could think of a variable as a container or box where
you can store data during Java program execution. This container is given a name that you create
when you declare the variable. Every variable is assigned data type which designates the type and
quantity of value it can hold. A variable in Java is designed to hold only one particular type of
data; it can legally hold that type of data and no other. The compiler will consider it to be a syntax
error if you try to violate this rule. We say that Java is a strongly typed language because it
enforces this rule.

Variables naming convention in java

1) Variables names cannot contain white spaces


for example: int num ber = 100; is invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case letter, for
example int number; For lengthy variables names that has more than one words do it like this: int
smallNumber; int bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.

In order to use a variable in a program you to need to perform 2 steps

1. Variable Declaration
2. Variable Initialization

Variable Declaration:
To declare a variable, you must specify the data type & give the variable a
unique name. Examples of other Valid Declarations are
int a,b,c;
float pi;
double d;
char a;

How do you declare a variable? A simple variable declaration


takes the form:

<type> < variable-name or list-of-variables-names-separated-by-commas>;

The (variable-name-or-names) can be a single variable name or a list of variable names


separated by commas. Good programming style is to declare only one variable in a
declaration statement, unless the variables are closely related in some way. For example:
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;
It is also good style to include a comment with each variable declaration to explain its
purpose in the program, or to give other information that might be useful to a human reader.
For example:
double principal; // Amount of money invested.
double interestRate; // Rate as a decimal, not percentage.

Variable Initialization:
To initialize a variable, you must assign it a valid value. The “=” sign is used in assignment
statements. Example of other Valid Initializations are
pi =3.14f;
tRates =20.22d;
a=’v’;
You can combine variable declaration and initialization. Example:
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;

The Java variables have mainly three types: Local, Instance and Static.

Types of variables
In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Class Variables or Static Variables

class TypesOfVariables {
static int a = 1; //static variable
int data = 99; //instance variable
void method() {
int b = 90; //local variable
}
}
We will explain what these are briefly, now, but will come back to them with more details later on.

1) Local Variables
Local Variables are a variable that are declared and used inside the body of a method (or a block).
When a variable is declared inside the main() subroutine of a program or inside be any other
subroutine, it is called a local variable for that subroutine. They exist only inside the method (or
block), while it is running, and are completely inaccessible from outside. Variable declarations can
occur anywhere inside the subroutine, as long as each variable is declared before it is used in
any expression.

Some people like to declare all the variables at the beginning of the subroutine. Others like
to wait to declare a variable until it is needed.

You can choose to:


1) declare important variables at the beginning of the subroutine, and use a comment to
explain the purpose of each variable.
2) declare ‘utility variables’ which are not important to the overall logic of the
subroutine at the point in the subroutine where they are first used.

2) Instance Variables
Instance variables, fortunately, are declared and defined in exactly the same way as local variables;
the only difference is their location in the class definition. They are defined/ declared inside a class
but outside the body of a method. They are object-specific.
Customarily, however, most instance variables are defined just after the class definition header. For
example, Listing 1.1 shows a simple class definition for the classBicycle, which inherits from the
class PersonPoweredVehicle. This class definition contains four instance variables:
■ bikeType: the kind of bicycle this bicycle is—for example, Mountain or
Street
■ chainGear, the number of gears in the front
■ rearCogs, the number of minor gears on the rear axle
■ currentGearFront and currentGearRear: the gears the
bike is currently in, both front and rear

Listing 1 . 1 . The bicycle class.


1: class Bicycle extends PersonPoweredVehicle {
2: String bikeType;
3: int chainGear;
4: int rearCogs;
5: int currentGearFront;
6: int currentGearRear;
7: }

3) Class or Static Variables

• Class variables, also known as static variables, are declared inside a class with the static
keyword, but outside a method, constructor or a block. Static variables are initialized only once, at
the start of the program execution. These variables should be initialized first, before the initialization
of any instance variables.
Java Variable Type Conversion & Type Casting
A variable of one type can receive the value of another type. Here there are 2 cases:

Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity. It is


like pouring the content of a dish into a basin. The basin will always and very easily contain a
dish’s content so need to worry about losses. This process is known as Conversion. It is
automatic, and non-explicit.

double d;
int i = 10;
d = i;
Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity. In
such cases, you have to explicitly specify the type cast operator. This process is known as
Type Casting. In this case, there are possibilities of encountering losses. Picture yourself
pouring the tea in your jug into a teacup. The jug has a larger capacity than a teacup, hence if
the jug has more tea than a teacup can hold, then the teacup will get full and some tea will be
spilled and lost.

double d = 10;
Type Cast
int i; Operator

i = (int) d

In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is
enforced by the compiler, it makes the programmer aware that the conversion he is about to do
may cause some loss in data and prevents accidental losses. Let us demonstrate these concepts

Step 1) Copy the following code into an editor.


class ExampleTypeCasting {
public static void main(String args[]) {
byte x;
int a = 270;
double b = 128.128;
System.out.println("int converted to byte");
x = (byte) a;
System.out.println("a and x " + a + " " + x);
System.out.println("double converted to int");
a = (int) b;
System.out.println("b and a " + b + " " + a);
System.out.println("\ndouble converted to byte");
x = (byte)b;
System.out.println("b and x " + b + " " + x);
}
}
Step 2) Save, Compile & Run the code.

Output:

int converted to byte


a and x 270 14
double converted to int
b and a 128.128 128

double converted to byte


b and x 128.128 -128

VARIABLES AND THE PRIMITIVE TYPES


Names are fundamental to programming. In programs, names are used to refer to many
different sorts of things. In order to use those things, a programmer must understand the rules
for giving names to things and the rules for using the names to work with those things. That is,
the programmer must understand the syntax and the semantics of names. According to the
syntax rules of Java, a name is a sequence of one or more characters. It must begin with a letter
or underscore and must consist entirely of letters, digits, and underscores. For example, here are
some legal names:

N n rate x15 quite a long name HelloWorld

No spaces are allowed in names; HelloWorld is a legal name, but “Hello World” is not.

Upper case and lower case letters are considered to be different, so that HelloWorld,
helloworld, HELLOWORLD, and hElloWorLD are all distinct names.
Certain names are reserved for special uses in Java, and cannot be used by the programmer
for other purposes. These reserved words include: class, public, static, if, else, while, and
several dozen other words.

ASSIGNMENT STATEMENT. In Java, the only way to get data into a variable is with an
assignment statement. An assignment statement takes the form:

(variable) = (expression);

where (expression) represents anything that refers to or computes a data value. When the
computer comes to an assignment statement in the course of executing a program, it
evaluates the expression and puts the resulting data value into the variable. For example,
consider the simple assignment statement

rate = 0.07;

interest = rate * principal;

Note that an assignment statement is a command that is executed by the computer at a


certain time. It is not a statement of fact. The meaning of an assignment statement is
completely different from the meaning of an equation in mathematics, even though both use
the symbol “=”.

VARIABLES TYPES AND LITERALS

A variable in Java is designed to hold only one particular type of data; it can legally hold
that type of data and no other. The compiler will consider it to be a syntax error if you try to
violate this rule. We say that Java is a strongly typed language because it enforces this
rule. There are eight so-called primitive types built into Java. The primitive types are named:
byte, short, int, long, float, double, char, and boolean. The first four types hold integers
(whole numbers such as 17, -38477, and 0). The four integer types are distinguished by the
ranges of integers they can hold. The float and double types hold real numbers (such as 3.6
and -145.99). Again, the two real types are distinguished by their range and accuracy. A
variable of type char holds a single character from the Unicode character set. And a variable
of type boolean holds one of the two logical values true or false. A variable of type byte
holds a string of eight bits, which can represent any of the integers between -128 and 127,
inclusive. (There are 256 integers in that range; eight bits can represent 256—two raised to
the power eight—different values.) As for the other integer types, short corresponds to two
bytes (16 bits). Variables of type short have values in the range -32768 to 32767. int
corresponds to four bytes (32 bits). Variables of type int have values in the range -
2147483648 to 2147483647. long corresponds to eight bytes (64 bits). Variables of type
long have values in the range -9223372036854775808 to 9223372036854775807.

The float data type is represented in four bytes of memory, using a standard method for
encoding real numbers. The maximum value for a float is about 10 raised to the power 38. A
float can have about 7 significant digits. (So that 32.3989231134 and 32.3989234399 would
both have to be rounded off to about 32.398923 in order to be stored in a variable of type
float.) A double takes up 8 bytes, can range up to about 10 to the power 308, and has about
15 significant digits. A variable of type char occupies two bytes in memory. The value of a
char variable is a single character such as A, *, x, or a space character. The value can also be
a special character such a tab or a carriage return or one of the many Unicode characters that
come from different languages. When a character is typed into a program, it must be
surrounded by single quotes; for example: ’A’, ’*’, or ’x’. Without the quotes, A would be
an identifier and * would be a multiplication operator. The quotes are not part of the value
and are not stored in the variable; they are just a convention for naming a particular
character constant in a program.

A name for a constant value is called a LITERAL. A literal is what you have to type in a
program to represent a value. ’A’ and ’*’ are literals of type char, representing the character
values A and *. Certain special characters have special literals that use a backslash, \, as an
“escape character”. In particular, a tab is represented as ’\t’, a carriage return as ’\r’, a
linefeed as ’\n’, the single quote character as ’\’’, and the backslash itself as ’\\’. Note that
even though you type two characters between the quotes in ’\t’, the value represented by this
literal is a single tab character.

Numeric literals are a little more complicated. But there are a number of possibilities for
expressing numbers in a Java program. First of all, we may have integers and decimal
numbers. Secondly real numbers can be represented in an exponential form such as 1.3e12
or 12.3737e-108. The “e12” and “e-108” represent powers of 10, so that 1.3e12 means 1.3
times 1012 and 12.3737e-108 means 12.3737 times 10−108. This format can be used to express
very large and very small numbers.

Any numerical literal that contains a decimal point or exponential is a literal of type
double. To make a literal of type float, you have to append an “F” or “f” to the end of the
number. For example, “1.2F” stands for 1.2 considered as a value of type float. (NOTE that
the rules of Java say that you can’t assign a value of type double to a variable of type
float)

Suppose therefore that x is a variable of type float then an expression like:

“x = 1.2;” will come up with a ridiculous-seeming error message

You have to say “x = 1.2F;".

Even for integer literals, there are some complications. Ordinary integers such as 177777
and -32 are literals of type byte, short, or int, depending on their size. You can make a literal
of type long by adding “L” as a suffix. For example: 17L or 728476874368L.

As another complication, Java allows octal (base-8) and hexadecimal (base-16) literals.

Note that Octal numbers use only the digits 0 through 7. In Java, a numeric literal that
begins with a 0 is interpreted as an octal number; for example, the literal 045 represents the
number 37, not the number 45.

Note also that Hexadecimal numbers use 16 digits, the usual digits 0 through 9 and the
letters A, B, C, D, E, and F. Upper case and lower case letters can be used interchangeably
in this context. The letters represent the numbers 10 through 15. In Java, a hexadecimal
literal begins with 0x or 0X, as in 0x45 or 0xFF7A.
Hexadecimal numbers are also used in character literals to represent arbitrary Unicode
characters. A Unicode literal consists of \u followed by four hexadecimal digits. For
example, the character literal ’\u00E9’ represents the Unicode character that is an “e” with
an acute accent.

For the type boolean, there are precisely two literals: true and false. These literals are typed
without quotes, but they represent values, not variables. Boolean values occur most often as
the values of conditional expressions. For example,

rate > 0.05

is a boolean-valued expression that evaluates to true if the value of the variable rate is
greater than 0.05, and to false if the value of rate is not greater than 0.05. Of course, boolean
values can also be assigned to variables of type boolean.

Java has other types in addition to the primitive types, but all the other types represent

objects rather than “primitive” data values.

One predefined object type that is very important is the type String. A String is a sequence
of characters such as "Hello World!". The double quotes are part of the literal; they have to
be typed in the program. However, they are not part of the actual string value, which
consists of just the characters between the quotes. Within a string, special characters can be
represented using the backslash notation. Within this context, the double quote is itself a
special character.

For example, to represent the string value

I said, "Are you listening!"

with a linefeed at the end, you would have to type the string literal:

"I said, \"Are you listening!\"\n"

You can also use \t, \r, \\, and unicode sequences such as \u00E9 to represent other special
characters in string literals. Because strings are objects, their behavior in programs is
peculiar in some respects. Based on the new program code, the Scanner variable
InputVariableName was first saved into MyVariableName and then was used to display the
user-generated input to the screen Here is a simple program using some variables and
assignment statements:

/**
* This class implements a simple program that
* will compute the amount of interest that is
* earned on $17,000 invested at an interest
* rate of 0.07 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {

public static void main(String[] args) {

/* Declare the variables. */

double principal; // The value of the investment.


double rate; // The annual interest rate.
double interest; // Interest earned in one year.

/* Do the computations. */

principal = 17000;
rate = 0.07;
interest = principal * rate; // Compute the interest.
principal = principal + interest;

// Compute value of investment after one year, with interest.


// (Note: The new value replaces the old value of principal.)

/* Output the results. */

System.out.print("The interest earned is $");


System.out.println(interest);
System.out.print("The value of the investment after one year is $");
System.out.println(principal);

} // end of main()

} // end of class Interest

This program uses several subroutine call statements to display information to the user of the
program. Two different subroutines are used: System.out.print and System.out.println.

The difference between these is that System.out.println adds a linefeed after the end of the
information that it displays, while System.out.print does not. Thus, the value of interest,
which is displayed by the subroutine call “System.out.println(interest);”, follows on the
same line after the string displayed by the previous System.out.print statement. Note that the
value to be displayed by System.out.print or System.out.println is provided in parentheses
after the subroutine name. This value is called a parameter to the subroutine. A parameter
provides a subroutine with information it needs to perform its task. In a subroutine call
statement, any parameters are listed in parentheses after the subroutine name. Not all
subroutines have parameters. If there are no parameters in a subroutine call statement, the
subroutine name must be followed by an empty pair of parentheses.
1. Variables naming convention in java
1) Variables naming cannot contain white spaces, for example: int num ber = 100; is
invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one
words do it like this: int smallNumber; int bigNumber; (start the second word with
capital letter).
4) Variable names are case sensitive in Java.
Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
Static (or class) Variable
Static variables are also known as class variable because they are associated with the
class and common for all the instances of class. For example, If I create three objects
of a class and access this static variable, it would be common for all, the changes
made to the variable using one of the object would reflect when you access it through
other objects.
Example of static variable
public class StaticVarExample {
public static String myClassVar="class or static variable";

public static void main(String args[]){


StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);

//changing the value of static variable using obj2


obj2.myClassVar = "Changed Text";

//All three will display "Changed Text"


System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}
Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
As you can see all three statements displayed the same output irrespective of the
instance through which it is being accessed. That’s is why we can access the static
variables without using the objects like this:
System.out.println(myClassVar);
Do note that only static variables can be accessed like this. This doesn’t apply for
instance and local variables.
Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike static
variable, instance variables have their own separate copy of instance variable. We
have changed the instance variable value using object obj2 in the following program
and when we displayed the variable using all three objects, only the obj2 value got
changed, others remain unchanged. This shows that they have their own copy of
instance variable.
Example of Instance variable
public class InstanceVarExample {
String myInstanceVar="instance variable";

public static void main(String args[]){


InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();

System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);

obj2.myInstanceVar = "Changed Text";

System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
}
}
Output:
instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable
These variables are declared inside method of the class. Their scope is limited to the
method which means that You can’t change their values and access them outside of
the method.
In this example, I have declared the instance variable with the same name as local
variable, this is to demonstrate the scope of local variables.

Example of Local variable


public class VariableExample {
// instance variable
public String myVar="instance variable";

public void myMethod(){


// local variable
String myVar = "Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

/* We are calling the method, that changes the


* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}
Output:
Calling Method
Inside Method
instance variable
If I hadn’t declared the instance variable and only declared the local variable inside
method then the statement System.out.println(obj.myVar); would have thrown
compilation error. As you cannot change and access local variables outside the
method.
2. Data Types in Java

Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values. In java we have two categories of data type:
1) Primitive data types 2) Non-primitive data types – Arrays and Strings are non-
primitive data types, we will discuss them later in the coming tutorials. Here we will
discuss primitive data types and literals in Java.
Java is a statically typed language. A language is statically typed, if the data type of a
variable is known at compile time. This means that you must specify the type of the
variable (Declare the variable) before you can use it.
In the last tutorial about Java Variables, we learned how to declare a variable, lets
recall it:
int num;
So in order to use the variable num in our program, we must declare it first as shown
above. It is a good programming practice to declare all the variables ( that you are
going to use) in the beginning of the program.
1. 1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float
and double. Java developers included these data types to maintain the portability of
java as the size of these primitive data types do not change from one operating system
to another.
byte, short, int and long data types are used for storing whole numbers.
float and double are used for fractional numbers.
char is used for storing characters(letters).
boolean data type is used for variables that holds either true or false.
1. byte
This can hold whole number between -128 and 127. Mostly used to save memory and
when you are certain that the numbers would be in the limit specified by byte data
type.
Default size of this data type: 1 byte.
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

byte num;

num = 113;
System.out.println(num);
}
}
Output:
113
Try the same program by assigning value assigning 150 value to variable num, you
would get type mismatch error because the value 150 is out of the range of byte data
type. The range of byte as I mentioned above is -128 to 127.
2. short
This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte
short num = 45678;
3. int
Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

short num;

num = 150;
System.out.println(num);
}
}
Output:
150
The byte data type couldn’t hold the value 150 but a short data type can because it
has a wider range.
4. long
Used when int is not large enough to hold the value, it has wider range than int data
type, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {

long num = -12332252626L;


System.out.println(num);
}
}
Output:
-12332252626
5. double
Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
class JavaExample {
public static void main(String[] args) {

double num = -42937737.9d;


System.out.println(num);
}
}
Output:
-4.29377379E7
6. float
Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
class JavaExample {
public static void main(String[] args) {

float num = 19.98f;


System.out.println(num);
}
}
Output:
19.98
7. boolean
It holds either true of false.
class JavaExample {
public static void main(String[] args) {

boolean b = false;
System.out.println(b);
}
}
Output:
false
8. char
It holds characters.
size: 2 bytes
class JavaExample {
public static void main(String[] args) {

char ch = 'Z';
System.out.println(ch);
}
}
Output:
Z
2. Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is a Integer literal.
char ch = 'A';
Here A is a char literal
1. Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;
2. Float Literals
Used for data type float and double.

double num1 = 22.4;


float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
3. Char and String Literal
Used for char and String type.
char ch = 'Z';
String str = "BeginnersBook";

3. Type Casting in Java


Assigning a value of one primitive data type to another primitive data type is known as casting.
There are two types of type casting in java as shown in the following diagram.

 Narrowing(explicit) type casting


 Widening(implicit) type casting

1. Narrowing Type Casting


It is also known as explicit type casting. It is done when assigning a larger size data type to
smaller size data type, thus the term narrowing is used.
Notice the int inside parentheses before double variable d and float variable f. This is done
when passing the larger size data type value to smaller size data type.
public class JavaExample {
public static void main(String[] args) {
double d = 4.55d;
float f = 1.25f;
int i = (int)d; // Explicit casting: double to int
int i2 = (int)f; // Explicit casting: float to int

System.out.println("Double Value: "+d); // Prints 4.55


System.out.println("Double to int: "+i); // Prints 4
System.out.println("Float value: "+f); // Prints 1.25
System.out.println("Float to int: "+i2); // Prints 1
}
}
Output:

2. Widening Type Casting


Widening type casting is an automatic casting. In this type casting, a value of smaller data
type is assigned to larger size data type. This is also called implicit type casting as there is no
need to mention the data type in parentheses and the conversion is handled automatically by
the compiler.
public class JavaExample {
public static void main(String[] args) {
int i = 1001;
float f = 105.00f;
long l = i; // Implicit casting: int to long
double d = f; // Implicit casting: float to double

System.out.println("int Value: "+i); // Prints 1001


System.out.println("int to long: "+l); // Prints 1001
System.out.println("float value: "+f); // Prints 105.0
System.out.println("float to double: "+d); // Prints 105.0
}
}
Output:

4. Operators in Java With Examples


Operator is a symbol that instructs the compiler to perform a specific action. For
example, a “+” operator instructs the compiler to perform addition, a “>” operator
instructs the compiler to perform comparison, “=” for assignment and so on. In this
guide, we will discuss operations in java with the help of examples.
Operator and Operand:
In any operation, there is an operator and operands. For example: In a+b, the “+”
symbol is the operator and a & b are operands.
Types of Operator in Java

Operators in java are classified in following eight categories:

1) Arithmetic Operators

2) Assignment Operators

3) Unary Operators
4) Logical Operators

5) Relational operators

6) Bitwise Operators

7) Ternary Operator

8) Shift Operators

1) Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %

Note: Division (/) operator returns quotient while modulo operator(%)


returns remainder. For example 10 % 5 would return 0 while 10/5 would return 2.
Example of Arithmetic Operators
public class JavaExample {
public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

System.out.println("num1+num2: " + (num1 + num2) );


System.out.println("num1-num2: " + (num1 - num2) );
System.out.println("num1*num2: " + (num1 * num2) );
System.out.println("num1/num2: " + (num1 / num2) );
System.out.println("num1%num2: " + (num1 % num2) );
}
}
Output:
2) Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=


Example of Assignment Operators
public class JavaExample {
public static void main(String args[]) {
int num1 = 10, num2;

num2 = num1;
System.out.println("= Output: "+num2);
num2 += num1;
System.out.println("+= Output: "+num2);
num2 -= num1;
System.out.println("-= Output: "+num2);
num2 *= num1;
System.out.println("*= Output: "+num2);
num2 /= num1;
System.out.println("/= Output: "+num2);
num2 %= num1;
System.out.println("%= Output: "+num2);
}
}
Output:

3) Unary Operators
As the name suggests, The Unary operators in Java involve single operand. Java
supports following unary operators:

 Unary minus(-)
 Increment(++)
 Decrement(- -)
 NOT(!)
 Bitwise Complement(~)

num++ is equivalent to num=num+1;


num–- is equivalent to num=num-1;
Example of Unary Operators
public class JavaExample {
public static void main(String args[]){
int num1=100;
int num2=200;

//minus(-) unary operator


int inverseNum = -num1;
System.out.println("Opposite of num1: "+inverseNum);

//increment
num1++;

//decrement
num2--;

System.out.println("num1++ is: "+num1);


System.out.println("num2-- is: "+num2);

}
}
Output:
Opposite of num1: -100
num1++ is: 101
num2-- is: 199
The NOT(!) Operator reverses the logical state (true or false) of an operand. If an
operand or condition is true, then the Logical NOT operator will make it false and vice-
versa.
If value of a boolean variable 'bool' is true, then the value of
!bool is false
If the value of 'bool' is false, then the value of !bool is true

4) Logical Operators

Logical Operators are used to evaluate the outcome of conditions. There are three
logical operators: AND (&&), OR (||) and NOT (!). The AND and OR operators are
used when multiple conditions are combined and we need to evaluate the outcome as
a whole.
Example of Logical Operators
In this example, we are performing logical operations on boolean variables. However
in practical scenarios, these operators are used to combine the multiple conditions (or
expressions), which we have covered in the separate tutorial (link is at the end of the
following program).
public class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

System.out.println("b1 && b2: " + (b1&&b2));


System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}
}
Output:
b1 && b2: false
b1 || b2: true
!(b1 && b2): true

5) Comparison (Relational) operators

Relational operators are used to compare two operands. In java, we have following
relational operators:
Example of Relational operators
Note: This example is using if-else statement which is our next tutorial, if you are
finding it difficult to understand then refer if-else in Java.
public class JavaExample {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if( num1 != num2 ){
System.out.println("num1 and num2 are not equal");
}
else{
System.out.println("num1 and num2 are equal");
}

if( num1 > num2 ){


System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}

if( num1 < num2 ){


System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}
}
}
Output:

6) Bitwise Operators
Bitwise operators are used to perform bit-level operations. Let’s say you are
performing an AND operation on two numbers (a & b), then these numbers are
converted into binary numbers and then the AND operation is performed. Finally, the
compiler returns decimal equivalent of the output binary number.
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if
both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010
because in the binary form of num1 and num2 only second last bits are matching.
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if
either bit is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if
they are not equal, else it returns 0. In our example it would return 29 which is
equivalent to 00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In
our example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit,
and assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent
to 00101100
Note: In the example below we are providing 2 at the right side of this shift operator
that is the reason bits are moving two places to the left side. We can change this
number and bits would be moved by the number of bits specified on the right side of
the operator. Same applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right
bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent
to 00000010
Example of Bitwise Operators
public class BitwiseOperatorDemo {
public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


System.out.println("num1 & num2: "+result);

result = num1 | num2;


System.out.println("num1 | num2: "+result);

result = num1 ^ num2;


System.out.println("num1 ^ num2: "+result);

result = ~num1;
System.out.println("~num1: "+result);
result = num1 << 2;
System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}
Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

7) Ternary Operator
Ternary operator is the only operator in java that takes three operands. This operator
is frequently used as a one line replacement for if…else statement.
Syntax:
variable = Condition ? Expression1: Expression2
If condition is true, the Expression1 executes.
If condition is false, the Expression2 executes.

If the condition returns true, the result of Expression1 is assigned to variable else
result of Expression2 is assigned to variable.
Example of Ternary Operator
public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}
Output:
num2: 200
num2: 100
8) Shift Operators

Shift operators are used to perform bit manipulation. In this guide, we will discuss
various shift operators supported in java with the help of examples. Java supports
following shift operators:
Shift operator example
public class JavaExample {
public static void main(String[] args) {
int num = 24;

//Left shift
System.out.println("num<<2: "+(num<<2));

//Right shift
System.out.println("num>>2: "+(num>>2));
}
}
Output:
num<<2: 96 num>>2: 6

Operator Precedence in Java


This determines which operator needs to be evaluated first if an expression has more
than one operator. Operator with higher precedence at the top and lower precedence
at the bottom.

Operators Precedence

Unary
++ – – ! ~
Operators

Multiplicative * /%

Additive + –

Shift << >> >>>

Relational > >= < <=

Equality == !=

Bitwise AND &

Bitwise XOR ^
Bitwise OR |

Logical AND &&

Logical OR ||

Ternary ?:

= += -= *= /= %= > >= <


Assignment
<= &= ^= |=

Example 2: Read two integer or floating point numbers and display the
multiplication
In the above program, we can only integers. What if we want to calculate the
multiplication of two float numbers? This programs allows you to enter float numbers
and calculates the product.
Here we are using data type double for numbers so that you can enter integer as well
as floating point numbers.
import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

/* This reads the input provided by user


* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");

// This method reads the number provided using keyboard


double num1 = scan.nextDouble();

System.out.print("Enter second number: ");


double num2 = scan.nextDouble();

// Closing Scanner after the use


scan.close();

// Calculating product of two numbers


double product = num1*num2;

// Displaying the multiplication result


System.out.println("Output: "+product);
}
}
Output:
Enter first number: 1.5
Enter second number: 2.5
Output: 3.75
5. Java Program to find ASCII value of a Character

ASCII is a code for representing English characters as numbers, each letter of english
alphabets is assigned a number ranging from 0 to 127. For example, the ASCII code
for uppercase P is 80.
In Java programming, we have two ways to find ASCII value of a character 1) By
assigning a character to the int variable 2) By type casting character value as int
Lets write a program to understand how it works:
Example: Program to find ASCII code of a character
public class Demo {

public static void main(String[] args) {

char ch = 'P';
int asciiCode = ch;
// type casting char as int
int asciiValue = (int)ch;

System.out.println("ASCII value of "+ch+" is: " + asciiCode);


System.out.println("ASCII value of "+ch+" is: " +
asciiValue);
}
}
Output:
ASCII value of P is: 80
ASCII value of P is: 80
Modifiers are keywords that you add to those definitions to change their meanings.
Java language has a wide variety of modifiers, including the following −
 Java Access Modifiers
 Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or
variable. The modifier precedes the rest of the statement, as in the following example.
Example
public class className {
// ...
}

private boolean myFlag;


static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;

public static void main(String[] arguments) {


// body of method
}

Access Control Modifiers

Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are −
 Visible to the package, the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Non-Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionality.


 The static modifier for creating class methods and variables.
 The final modifier for finalizing the implementations of classes, methods, and
variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

What is Next?

In the next section, we will be discussing about Basic Operators used in Java
Language. The chapter will give you an overview of how these operators can be used
during application development.
Variable Type
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form of
a variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated
list.
Following are valid examples of variable declaration and initialization in Java −

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'
This chapter will explain various variable types available in Java Language. There are
three kinds of variables in Java −
 Local variables
 Instance variables
 Class/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.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.
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();
}
}
This will produce the following result −
Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the time
of compilation.
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
This will produce the following error while compiling it −
Output
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error

CLASS INSTANCE CREATION EXPRESSION or OBJECT CREATION


EXPRESSION
e.g. Test test = new Test();

Keyword new creates a new object (test as in the above example) of the class
specified to the right of the new keyword (Test as in the above example). The
parentheses – () – to the right of the name of the class are required. Those
parentheses in combination with a class name represent a call to a constructor, which
is similar to a method, but is used only at the time an object is created, to initialize the
object's data. Constructors are special methods that are used for initializing objects
when they are created.
Each new class you create becomes a new type in Java that can be used to declare
variables and create objects. Programmers can declare new class types as needed;
this is one reason why Java is known as an extensible language.

Variables declared inside a method are not visible to any other member of that class or
outside that class. Such variables are termed local variables.

Typically, you cannot call a method that belongs to another class until you create an
object of that class

A static method is special because it can be called without first creating an object of
the class in which the method is declared.

Instance Variables

 Instance variables are declared inside a class, and usually immediately after the
class definition header, but outside any method, constructor or any block.
 Instance variables can be declared in class level before or after use.
 Each object of the class will have its own set of variables – instance variables that
represent the current state of the object and methods that defines the task that
object can perform.
 Access modifiers can be given for instance variables.
 The access modifier is used to ensure that each object maintains it own set of
variables and thus not visible to any other object of the class or any other class.
 Instance variables are visible to all members of the class, but not to members of
another class.
 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.
 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.
 To enable other classes to access instance variables in order to reflect a change in
the state of the objects we use public service methods – set and get – methods to
facilitate this through a well defined mechanism. The set methods enables changes
while get methods gives the current state of the object
Example
import java.io.*;
public class Employee {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This will produce the following result −
Output
name : Ransika
salary :1000.0

Class/Static Variables

 Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final, and static. Constant variables
never change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. 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. Additionally, values can be
assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class
name ClassName.VariableName.
 When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final, the
naming syntax is the same as instance and local variables.
Example
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);
}
}
This will produce the following result −
Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be
accessed as Employee.DEPARTMENT

What is Next?

You already have used access modifiers (public & private) in this chapter. The next
chapter will explain Access Modifiers and Non-Access Modifiers in detail.

Java Access Modifiers – Public, Private, Protected & Default


You must have seen public, private and protected keywords while practising java programs,
these are called access modifiers. An access modifier restricts the access of a class, constructor,
data member and method in another class. In java we have four access modifiers:
1. default
2. private
3. protected
4. public
1. Default access modifier
When we do not mention any access modifier, it is called default access modifier. The scope of
this modifier is limited to the package only. This means that if we have a class with the default
access modifier in a package, only those classes that are in this package can access this class.
No other class outside this package can access this class. Similarly, if we have a default method
or data member in a class, it would not be visible in the class of another package. Lets see an
example to understand this:
Default Access Modifier Example in Java
To understand this example, you must have the knowledge of packages in java.
In this example we have two classes, Test class is trying to access the default method of
Addition class, since class Test belongs to a different package, this program would throw
compilation error, because the scope of default modifier is limited to the same package in
which it is declared.
Addition.java
package abcpackage;

public class Addition {


/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java
package xyzpackage;

/* We are importing the abcpackage


* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
The method addTwoNumbers(int, int) from the type Addition is not
visible
at xyzpackage.Test.main(Test.java:12)
2. Private access modifier
The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from outside
of the class.

Let’s see an example to understand this:


Private access modifier example in java
This example throws compilation error because we are trying to access the private data member
and method of class ABC in the class Example. The private data member and method are only
accessible within the class.
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
Compile - time error
3. Protected Access Modifier
Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is
similar to default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.
Protected access modifier example in Java
In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class
extends class Addition and the protected modifier allows the access of protected members in
subclasses (in any packages).
Addition.java
package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}
Test.java
package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:
33
4. Public access modifier
The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.
public access modifier example in java
Lets take the same example that we have seen above but this time the method
addTwoNumbers() has public modifier and class Test is able to access this method without
even extending the Addition class. This is because public modifier has visibility everywhere.
Addition.java

package abcpackage;

public class Addition {

public int addTwoNumbers(int a, int b){


return a+b;
}
}
Test.java

package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:
101

Scope
access
modifiers Class Package Subclass Subclass Outside
(samepackage) (diffpackage) Class
Public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes No
default Yes Yes Yes No No
private Yes No No No No

Methods and Constructors a Deeper Look


As we earlier mentioned, methods are used for specifying the tasks that objects of the class can
perform. Constructors are special methods that are used for initializing objects when they are
created. In order to see the differences between the constructors and regular (non-constructor)
methods, we have presented below the structure of a method:

accessModifer returnType methodName( parameterList )


{
statements
return statement
}
Where:
accessModifer (access modifier) specifies the visibility of the method to other classes –
the access modifier may be specified public or private. Public specifies that the method is
visible to other classes “that is visible to the public” while private is the exact opposite. Private
methods cannot be accessed outside the class from which it is defined and thus it cannot be
inherited.
returnType specifies the “nature” of the value the method gives back to its calling method
(if any) when it completes its task. The return type could a primitive type value or reference
type value as the case may be.
methodName (method name) is an identifier used to make reference to the method.
parameterList is an optional list of identifiers representing the values (arguments) to be
passed into the method. The parameters –often referred to as formal parameters – are used by
methods in carrying out of their tasks. They must have a type followed by an
identifier. Several parameters must be separated using commas.
statements – instructions that enable the method to carry out its tasks.
return statement is used to return (send) data back to the calling method. When the
return statement is implemented without a value following it, then the returnType must be
specified as void.

Both regular methods and constructors are permitted to have parameters (formal parameters).
Note: values passed into methods and constructors are referred to as actual parameters which
are copies of the actual data except when the data are of type reference.
Differences between Methods and Constructors
a. Constructors must have the same name as the class - both in capitalization and in
sequence - in which it is declared.
b. Constructors do not have a return type in its method definition header.
c. The return statement is not required.
d. Constructors are only executed when an object is created, they may not be invoked if
the state of the object alters. In such a situation that the state of the object changes,
public service methods will be required to assist in reflecting the change.
e. Constructors may not be declared as static as they are involved in the creation and
initialization of the objects themselves.

You might also like