Notes On Java August 2024
Notes On Java August 2024
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.
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.
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:
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.
Why JVM?
Here are the important reasons of using JVM:
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.
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.
/*
* This is a simple Java program
* Call this file Example.java
*/
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
****************************************************************
*/
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.
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:
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.
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.
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.
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:\>) type: java Example. (You need not type the .class extension)
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
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)
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
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,
Java has other types in addition to the primitive types, but all the other types represent
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.
with a linefeed at the end, you would have to type the string literal:
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.
*/
/* Do the computations. */
principal = 17000;
rate = 0.07;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
} // end of main()
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.
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;
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.
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
• 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:
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
Output:
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;
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)
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,
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
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.
with a linefeed at the end, you would have to type the string literal:
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 {
/* Do the computations. */
principal = 17000;
rate = 0.07;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
} // end of main()
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";
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
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.
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) {
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.
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
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(~)
//increment
num1++;
//decrement
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;
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");
}
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[]) {
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 {
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
Operators Precedence
Unary
++ – – ! ~
Operators
Multiplicative * /%
Additive + –
Equality == !=
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Ternary ?:
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;
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 {
char ch = 'P';
int asciiCode = ch;
// type casting char as int
int asciiValue = (int)ch;
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
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
Local Variables
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 {
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 {
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
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.
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.
package abcpackage;
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
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.