(@DeveloperVibes) Chapter
(@DeveloperVibes) Chapter
n Introduction
n Java Program Structure
n Simple Java Program
n Tokens
n Java Statements
n Java Virtual Machine
n Constants and Variables
n Declaration of Variables
n Scope of Variables
n Data types
n Symbolic Constants
n Type Casting
n command line arguments
INTRODUCTION
The Java Programming Language is a general-purpose, concurrent, strongly typed,
class-based object-oriented language. It is normally compiled to the bytecode in-
struction set defined in the Java Virtual Machine Specification. Here in this chapter
you will learn about key features of Java that is how to create a simple Java
program, explaining each & every concept associated with a Java program where
to declare class, package, interface, main method, how to compile and execute it.
You will observe that most of the program used in this book to explain various
concepts, do not accept input from keyboard. This is because in Java accepting
input from user requires use of InputStream classes (that you will study later). So
at this stage in order to understand and implement concepts of Java, we will be
using programs that can display outputs on the basis of predefined conditions and 17
Programming with Java values. This chapter also tells you about tokens, constants, variables, data types.
You will also learn about how to declare variables, how to initialize them, how to
declare constants, types of constants, scope of variables etc.
Basically this chapter deals with basic concepts of Java programming.
NOTES
JAVA PROGRAM STRUCTURE
Definition: Java Program Structure means the way or general form to write a
Java Program. It defines structure of a Java program
At this stage you are well aware of the basic concept of Java, fundamental of
OOPs, so now its time to write Java programs. So let’s begin with program struc-
ture of Java.
Document Section // Suggested
Package package-name //optional
import [Link] or * //optional
//Class declaration
class Class-name //optional
{
Type var-name; //Variable declaration
Type var-name;
// method defination
return-type method( parameter list )
{
Body of method
}
}
// interface declaration
access interface name // optional
{
Return-type method name( parameter list);
Return-type method name( parameter list);
Type final var1= value;
}
// main() method class
class Class-name1 //essential part
{
// call to main method
public static void main( String args [] )
{
// Object Creation
// body of method
}
}
Java program structure begins with a line:
Document Section
In this section you can write comments. Comments are very helpful for users as they
18 help them in understanding the code. They are optional but this is suggested that you
should write them as they are used to explain the operation of program. Key Features of Java
Package package-name
This means here you can create package with any name. Package is the group of
classes defined under one name. So if you want to declare so many classes under
NOTES
one root then you can declare them inside a package. This is optional part means
if you don’t want to declare then don’t worry go ahead, you will not get any error.
Here package is the keyword that tells to the compiler that a package is going to
be created. Package-name is any name given to the package, any name like abc,
root, pkg1, area etc. Remember it should not be the name of any keyword. Any
class declared inside a package will be accessed in correspondence with its pack-
age name.
Third line of code says:
import [Link] or *
This line indicates that if you want to use classes of any other package, then you
can access them directly by importing them into your program. You can import them
in your program by using import and then giving the package name followed by
class name. Here pkg1 and pkg2 are name of package. If you want to import entire
package then write *, otherwise if you want to import some specific class then write
name of class. Technically, it is not required to write this statement to complete the
program so again this is optional.
Then comes class definition, here you will specify the variables and methods that will
be used in the program. This is not the main class as it does not contain main( )
method. Again this class is optional. Details about class declaration you will read in
Classes Chapter. Here class-name is the name of class, type is data type of variable,
return type is type of data that method will return and parameter list is a sequence
of values separated by comma.
Then you can declare interface. Interfaces are similar to classes but their methods
do not have body and it can define only constant variable. access specifies the
scope up to which interface can be implemented, name is name given to interface.
Again this is optional, you can omit this block.
The most important thing that you need to include in a Java program is class
containing main method. The next block declares a class that contains main( )
method. It is a class where you can create objects of other class also in order to
access their members.
A very important thing to remember try to keep the name of program as the name
of class having main( ) method. Reason, very soon in the next topic you will get the
answer.
This is the general structure to write a Java program. Now let us understand it by
using a simple program.
SIMPLE JAVA PROGRAM
So after learning structure of Java program, now let us write a simple program
that will display a name.
Program to display a name
19
// A simple Java Program
Programming with Java // Name of this file will be "[Link]"
}
}
OUTPUT
My name is Nandini
The first and very important thing to keep in mind about Java program is that in Java
name of the file that contain main() method is very important. So in Java the name
you gave to the class (that contains main() method) is the name of the Java Program.
It means the name which you gave to the Class containing main method is the main
Class and that name will be served as Filename.
Like in the given program name of the class containing main( ) is Name, so the name
of this file will be “[Link]”. But while writing name of file, you should be
careful about case. It should match with class name as Java is case-sensitive.
In Java the file that contains main() method is termed as compilation unit. The Java
compiler requires that a source file uses the .java as file extension. The reason for
giving same name to class containing main() method and file is that when source
code of Java is compiled, then all classes of that Java program are compiled and
each of the class is separately put into its output file. Output file of each class is
named after its name and using .class extension. So in this way name of source file
match the name of .class file. Here actually by following this concept for naming a
file, you are specifying the name of the class you want the interpreter to execute.
So at the time of execution, the interpreter will search for the file by that name that
has the .class extension. If it finds the file then it executes the code contained in that
specified class. If a program contains two classes and we write filename as name
of class not containing main() method. Then no doubt program will be compiled and
will create two class files. But if we want to run the program, we need to write name
of class containing main() method. So this naming convention arise need to remem-
ber two class names, one that we used to save file and other which contains main()
method. Sometimes this can create confusion. So to remove this confusion, you are
suggested to write name of file as name of class containing main() method.
The program as you have seen starts with these lines.
// A simple Java Program
// Name of this file will be “[Link]”
These lines are called comments in a program. Comment is actually a method that
is included in the program in order to explain the operation of the program. Com-
20 ments are used to explain some specific part of program i.e. what it is doing or to
describe function of some feature. These comments are helpful to all persons read-
ing this program. Whatever you write as comments in a program all that is ignored Key Features of Java
by the compiler. So they are just added to make the program easy to understand.
Here these lines tells, it is a very simple example of Java program and its name
should be “[Link]” as name of class containing main() method is Name. All
NOTES
comments used in the program are used to describe the functions of each feature
included.
Java supports three types of comments. They are:
Single-line Comment
Multiline Comment
Documentation Comment
Single-line Comment
This is a comment used for brief remarks, line by line. As the name suggests,
they are used if you want to write a single line as comment. They are preceded
by // sign and ends at the end of the line.
For example,
// This is the starting
Multiline Comment
Multiline Comments are used for longer remarks. These can be of several lines.
They begins with /* and ends with */.
For example,
/* This is the starting program.
It will help you to begin Java programming. */
Documentation Comment
This type of comment is used to produce HTML file that documents your
program. The documentation comment begins with a /** and ends with */.
For example:
/**
* this city is good.
* said by great persons
* in 1990
* @ citynews
*/
The next line of code is declaration of Class name.
class Name
Here you will use class keyword to declare the name of new class and to inform
the compiler that it is the class name. Name is an identifier (you will learn about
identifier in next section) and is the class name. The entire class members are kept
under curly braces { }. Whatever you want to define, you need to define under
these braces.
21
Programming with Java Now the next line of code:
public static void main( String args [] )
From here main( ) method starts. This is the line from where program begins its
execution. All programs in Java begin by calling main( ) method.
NOTES
Let’s start understanding each keyword used in this line.
public: This keyword is an access specifier. When a class member is preceded by
public then it means its members can be accessed by code outside its class. When
main( ) is declared public then it means that it can be used by code outside its class.
This is the reason why main( ) is declared public.
static: This keyword is used when we want to access a method without creating
its object. So as we are calling main( ) before making any objects of its class.
void: void tells that a method does not return a value. main( ) is declared void
because it does not return any value.
String args []: When a method is called, values are passed, the variables who
receive those values with in the set of parentheses are called parameters. Any
information which you want to pass to a method is received by parameters. A
method may or may not have parameters. If there are no parameters then still you
are required to include the empty parentheses.
In main there is one parameter called String args[]. It means it is a parameter named
args which is an array(collection of similar things) of objects of class String. Well
String class is a class that contains method for string operations. And then we are
making objects of String and that too a collection means many in number. That’s
why we are making it an array and giving it a name args. Object of String type store
strings. args will receive command line argument when program is executed.
As you know Java is case-sensitive. So be careful while writing main( ). Don’t write
it as Main( ) because though Java will compile all classes included in the program
still it will run only that class that will contain main( ). So if you write Main( ) instead
of main( ) then it will compile but will not run and will give a runtime error.
{ braces means the start of main( ) method body. Anything written inside { } braces
belong to main method. One more point to keep in mind is that Java may have
many classes in a program but only one class will have main( ) method.
The next line of code is:
[Link](“My name is Nandini”);
This line will produce output My name is Nandini on screen.
System is a predefined class and out is the output stream that display output on
console. out is actually an object of Printwriter Class defined in System. println()
is actually a method to display output on screen. It displays the string passed to it
followed by a new line on the screen. You can also use print() for displaying output.
The difference is that println() gives a new line on the screen while print() does not
provide this facility. Anything that you want to display on screen, it should be written
inside double quotes i.e. between " ".
println statement ends with a semicolon. This is because all statements in Java end
22
with a semicolon. The first } braces means end of main( ) method and second one
means the end of Class.
Compiling and Running Java Program Key Features of Java
To compile the Name program, execute the Java Compiler, javac, specifying the
name of the main file. So you will write the command on Command Prompt as:
C:/> javac [Link] NOTES
The javac compiler creates a file called [Link]. This file contains the bytecode
of the program. This bytecode contains instructions that are executed by Java
interpreter. So the output that is produced by javac is bytecode not the code that
can be directly executed.
So in order to run the program, you will use Java interpreter called java. To run
the program you will write :
C:/> java classname (main class)
Now output will be displayed.
TOKENS
Definition : Tokens are the smallest individual units in a program.
When we write a program then we require various important things. We require
tokens, white spaces, and syntax of language.
Various Tokens which are used are:
Keywords
Identifiers
Literals
Operators
Separators
White space
Keywords
Keywords are the words whose meaning has already been defined to Java
compiler. They convey special meaning to the compiler. They cannot be used
as variable name, class name or any method name because if we are doing this
then we are assigning new meaning to the keyword. They are also called as
reserved words as there name is reserved and cannot be used for any other
purpose. The keywords that are reserved by Java language are:
abstract- It specifies that a class or method will be implemented later in any
subclass.
boolean- A data type that can hold True and False values only.
break- A control statement for breaking out of loops.
byte- A data type that can hold 8-bit data values.
case- Used in switch statements to indicate blocks of text.
catch- Catches exceptions generated by try statements.
char- A data type that can hold 16-bit character values.
class- To declare a new class. 23
Programming with Java continue- Take the control to the beginning of loop.
default- Specifies the default block of code in switch statement.
do- Starts a do-while loop.
NOTES double- A data type that can hold 64-bit floating point values.
else- It indicate a alternative in if statement.
extends- It indicate that a class is derived from another class.
final- Indicates a variable holds a constant value or a method will not be
overridden.
finally- Indicates a block of code in a try-catch structure that will always
be executed.
float- A data type that can hold 32-bit floating point values.
for- To start a for loop.
if- Test whether a statement is true or false.
implements- It specifies that a class implements an interface.
import- To refer to other classes.
instanceof- Indicates whether an object is an instance of a specific class or
implements a specific interface.
int- A data type that can hold 32-bit integer values.
interface- Declares an interface.
long- A data type that can hold 64-bit integer values.
native- indicates that a method is implemented with native(platform-spe-
cific) code.
new- Creates new objects.
null- Indicates that a reference does not refer to anything.
package- Declares a Java package.
private- An access specifier indicates that a method or variable may be
accessed only by the members of class in which they are declared.
protected- An access specifier indicates that a method or variable may be
accessed only by the members of class in which they are declared or by
members of its subclass.
public- An access specifier indicates that a method or variable may be
accessed outside the class in which they are declared.
return- Return value to the calling method.
short- A data type that can hold 16-bit integer values.
static- To access a method without creating its object.
super- Refers to base Class.
switch- A statement that executes code based on test value.
synchronized- Specifies critical sections or methods in multithreaded code.
this- Refers to the current object.
24 throw- Creates an exception.
throws- Indicates what exceptions may be thrown by a method Key Features of Java
transient- Specifies that a variable is not part of an object’s persistent state.
try- Starts a block of code that will be tested for exceptions.
void- Specifies that a method does not return a value. NOTES
volatile- Indicates that a variable may change asynchronously.
while- Starts a while loop.
Identifiers
Identifier refers to the name of variables, functions, array, classes created by
programmer. Some points to be kept in mind in order to define names:
An identifier is a sequence of uppercase and lowercase letters, numbers or
the underscore and dollar sign characters.
The name cannot start with a number.
As Java is case-sensitive, uppercase and lowercase letters are distinct. It
means in Java sum and SUM is different.
Example: length, name, Marks, HEIGHT, $money, hra4.
Some invalid identifiers are: 2value, avg-temp, run/time.
Literals
Literals refer to fixed values that do not change during the execution of a
program. There are four types of literals in Java. They are:
Integer Literals
Floating-point Literals
Character Literals
String Literals
Example:
100 ::::::::::: Integer Constant
98.6 ::::::::::: Floating Point Constant
‘X’ ::::::::::: Character Constant
“This is a string” ::::::::::: String Constant
They can be used anywhere in the program.
Operators
They are tokens that perform some computation when applied to variables. Java
has a rich set of operators. Various types of operators that Java provides are:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Increment and Decrement Operators
Conditional Operators 25
Special Operators
Programming with Java We will discuss about operators in next chapter.
Separators
Separators are symbols that are used to define the structure of a program.
NOTES In Java the various separators used are:
Symbol Name Purpose
() Parentheses contain list of parameters
{} Braces define blocks
[] Brackets declare Arrays
; Semicolon terminates statements
, Comma separates consecutive
identifiers
White space:
As you know Java is a free form language so you can write anywhere i.e. no
need to follow any special indentation rules. So you can write even the whole
program in one single line but one white space is required between each token.
White space in Java means space or tab or new line. White space improves
readability by setting off sections of code that are logically related.
White spaces should be used in the following circumstances:
A keyword followed by a parenthesis should be separated by a space.
Example:
while (true) {
...
}
Note that a blank space should not be used between a method name and
its opening parenthesis. This helps to distinguish keywords from method
calls.
A blank space should appear after commas in argument lists.
All binary operators should be separated from their operands by spaces.
Blank spaces should never separate unary operators such as unary minus,
increment (“++”), and decrement (“—”) from their operands. Example:
a += c + d;
a = (a + b) / (c * d);
while (d++ = s++)
{
n++;
}
The expressions in for statement should be separated by blank spaces.
Example:
for (expr1; expr2; expr3)
26 In spite of space there are four other white space characters in Java. They
are: the horizontal tab, the form feed, the carriage return, and the linefeed.
All literals in Java treat all types of white space as same but in case of string Key Features of Java
literal only space character is used. Carriage returns, tabs, line feeds and
form feeds must be inserted with special escape sequences like \r, \t, \f, and
\n. You cannot break a String across a line like this:
NOTES
String nature = “The four seasons, have their own
charm and beauty...each one is incomplete
without the other....here the beauty of winter
is depicted, the joy that it creates, when it sets in.......”;
Instead you must use \n and the string concatenation operator, +, like this:
String nature = “The four seasons, have their own \n” +
“ charm and beauty...each one is incomplete \n” +
“ without the other....here the beauty of winter \n” +
is depicted, the joy that it creates, when it sets in.......”;
Note that you can break a statement across multiple lines; you just can’t break
a String literal.
JAVA STATEMENTS
Definition: Statement is the instruction that you write in a program in order to
state something.
Statement means the act of stating something. In a program we write statement
when we want to perform some actions. Each instruction in a program is written as
separate statement. So you can say a complete program is a series of statements.
You must write statements in the order you want them to execute. Blank spaces may
be inserted between two words of a statement while it is not allowed in keywords,
constants and variables names.
All statements are written in small case letters. No rules are specified for the position
of statements in the program.
Most important thing about statement is that they must end with a semicolon ( ; ).
Semicolon acts as a statement terminator.
In Java, if a statement does not include semicolon at the end then technically they
are not considered as statements. If you use any other symbol other than semicolon
at the end of the statement; then the Java compiler refuses to translate your code
into bytecode.
Example:
[Link](“this is a statement”);
There are three types of statements. They are
l Type declaration Statement - To declare the type of variables used in a
program i.e. whether it will contain integers, floating point numbers or any other.
l Arithmetic Statement - To perform arithmetic operations between constants
and variables.
l Control Statement – To control sequence of execution of various statements
27
in a program. There are four types of Control Statements :
Programming with Java Sequence Control Statement
Decision or Selection Control Statement
Repetition or Loop Control Statement
NOTES Case Control Statement
Sequence Control statement are statement that are to be executed in sequence.
They are simple statements.
Decision or Selection Control statements are statements that are executed on the
basis of some condition.
It include if statement, if-then-else statement, nested if-else statement.
Repetition or Loop control Statements are those that are repeated a number of
times. It include for loop, while loop, do-while loop.
Case Control Statement uses Switch case for execution of statement.
You will study details about statements in 4th chapter.
JAVA VIRTUAL MACHINE
When we compile a Java program, then the compiler produces the bytecode.
Bytecode is actually a code that can be used to run on any platform. JVM or Java
Virtual Machine is a virtual machine that contains bytecode. It is not a real machine
and it resides inside memory. Bytecode is not machine code. It is converted into
machine code by the use of interpreter. So interpreter acts as an intermediary
between JVM and real machine.
The JVM is the important component of the Java Platform. With JVM, you need
not to write the program again and again what you need is just the bytecode and
JVM installed on that machine and this way you will able to execute the programs.
JVM is different for different types of platforms. The use of the same bytecode for
all platforms allows Java to be described as “compile once, run anywhere”, as
opposed to “write once, compile anywhere”, which describes cross-platform com-
piled languages
A program may consists of many classes in different files. JVM first read the .class
file (containing bytecode produce from source code) that is generated from compiler
then interpreter converts it into machine code. It converts it into low level instruc-
tions according to the platform on which it was supposed to run. These low level
instructions are then executed and you get the desired output.
So working of JVM can be described as:
u Reading the bytecode
u Verifying the bytecode
u Linking the code with library
The JVM, which is apart of the JRE (Java Runtime Environment), comes into
action when a Java program is executed. JIT (Just In Time) is the part of the JVM
that is used to speed up the execution. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed
28 for compilation.
Given diagram shows you overall working. Key Features of Java
NOTES
The JVM is distributed along with a set of standard class libraries that implement
the Java API (Application Programming Interface). An application programming
interface is what a computer system, library or application provides in order to allow
data exchange between them. API provides you with sets of classes. You can use
these classes to build application programs & applets. Java and API are bundled
together as the Java Runtime Environment.
Running Java programs with the JVM rather than downloading full program provide
you advantage of security to your system. As when Java executes the program, the
JVM monitors all procedure itself. By watching all program, it take care of any
unexpected thing happening in the program. By this way it does not let any malicious
program or virus being entered into your machine. JVM provides a very important
advantage to your system by ensuring security.
CONSTANTS AND VARIABLES
Definition: A Constant is an entity that does not change while Variable is an
entity that may change.
Letters, numbers and special symbols together create keywords, variable and iden-
tifiers. In any Java program we perform operations like addition, subtraction, mul-
tiplication, division or any other. For all these operations, we require some values Check Your Progress:
to be stored somewhere and also the result of these calculations require place in 1. Which types of com-
memory for storage. ments does java
Memory in computers consists of millions of cells just like a human memory. Memory Support?
cells are allocated to the values as per the requirement of the values. Every cell is 2. Define Java state-
assigned a memory address. Now in order to use these values, you need to access ments.
the memory location. But it is very difficult to remember memory address and
access the memory location.
29
Programming with Java To make the retrieval and usage of these values easy these memory cells are given
names. So memory is now referred to as names. There is one advantage you can
change the name given to the memory location. So the name given to the memory
location in which it is stored is called variable name. As it may vary, so it is variable
NOTES while constants are the values that do not change.
For example:
Let us consider we store a value 5 in a memory location and give it a name value;
so 5 get stored in memory with name value like this :
Value 5
Value= 5
Now we assign a new value 25 to value, so it will now overwrite the earlier value
5, since memory location can hold one value at a time.
So here location whose name is value can hold different values at different
times, it may vary as per user requirement, is known as a variable. While 5 or
25 will not change, hence are known as constants.
Program : showing variable and constant
// A Program that shows variable and constant
// Name of this file will be "[Link]"
long a = 765432123456789L;
[Link]("Number ="+a);
}
}
OUTPUT
31
Number= 765432123456789
Programming with Java You need to append L at the end of long type of integer constant.
There are three types of integer in Java.
Decimal integer constant (base 10)
NOTES Octal integer constant (base 8)
Hexadecimal integer constant (base 16)
Decimal integer constant
A decimal integer constant consists of a sequence of digits which begins with
any number other than 0.
For example: 23, 345, -34, +2
Octal integer constant
An octal integer constant consists of a sequence of digits which begins with
0.
For example: 12 will be represented as 014
Hexadecimal integer constant
A hexadecimal integer constant consists of a sequence of digits which begin
with 0X or 0x.
For example: 22 will be represented as 0X16
Floating-point Constants:
Definition : Floating-point constants are numbers with fractional part. They
represent numbers with decimal values with a fractional component. They are
also called real numbers.
It has two forms:
Standard notation or Fractional form
Scientific notation or Exponential form
Standard notation or Fractional form
A real constant in fractional form consists of digits including a decimal point between
them.
There are several rules for writing fractional form constants:
1. A real constant must have at least one digit.
2. It must have decimal point.
3. It can be either positive or negative.
4. No commas or blanks are allowed with in a real constant.
5. A number with no sign is assumed to be positive.
For example:
2.4, 4.5, 34.98, -0.098
Scientific notation or Exponential form
A real constant in exponential form has two parts: mantissa and an exponent. The
mantissa must be either an integer or a proper real constant. The mantissa is fol-
32 lowed by a letter E or e and the exponent.
There are several rules for writing exponential form constants: Key Features of Java
1. The mantissa part and exponent should be separated by a letter e or E.
2. The exponent must have at least one digit, which must be a positive or
negative integer. Default sign is positive. NOTES
3. The mantissa can be either positive or negative.
4. Default sign of mantissa is assumed to be positive.
For example:
+3.2e-5, 4.6e8, 0.5e9
A Program showing Real constant by using float
// Name of this file will be "[Link]"
You need to append f at the end of float type of floating-point constant. This is
because default type of floating-point constant is double. So you need to write f at
the end if you are using float.
Character constants:
Definition: Character constant is one character enclosed in single quotes.
They are 16-bit values that can be converted into integers. You can also perform
operations like addition, subtraction on them as on integers. Some of the ASCII
characters that cannot be entered directly, can be entered through escape sequence
such as ‘\n’ for newline character.
For example: ‘a’, ‘f’, ‘s’, ‘g’
Program showing use of character constant
// Name of this file will be "[Link]"
class Show //Class declaration
{
// call to main function
public static void main(String args[])
{
char val1; 33
val1= 66; //specify val1
Programming with Java [Link]("character=" +val1);
}
}
OUTPUT
NOTES
character = B
The table given below shows escape sequence of some characters
Escape Sequence Meaning
\ddd Octal character
\uxxxx Hexadecimal character
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n Newline character
\f Formfeed
\t Tab
\b Backspace
Table : Escape sequence of charac-
ters
Boolean constants
There are two values that a boolean constant can have. They are either true or false.
It does not contain numeric values 0 and 1. These values can only be assigned to
boolean variables.
Let’s see a program that uses Boolean constant.
Program showing use of Boolean constant
// Name of this file will be "[Link]"
Name syntax Standard rules. Standard rules. static public final variables
(constants) are all upper
case, otherwise normal
naming conventions.
It will give you zero as output because we have not initialized r, but r is automatically
initialized to zero as it is an instance variable so it automatically gives you 0.0 as
output.
DECLARATION OF VARIABLES
Definition: Declaration of variable means telling what type of data it will store.
As we know variables represent named storage locations whose values can be
manipulated during program run. It is the basic unit of storage in a Java program.
All variables must be declared before they are used. The general form of a variable
declaration is:
Type variable name
Here type means the data type. It tells what type of data variable will contain
whether integer, character or float. Variable name is the name of variable. Value is
any constant stored in this named location.
A variable in Java can store two kinds of values:
Java primitive type values
Java’s primitive types are
integers (whole numbers, declared as byte, short, int, or long; only int need
be of interest to a beginner)
floating-point numbers (decimal numbers, declared as float or double; only
float need be of interest at first)
characters (declared as char, representing one character like ‘A’ or ‘,’)
boolean (holding only true or false as values).
For example:
int a, sum=56; declaring integer variable
float marks, total; declaring float variable
char c = ‘r’; declaring character variable
double radius; declaring double variable
boolean h; declaring boolean variable
a reference to a Java object: It means creating variables of class type that can
37
store reference to class members. This you will study in 'Classes' chapter.
Programming with Java Initialization of Variables
Initilaization means giving values to variables. In Java you can initialize a variable in
two ways
NOTES Static Dynamic
Static means memory is allocated to all variables when program is started. So you
need to initialize them at starting only.
Dynamic means in Java you can declare variables anywhere in the program because
memory is allocated to them when statement belonging to that variable is executed.
Lets understand this concept by use of a program.
Program showing initialization of variables
// Name of this file will be "[Link]"
class Show //Class declaration
{
public static void main( String args [] )
{
int a= 3;
int b=4;
[Link]("sum of two number");
// sum is dynamically initialized
int sum= a+b;
[Link]("sum="+sum);
}
}
OUTPUT
sum of two number
sum= 7
Here sum variable is dynamically initialized while a and b are static variables.
SCOPE OF VARIABLES
Definition: Scope of variable means the extent to which a variable can be used.
All variable have a scope. It determines the value of variable will be available up
to what parts of program. As Java supports dynamic initialization, variable can be
declared at any place. You can declare variable with in a block also. A block begins
with { and ends with }. It defines scope of variable. For a new block , you are
assigning a new scope to variable. In Java we don’t have local and global variables.
In Java scope is determined through blocks. Variable defined inside a block is not
accessed by a code outside the block. So its scope will be inside that block. When
you are declaring a variable with in a scope then you are localizing that variable.
When we determine a variable inside a block then we are protecting it from unau-
thorized access.
Program given below will show you how variable works inside blocks. Here I have
38 used if-then statement that is used as control statement. You will study about if then
statement in next chapter.
Program showing block scope of variable Key Features of Java
40
// Name of this file will be "[Link]"
class Calc //Class declaration
{ Key Features of Java
// call to main function
public static void main( String args [] )
{
int distance; NOTES
int speed;
int time;
speed = 160; //specify speed
time = 20; //specify time
// calculate distance
distance = speed * time;
[Link]("Distance=" +distance);
[Link]("meters");
}
}
OUTPUT
Distance= 3200meters
Now let’s see this program using long data type.
Program showing use of long
// Name of this file will be "[Link]"
class Calc //Class declaration
{
// call to main function
public static void main( String args [] )
{
long distance;
long speed;
long time;
speed = 169850000; //specify speed
time = 2000000; //specify time
// calculate distance
distance = speed * time;
[Link]("Distance=" +distance);
[Link](" meters");
}
}
OUTPUT
Distance= 339700000000000 meters
As you can see, output of program is large, it could not be held in int data type so
we use long data type
Floating-point numbers :
Floating-point numbers are used when we want to calculate some fractional value.
They are also called as real numbers. They are required for calculation of trigonom-
etry, to find square root as result of these type of calculations are fractional numbers.
41
Programming with Java There are two types of floating-point types:
float double
float : It is a data type of 4 byte i.e. 32 bits. It has range from 1.4e-045 to 3.4e+038.
NOTES Decimal point indicates that given number is floating-point number. float data type is
used when you need fractional number. It specifies a single precision value.
For example:
float radius, area;
double: It is a data type of 8 byte i.e. 64 bits which specifies double precision
value. It stores floating-point numbers with much larger range. It has range from
4.9e-324 to 1.8e+308.
For example:
double area, radius;
Program showing use of float and double
// Name of this file will be "[Link]"
class Calc //Class declaration
{
// call to main function
public static void main( String args [] )
{
float length;
float breadth;
double area;
length = 2.4f; //specify length
breadth = 1.5f; //specify breath
// compute area
area = length * breadth;
[Link]("Area =" +area);
}
}
OUTPUT
Area= 3.6000001430511475
Characters :
In Java characters are represented by char data type. It is of 16 bits and has range
from 0 to 65,536. It means there are no negative chars. Java uses Unicode to
represent characters. Unicode defines a fully international character set that repre-
sents all of the characters found in all human languages. This is the reason why it
requires 16 bits.
For example:
char val;
Program showing use of char
42 // Name of this file will be "[Link]"
class Calc //Class declaration
{ Key Features of Java
// call to main function
public static void main( String args [] )
{
NOTES
char val,val1;
val='A'; //specify val
val1=66; //specify val1
[Link]("val=" +val);
[Link]("val1=" +val1);
}
}
OUTPUT
val= A
val1= B
Here val1 is assigned the value 66 which is the ASCII and Unicode value that
correspond to the letter ‘B’. Even though chars are not integers they behave as
subset of integers. So you can add them and increment the value of character.
For Example:
In the above program if you would have write val++ and then print its value. Then
also it would have given B as output.
Boolean :
Boolean has logical values. It has two values true or false. When you use boolean
as datatype then it results in one of the two values.
For example:
boolean a;
Program showing use of boolean
// Name of this file will be "[Link]"
class Calc //Class declaration
{
// call to main function
public static void main( String args [] )
{
boolean a; Check Your Progress:
a = true; //specify a 3. Define Data types.
[Link]("a is" +a); 4. Floating Point Num-
a = false; //specify a bers.
[Link]("a is" +a);
}
} 43
Programming with Java OUTPUT
a is true
a is false
SYMBOLIC CONSTANTS
Java supports the use of various types of constants, such as integers (5, 2), floating
point numbers (2.5, 6.022e+23), characters (‘a’, ‘\n’), booleans (‘true’, ‘false’),
and strings (“Hello”). Extensive use of constants within a program can lead to two
problems: first, the meaning of the constant is often unclear from the context and
second, if we want to change contents of constant then it requires the entire program
source code to be searched for occurrences of that literal, which can sometimes
lead to error if any of occurrence of constant is ignored.
A solution to this problem is to declare meaningfully-named constants as class
variables. Their values should be set to the desired constant, and we should use the
name of constant throughout the program rather than writing constant value every-
where. The advantages to this approach are that the constant’s name can clearly
indicate its meaning or intended use, and should the constant need to be changed,
its declaration can be modified without having to search the entire code for all its
occurrences.
The final keyword in Java is used to declare constants. Symbolic Constants are
always written in capital letters.
Attempting to change the value of final-qualified variable results in a compile-time
error.
For example:
final int VAL=5;
here VAL will not occupy memory on a per-instance basis. Thus it is a constant.
Program showing use of final
// Name of this file will be "[Link]"
Here compiler will give you an error that you can’t assign value to a final variable.
TYPE CASTING
It is very common to assign a value of one type to a variable of another type. If
the two variables are compatible then Java compiler will automatically convert them.
For example: if you want to assign an int value to a long variable or a float value
to double then this conversion is compatible. So compiler will automatically convert
it. But if you want to convert double into byte then it can’t be possible. For this is
an incompatible type. Java defines a method for explicit conversion also.
There are two types of conversions or casting in Java.
Automatic Conversions or implicit conversion
Explicit Conversions
Automatic Conversions (Implicit Conversion)
One type of data can be assigned to another type when they satisfied two condi-
tions:
The two types are compatible.
The destination type is larger than source type.
This way Java can perform automatic conversion if two conditions are satisfied.
Numeric types are not compatible with char and boolean. Integer and floating type
are compatible with each other.
char and boolean are not compatible with each other.
Explicit Conversions
This is performed when you want to create a conversion between incompatible
types such as int to byte, float to int.
It has general form:
(Target-value) value
Here target value specifies the desired type to convert the specified value. For
example, if you want to convert int into float then you will write as:
int a;
float b;
a= (int) b;
this conversion will truncate decimal part and store integer part into variable a i.e.
if b contains 1.23 then a will be assigned 1 as its value.
Similarly if you will perform conversion from int to byte then it will give you modulus
(remainder of the division of int by byte range i.e. 256) as its value. So if a is int
type then b is byte type. Let a=257 then when cast to byte then byte variable i.e.
b will have 1 as its value. 45
Programming with Java Program showing type casting
// Name of this file will be "[Link]"
}
}
OUTPUT
Conversion of int into byte
b=44
Conversion of double into int
a=3
In case of conversion from int to byte modulus is the value of b while in conversion
from double to int decimal part is removed and integer part is the value of a.
Command Line Arguments
Sometimes we want to give input to our program at the time of execution. In Java
we can provide input to the program by passing parameters to it which are called
as command line arguments. Command line arguments are the parameters that are
passed to the application programs at the time of execution. When program is
invoked for execution, at that time compiler checks whether it contain any argu-
ments or not. If it contains then it passes them to the application program.
We write a command to execute the program i.e.
java source code name
Here after the name of source code, you can write command line arguments.
Example:
java Hello sir
Here Hello is the name of source code. When we write a program then we write
main method as,
public static void main ( String args[])
Here, as you know args is an array that receives all parameters and stores them as
their element. args is an array that can store multiple things but of same types. sir is
the parameter that will be passed to array named as args. args will store it at index
zero i.e.
46 args[0] sir
you can access array elements by using index i.e. numbers starting from 0. Indexes Key Features of Java
are numbers like 0, 1, 2………. & so on written inside brackets [ ].
So if you give 'How are you' then it will be stored as:
args[0] = How
NOTES
args[1] = are
args[2] = you
About array you will study in chapter 5.
Program to show command line arguments
// Name of this file will be "[Link]"
class Show //Class declaration
{
public static void main( String args [] )
{
String str;
str = args[0];
[Link]("name is" +str);
}
}
When you will run this program then you will write as:
java Show Nandini
OUTPUT
name isNandini
Here we have passed only one parameter, we can pass more than one parameters.
For accessing more than one parameters, we need to use loops. We will discuss
about loops in chapter 4. just see an example here.
Program that passes more than one command line arguments
// Name of this file will be "[Link]"
class Show //Class declaration
{
public static void main( String args [] )
{
String str;
int count,i;
count = [Link];
[Link]("number of arguments"+count);
for(i = 0; i<count;i++)
{
str = args[i];
[Link]("You are" +str);
}
}
}
When you will run this program then you will write as:
java Show good beautiful sincere hardworking 47
Programming with Java OUTPUT
number of arguments4
You aregood
You arebeautiful
NOTES You aresincere
You arehardworking
ANSWER OF THE CHECK YOUR PROGRESS :
1. Java supports three types of comments. They are:
Single-line Comment
Multiline Comment
Documentation Comment
2. Statement is the instruction that you write in a program in order to state
something.
3. Data types are means to identify the type of data and associated operations
of handling it.
4. Floating-point numbers are used when we want to calculate some fractional
value. They are also called as real numbers. They are required for calcu-
lation of trigonometry, to find square root as result of these type of calcu-
lations are fractional numbers.
EXERCISE
1. Write down about Java Program Structure.
2. What do you mean by variables, constants and data types in Java ?
3. Define typecasting and symbolic constants in Java.
4. Explain scope of variables.
5. What are variables? How are they declared?
6. Tell about different data types of Java.
7. Explain constants in detail.
8. Differentiate between constants and variables in Java.
9. Explain JVM.
10. Write a short note on statements.
11. Write a program that passes command line arguments.
12. Write a simple Java program that displays your name and address.
13. Why it is preferred to give file name same as that of classname having main()
method ? What will happen if you provide any other classname as filename
in Java. Will it be compiled and executed ?
14. Explain the following :
(a) Variables
(b) Data type for floating-point numbers
(c) Identifiers
(d) JVM
(e) Keywords
48
15. Differentiate between types of variables in Java.