SlideShare a Scribd company logo
1 of 74
Download to read offline
1
PROGRAMMING
JAVA
Arun Umrao
www.sdmsacademy.in
DRAFT COPY - GPL LICENSING
2
Contents
1 Introduction 7
1.1 Data In & Data Out . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.1.1 Print Output . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.1.2 Formatted Output . . . . . . . . . . . . . . . . . . . . . . 8
1.1.3 Escape Characters . . . . . . . . . . . . . . . . . . . . . . 10
1.1.4 Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.1.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.1.6 Variables & Data Type . . . . . . . . . . . . . . . . . . . 12
Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Character . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Short . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Float Decimals . . . . . . . . . . . . . . . . . . . . . . . . 14
Double Decimals . . . . . . . . . . . . . . . . . . . . . . . 15
Declaration, Initialization & Assignment . . . . . . . . . . 15
Signed & Unsigned Integer . . . . . . . . . . . . . . . . . 16
Overflow of Data . . . . . . . . . . . . . . . . . . . . . . . 17
Cast Operators . . . . . . . . . . . . . . . . . . . . . . . . 17
Scope of Variables . . . . . . . . . . . . . . . . . . . . . . 18
1.1.7 Access Controll . . . . . . . . . . . . . . . . . . . . . . . . 19
private . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
package . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
protected . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
public . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.2 Java Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.2.1 Expression . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.2.2 Unary Operaors . . . . . . . . . . . . . . . . . . . . . . . 19
1.2.3 Binary Relations . . . . . . . . . . . . . . . . . . . . . . . 20
1.2.4 Logical Relations . . . . . . . . . . . . . . . . . . . . . . . 22
1.2.5 Precedence of Relational Operators . . . . . . . . . . . . . 24
1.2.6 Bitwise Operator . . . . . . . . . . . . . . . . . . . . . . . 25
1.2.7 Shift Operator . . . . . . . . . . . . . . . . . . . . . . . . 27
1.2.8 Condition & Relation . . . . . . . . . . . . . . . . . . . . 29
3
4 CONTENTS
1.2.9 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . 30
1.2.10 Precedence of Arithmatic Operators . . . . . . . . . . . . 31
1.2.11 Relational Operators . . . . . . . . . . . . . . . . . . . . . 32
1.3 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.3.1 if condition . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.3.2 if-else condition . . . . . . . . . . . . . . . . . . . . . . . . 33
1.3.3 switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.4 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.4.1 for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.4.2 while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.4.3 For Loop Like While Loop . . . . . . . . . . . . . . . . . . 38
1.5 Parsing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.6 Mathematical Operator . . . . . . . . . . . . . . . . . . . . . . . 40
1.6.1 Trigonometric Functions . . . . . . . . . . . . . . . . . . . 40
cos, sin & tan . . . . . . . . . . . . . . . . . . . . . . . . . 40
acos, asin & atan . . . . . . . . . . . . . . . . . . . . . . . 41
cosh, sinh & tanh . . . . . . . . . . . . . . . . . . . . . . . 42
1.6.2 Logarithm Function . . . . . . . . . . . . . . . . . . . . . 42
exp, log . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.6.3 Arithmatic Function . . . . . . . . . . . . . . . . . . . . . 43
pow, sqrt, floor, ceil & round . . . . . . . . . . . . . . . . 43
2 String & Arrays 45
2.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.2 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.2.1 Dyanmic Array . . . . . . . . . . . . . . . . . . . . . . . . 46
2.2.2 Uni-dimensional Array . . . . . . . . . . . . . . . . . . . . 46
2.2.3 Multi-dimensional Array . . . . . . . . . . . . . . . . . . . 47
2.2.4 Size of Array . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.3 Class, Object & Function . . . . . . . . . . . . . . . . . . . . . . 49
2.3.1 Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.3.2 Prototyping . . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.3.3 this Reference . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.3.4 Field Declaration . . . . . . . . . . . . . . . . . . . . . . . 55
2.3.5 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 55
2.3.6 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.3.7 Type of Objects . . . . . . . . . . . . . . . . . . . . . . . 57
2.4 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.4.1 Exception Handling . . . . . . . . . . . . . . . . . . . . . 62
3 Accessing System Files 63
3.1 Input Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.1.1 File Handling . . . . . . . . . . . . . . . . . . . . . . . . . 64
Open a File . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Close a File . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Reading File . . . . . . . . . . . . . . . . . . . . . . . . . 66
CONTENTS 5
Writing File . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Temporary File . . . . . . . . . . . . . . . . . . . . . . . . 67
Memory Mapped I/O . . . . . . . . . . . . . . . . . . . . 68
Random Access File . . . . . . . . . . . . . . . . . . . . . 69
File Pointer to Class . . . . . . . . . . . . . . . . . . . . . 71
3.1.2 File Directory . . . . . . . . . . . . . . . . . . . . . . . . . 71
Finding Roots . . . . . . . . . . . . . . . . . . . . . . . . 71
File Object . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
3.2 JNI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6 CONTENTS
Chapter 1
Introduction
Here we have use Netbean IDE for java programming.
1.1 Data In & Data Out
In Java, input and output is received and sent through standard input and
output stream. The input is accepted via in stream while output is sent via out
stream. Java has strong grouping convention. Function or block domain are
limited by curly braces, ie {...}. All the variable defined inside the {...} have
local scope. A semicolon is used to terminate the line.
1.1.1 Print Output
We can print the output in out stream via system i/o class. Se example below,
in which “Hi” is printed in output stream.
✞
1 package jscript;
/*Jscript is main class name. It shall be same as*
3 *file name. i.e. file name must be jscript.java*/
public class Jscript {
5
public static void main(String[] args) {
7 System.out.println("Hi");
}
9 }
✆
✞
Hi
✆
When a java program is run, it starts execution from the main() function.
This main() function is defined here as public so that it can be executed from
anywhere. Its return type is void, i.e. no return value. In the following line
✞
1 public static void main(String[] args) {}
✆
7
8 CHAPTER 1. INTRODUCTION
(String[] args) receives the string array from the commandline. Number of input
arrays are counted by using length object. In java, class name shall be same as
its file name where it is declared. Here println is similar to the printf of C.
1.1.2 Formatted Output
In Java, values or variables can be placed inside the string by using ‘+’ sign as
shown in example below.
✞
1 package jscript;
/*Jscript is main class name. It shall be same as*
3 *file name. i.e. file name must be jscript.java*/
public class Jscript {
5
public static void main(String[] args) {
7 System.out.println("Hi "+10+" .");
}
9 }
✆
✞
Hi 10 .
✆
Here, println is short form of print a line and it prints the string at output
stream. printf is short form of print formatted and it can be used in place of
println for formatted output.
✞
1 package jscript;
/*Jscript is main class name. It shall be same as*
3 *file name. i.e. file name must be jscript.java*/
5 public class Jscript {
7 public static void main(String[] args) {
System.out.printf("Hi %d.n", 10);
9 }
}
✆
✞
Hi 10.
✆
In Java, modifiers are used to print formatted outputs. A modifier ‘%s’ simply
puts the string by creating space equal to the length of string. If this modifier
is redefined like ‘%20s’ (a positive integer between % and ‘s’ symbols), then
space for 20 characters is created. If string length is less than 20 characters
then ‘ ’ (space) is prefixed to the string to increase its length to 20. If number
in modifier is less than the length of string then nothing is done.
✞
1 package jscript;
3 public class Jscript {
1.1. DATA IN & DATA OUT 9
Symbolic Constant Represents
%a Floating-point number, hexadecimal digits and p-
notation.
%A Floating-point number, hexadecimal digits and P-
notation.
%c Single character.
%d Signed decimal integer.
%e Floating-point number in e-notation form.
%E Floating-point number in e-notation form.
%f Floating-point number in decimal notation form.
%g If the exponent is less than 4 or greater than or equal
to the precision %e used otherwise %f is used.
%G If the exponent is less than 4 or greater than or equal
to the precision %E used otherwise %F is used.
%i Signed decimal integer.
%o Unsigned octal integer.
%p A pointer.
%s Character string.
%u Unsigned decimal integer.
%x Unsigned hexadecimal integer using hex digits 0f.
%X Unsigned hexadecimal integer using hex digits 0F.
%% Prints a percent sign.
Table 1.1: Conversion specifiers.
10 CHAPTER 1. INTRODUCTION
5 public static void main(String[] args) {
System.out.printf(""%s" secured numbers "%d"n", "Arun Kumar"
, 100);
7 System.out.printf(""%20s" secured numbers "%5d"n", "Arun
Kumar", 100);
}
9 }
✆
✞
"Arun Kumar" secured numbers "100"
" Arun Kumar" secured numbers " 100"
✆
For numeric modifiers, total spaces and filled space can also be used simulta-
neously if modifier is modified like ‘%10.6d’. Here number ‘10’ will create 10
spaces for placing a number and if digits in number is less than ‘6’ then ‘0’ will
be prefixed with the number.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i;
System.out.printf("%5s%10s%10sn", "Num", "Square", "Cubic");
8 for (i = 90; i < 92; i++) {
System.out.printf("%5d%10d%10dn", i, i * i, i * i * i);
10 }
}
12 }
✆
✞
Num Square Cubic
90 8100 729000
91 8281 753571
✆
1.1.3 Escape Characters
Escape characters are used to perform action even if they are used as string.
For example
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.println("Rajasthan");
7 }
}
✆
n at the end of println function would add a new line after “Rajasthan!”. The
output of the program is
1.1. DATA IN & DATA OUT 11
✞
Rajasthan
✆
Other escape characters are
Escape Character Meaning
t Adding a tab
n Start a new line
1.1.4 Quotes
In Java, double quotes is used to represents a group of character as a string.
Single quote represents to character code in decimal equivalent.
✞
package jscript;
2 /*Jscript is main class name. It shall be same as*
*file name. i.e. file name must be jscript.java*/
4 public class Jscript {
6 public static void main(String[] args) {
System.out.println("Uttar Pradesh.");
8 }
}
✆
✞
Uttar Pradesh.
✆
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
char a = ’a’;
7 System.out.println(a);
}
9 }
✆
✞
a
✆
1.1.5 Comments
Commenting is most useful feature of the Java programming. It is used to write
comments before or after a function or variable. Stuff within the commenting
delimiters is ignored during compilation of the program. There are two type
of commenting delimiters. First, single line commenting delimiter and second,
multi-line commenting delimiter. For single line commenting ‘//’ is used and
for multi-line commenting ‘/* ... */’ is used.
12 CHAPTER 1. INTRODUCTION
✞
1 /*
* Multiline comments
3 */
package jscript;
5
public class Jscript {
7
public static void main(String[] args) {
9 //Print cost of pen
System.out.println("Cost of pen is "+10);
11 }
}
✆
The output of above program is
✞
Cost of pen is 10
✆
1.1.6 Variables & Data Type
Variables are multicharacter names used to refer to some locations in memory
that holds a value to which we are working. A variable is equivalent to its
assigned value. A variable may be alphanumeric name with underscope charac-
ter. First numeric character of a variable name is not acceptable. Spaces and
special characters which are reserved for internal operations of Java are illegal.
Similarly, use of comma, dot, symbol of question mark, symbols reserved for
realtion operations, symbols reserved for bitwise operations, colon and line ter-
minating symbol are also considered as illegal if used in variable names. Key
words specially reserved for internal programming of Java, can not be used like
variable name. A list of reserved keyword is given in section ??.
✞
1 int A1; // Legal and acceptable.
int 1A; // Illegal, first character is numeric
3 int A_1;// Legal, _ is acceptable
int A$1;// Legal, $ is not reserved character
5 int A 1;// Illegal, space is not acceptable
int for;// Illegal, for is reserved keyword
✆
A variable declared once can not be declared again.
Boolean
Java has dedicated boolean type. Its value is either true or false.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
1.1. DATA IN & DATA OUT 13
6 System.out.println("Function is " + false);
}
8 }
✆
✞
Function is false
✆
Character
char is used to initialize a 18 bit unsigned unicode character.
✞
1 char *<var name>=<char code>;
✆
A char variable without initialization is not acceptable in java.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
char A1=100;
7
System.out.println("Char is " + A1);
9 }
}
✆
✞
Char is d
✆
Byte
It is one byte long integer value.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
byte i = 120;
7 System.out.println("i is " + i);
}
9 }
✆
✞
i is 120
✆
If the variable ‘i’ is assigned the integer value larger than 8 bits then compiler
shows error and refuse to compile the program.
14 CHAPTER 1. INTRODUCTION
Short
It is two byte long integer value.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
byte i = 510;
7 System.out.println("i is " + i);
}
9 }
✆
✞
i is 510
✆
If the variable ‘i’ is assigned the integer value larger than 16 bits then compiler
shows error and refuse to compile the program.
Integer
A 4 byte long numerical value is declared and initialized by using primitive data
type int. If an integer variable is initialized as decimal number, then compiler
refuse to compile the program.
✞
1 int <var name>;
int <var name>=<value>;
✆
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i=10;
System.out.println("i is " + i);
8 }
}
✆
✞
i is 10
✆
Float Decimals
This data type is floating-point type. It usually referred to as a single-precision
floating-point. Float-to-integer or integer-to-float type conversion of numbers
take place by casting the number. It is 4 byte long. Its range is from 1.2×10−38
to 1.2 × 1038
. Syntax for the float data type is
1.1. DATA IN & DATA OUT 15
✞
1 float <var name>;
float <var name>= (float) <decimal value>;
✆
See the example below.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 float i = (float) 10.126;
System.out.println("i is " + i);
8 }
}
✆
✞
i is 10.126
✆
Double Decimals
This data type is floating-point type. It usually referred to as a double-precision
floating-point. Double-to-integer or integer-to-double type conversion of num-
bers take place by casting the number. It is 8 bytes long. Its range is from
2.3 × 10−308
to 2.3 × 10308
. Syntax for the double data type is
✞
1 double <var name>;
double <var name>=<decimal value>;
✆
See the example below.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 double i = 1.12416;
System.out.println("i is " + i);
8 }
}
✆
✞
i is 1.12416
✆
Declaration, Initialization & Assignment
A variable in Java can be assigned as integer, if syntax is defined as given below:
✞
1 int variable_name;
✆
16 CHAPTER 1. INTRODUCTION
It means there is some space declared in data to store integer value. Multiple
variables can be assigned in single line or successive way like
✞
1 int variable_a, variable_b, variable_c;
✆
A variable in Java is said to be initialized if a numeric or an alphabatic value is
assigned to it. For example variable a is initialized by
✞
1 int variable_a = <value>;
✆
To distinct the words of a variable, underscore symbol (‘ ’) is used. Anytime
within a program in which we specify a value explicitly instead of referring
to a variable or some other form of data, that value is referred as a literal.
Literals can either take a form defined by their type, or one can use hexadecimal
(hex) notation to directly insert data into a variable regardless of its type. Hex
numbers are always preceded with ‘0x’. The length of data type is measured its
byte length. The datatype may be signed or unsigned. In signed data type, the
MSB is used for sign declaration and rest of the bits are used for data value. In
unsigned data type, all the bits are used for data value.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 0x50;
7 System.out.println("i is " + i);
}
9 }
✆
✞
i is 80
✆
Signed & Unsigned Integer
A byte is 8 bit long. The size of int is 4 byte, i.e. 32 bits. A signed integer is
that integer whose first bit, i.e. MSB is taken as sign bit. If integer is defined
as signed then MSB is sign bit and remaining 31 bits are used for storing an
integer. If integer is defined as unsigned then all 32 bits are used for storing an
integer.
✞
1 //+---------------------Sign bit
(1)1111111b =>-127d // Signed 7 bit integer
3 11111111b => 255d // Unsigned 8 bit integer
✆
A signed integer ranges from -2147483647 to 2147483647 while unsigned integer
ranges from 0 to 4294967294. In the Java, bit ‘0’ is used as positive sign and
bit ‘1’ is used as negative sign.
1.1. DATA IN & DATA OUT 17
Overflow of Data
A variable declared as integer, long, float or double integer and character has
capacity to store a specific size of data. An integer variable can not store data
as long as float variable. This is why, a variable shall be declared of proper size
for storing a data. To understand the overflow, consider a virtual datatype that
can store only one byte long data. This datatype may be signed or unsiged.
First assume it is unsigned, then the largest decimal value, that can be stored
by it is 255. Initially, datatype has initialized with decimal value 254.
✞
1 datatype k = 254d = 11111110b
✆
datatype is incremented by 1, it becomes
✞
1 datatype k = 255d = 11111111b
✆
Again, datatype is incremented by 1, it becomes
✞
1 datatype k = 255d = 1 00000000b
✆
The size of result is larger than one byte. The value of datatype reset to zero
due to overflow. Here, overflow carry is ‘1’. Similarly a positive signed value
becomes negative signed value if it is incremented beyond the signed data range.
Taking the same datatype with signed value.
✞
1 /* Bit inside parentheses represents to sign.*/
datatype k = 127d = (0)1111111b
✆
It is incremented by 1, it becomes
✞
/* Bit inside parentheses represents to sign.*/
2 datatype k = -0d = (1)0000000b
✆
It becomes negative zero. Again, if increment by 1, the result is
✞
/* Bit inside parentheses represents to sign.*/
2 datatype k = -1d = (1)0000001b
✆
Which is -1. Here, again datatype variable is overflowed. In java, overflow values
shows errors and program is not compiled.
Cast Operators
Cast operators are used in conversion of one type data into other type data.
Type casting may be of two types: (i) Implicit type casting and (ii) Explicit
type casting. Implicit type casting is automatically handled by compiler i.e.
when two or more data types are under execution. The final data-type will be
that data type which is declared. An explicit type cast is a cast that should we
specifically invoked with either of the cast. The compiler does not automatically
invoke to resolve the data type conversion.
18 CHAPTER 1. INTRODUCTION
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 float i = (int) 10.2;
System.out.println("i is " + i);
8 }
}
✆
Here, at first, 10.2 is converted into integer by truncating its decimal part and
then it is converted into float data type. Hence the 10.0 shall be final output of
above program.
✞
i is 10.0
✆
String can be converted to character array by using toCharArray() method.
✞
1 /*Convert string into char code.*/
char[] c = s.toCharArray();
✆
Here, ‘c’ represents to character array.
A string is converted into string array by using split() method. To split
string by space, synopsis is used like
✞
String[] sArray=s.split(" ");/*Space by " "*/
✆
To split the string from each character, split() method is used like
✞
1 String[] sArray=s.split("");/*No space by ""*/
✆
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String args[]) {
String str = "This is my room";
7 String[] k = str.split(" ");
System.out.printf("i is in string : %sn", k[0]);
9 }
}
✆
✞
i is in string : This
✆
Scope of Variables
Local variables are undefined prior to initialization. We can declare a variable
without initialization. But if it is try to use local variables before assigning a
value, the compiler will refuse to compile the program.
1.2. JAVA OPERATORS 19
1.1.7 Access Controll
All members of a class are accessible to the class itself. To control access from
other classes, class members have four possible access modifiers:
private
Private members declared private and they are accessible only in the same class.
package
Package members declared with no access modifier are accessible in classes in
the same package, as well as in the class itself.
protected
Protected members declared protected are accessible in subclasses of the class,
in classes in the same package, and in the class itself.
public
Public members declared public are accessible anywhere the class is accessible.
The private and protected access modifiers apply only to members not to the
classes or interfaces themselves. For a member to be accessible from a section of
code in some class, the member’s class must first be accessible from that code.
1.2 Java Operators
There are following types of Java operators.
1.2.1 Expression
An expression is a combination of one or more explicit values, constants, vari-
ables, operators, and functions. The evaluated value of expression is assigned
to another variable or printed in output stream. A function declared as void
type returns void value the this return value is discarded in an expression.
1.2.2 Unary Operaors
In a unary operation, operator has only one operand. The unary operators used
in Java are given in table below.
20 CHAPTER 1. INTRODUCTION
Table 1.2: Unary operators.
Type Representation
Increment ++x, x++
Decrement - - x, x - -
Positive +x
Negative -x
Ones‘ complement ∼ x
Logical negation !x
Cast (type-name) cast-expression
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i=10;
7 System.out.println("Name of tree is " + (-i));
}
9 }
✆
✞
Name of tree is -10
✆
1.2.3 Binary Relations
Binary operators are those operators which require two operands. These oper-
ators are addition, subtraction, multiplication, division, less than, greater than,
equals to etc. The relational binary operators are
1. < known as less than.
2. > known as greater than.
3. ≤ known as less than or equal to.
4. ≥ known as greater than or equal to.
5. == known as equals.
6. ! = known as not equals.
1.2. JAVA OPERATORS 21
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int a = 10;
7 int b = 20;
int c = 5;
9 if (a < b) {
System.out.println(a + " is less than " + b);
11 }
if (a > b) {
13 System.out.println(a + " is greater than " + b);
}
15 if (a <= c) {
System.out.println(a + " is less than or equal to " + c);
17 }
if (a == c) {
19 System.out.println(a + " is exactly equal to " + c);
}
21 if (a != b) {
System.out.println(a + " is not equal to " + b);
23 }
}
25 }
✆
Output of above program is
✞
10 is less than 20
10 is not equal to 20
✆
Remember that ‘=’ and ‘==’ are not same. For example, ‘c=20’ assigned
the value 20 to variable c and returns true in output rather than comparison of
c and 20. Reason behind is that c does not have a dedicated boolean type. So
‘0’ means false and anything else is true. In Java, the coditions like
✞
int a = 20; //constant initialized
2 if (a = 10) //incompatible integer type
System.out.println("Stuff");
✆
✞
1 if (0 < v < 10) {//bad operand type for <
System.out.println("Stuff");
3 }
✆
are not acceptable. The compiler shows error expressing ‘incompatible integer
type’ or ‘bad operand type for <’. The appropriate form of comparison is shown
in below example.
✞
1 package jscript;
22 CHAPTER 1. INTRODUCTION
3 public class Jscript {
5 public static void main(String[] args) {
int v = 7;
7 if (v == 7) {
System.out.println("v is " + v);
9 }
}
11 }
✆
✞
v is 7
✆
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int v = 7;
7 if (0 < v && v < 10) {
System.out.println("v=" + v +" is less than 20");
9 }
}
11 }
✆
✞
v=7 is less than 20
✆
1.2.4 Logical Relations
Logical relations sometimes known as boolear relations also. Logical operators
are those operators which compare the variables or results logically.
1. && known as logical AND. If both the operands are non-zero, then con-
dition becomes true.
2. || known as logical OR. If any of the two operands is non-zero, then con-
dition becomes true.
3. ! known as logical NOT. Use to reverses the logical state of its operand.
If a condition is true then Logical NOT operator will make false.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
1.2. JAVA OPERATORS 23
System.out.printf("6 != 6 && 6 / 2 < 5 is %bn", 6 != 6 && 6 / 2
< 5);
7 System.out.printf("6 != 6 || 6 / 2 < 5 is %bn", 6 != 6 || 6 / 2
< 5);
System.out.printf("6 != 6 is %bn", 6 != 6);
9 }
}
✆
✞
6 != 6 && 6 / 2 < 5 is false
6 != 6 || 6 / 2 < 5 is true
6 != 6 is false
✆
Logical expressions are evaluated from left to right. Evaluation stops as soon
as something is discovered that renders the expression false.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.printf("(2 < 3) && (4 > 5) is %bn", (2 < 3) && (4 >
5));
7 System.out.printf("(2 < 3) && (4 < 5) is %bn", (2 < 3) && (4 <
5));
}
9 }
✆
✞
(2 < 3) && (4 > 5) is false
(2 < 3) && (4 < 5) is true
✆
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int x = 6;
/* Here x is equal to 6. So, the relation*
8 * x != 6 is false. Now second relation*
* x / 2 < 5 is not evaluated here. So, *
10 * the result is 0. */
System.out.printf("Expression result is %bn", x != 6 && x / 2 <
5);
12 }
}
✆
✞
Expression result is false
✆
24 CHAPTER 1. INTRODUCTION
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int x = 4;
7 /* Here x is not equal to 6. So, that *
* x != 4 is true. Now second relation*
9 * x / 2 < 5 is logically ANDED with *
* the result of x != 6. Here x/2 is 2*
11 * and 2 is less than 5, so logical *
* AND of left and right values is 1 */
13 System.out.printf("Expression result is %bn", x != 6 && x / 2 <
5);
}
15 }
✆
✞
Expression result is true
✆
1.2.5 Precedence of Relational Operators
The precedence of the binary relational operators is less than that of the arith-
metic operators. This means, for example, x > y + 2 is same as x > (y + 2) and
x = y > 2 is same as x = (y > 2). It means, in an expression, order of evalu-
ation of operators is arithamtic operators, relational operators and assignment
operators respectively.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int x = 4, y = 1;
7 /*x > y + 2*/
/*x > 1 + 2*/
9 /*x > 3 */
/*4 > 3 (true)*/
11 if (x > y + 2) {
System.out.println("Expression Passed.");
13 } else {
System.out.println("Expression Failed.");
15 }
}
17 }
✆
✞
Expression Passed.
✆
1.2. JAVA OPERATORS 25
1.2.6 Bitwise Operator
A bitwise OR (|) gives result ‘1’ if either one or both bits are ‘1’ otherwise result
is zero. A bitwise AND (&) gives result ‘1’ if both bits are ‘1’ otherwise result is
zero. A bitwise XOR (ˆ) results ‘1’ if only either of two bits1
are ‘1’ otherwise
result is zero. A bitwise NOT (∼) or complement, is a unary operation that
performs logical negation on each bit, forming the ones’ complement of the given
binary value. Bits those are 0 become 1, and those that are 1 become 0.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
/*10 is Binary equivalent to 1010*/
7 int i = 10;
/*5 is Binary equivalent to 0101*/
9 int j = 5;
/*-------------------------**
11 Bitwise OR Operation is
1010
13 0101
------
15 1111 = 15
**------------------------*/
17 System.out.println("Bitwise OR of " + i + ", " + j + " is " + (i
| j));
/*-------------------------**
19 Bitwise AND Operation is
1010
21 0101
------
23 0000 = 0
**------------------------*/
25 System.out.println("Bitwise AND of " + i + ", " + j + " is " + (i
& j));
/*-------------------------**
27 Bitwise XOR Operation is
1010
29 0101
------
31 1111 = 15
**------------------------*/
33 System.out.println("Bitwise XOR of " + i + ", " + j + " is " + (i
^ j));
/*-------------------------**
35 Bitwise NOT Operation is
1010
1
If both bits are opposite bits.
26 CHAPTER 1. INTRODUCTION
37 ---------
0101 = -11
39 **------------------------*/
System.out.println("Bitwise NOT of " + i + " is " + (~i));
41 }
}
✆
✞
Bitwise OR of 10, 5 is 15
Bitwise AND of 10, 5 is 0
Bitwise XOR of 10, 5 is 15
Bitwise NOT of 10 is -11
✆
Normally, bitwise & operator returns the value equal to or less than the lesser
operand. This is why & operator is used to restric the upper limit of the random
result.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i = 0;
while (i < 10) {
8 System.out.println("i&" + i + " => " + (i & 5));
i++;
10 }
}
12 }
✆
✞
0&5 => 0, 1&5 => 1, 2&5 => 0, 3&5 => 1, 4&5 => 4,
5&5 => 5, 6&5 => 4, 7&5 => 5, 8&5 => 0, 9&5 => 1,
✆
While bitwise | operator returns the value equal to or larger than the largest
operand. This is why | operator is used to restrict the lower limit of random
result.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i = 0;
while (i < 10) {
8 System.out.println("i|" + i + " => " + (i | 5));
i++;
10 }
}
12 }
✆
1.2. JAVA OPERATORS 27
✞
0|5=>5, 1|5=>5, 2|5=>7, 3|5=>7, 4|5=>5
5|5=>5, 6|5=>7, 7|5=>7, 8|5=>13, 9|5=>13
✆
1.2.7 Shift Operator
Logical shift operators are
1. << known as left shift
2. >> known as right shift
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 /*Bit pattern of Decimal 4 is equivalent to binary 100*/
int i = 4;
8 /*Number of places take place by binary shift.*/
int j = 2;
10 /*<< makes 100 to 10000, i.e. 16 in decimal*/
System.out.println("<< of " + i + ", " + j + " is " + (i << j));
12 /*>> makes 100 to 1, i.e. 1 in decimal*/
System.out.println(">> of " + i + ", " + j + " is " + (i >> j));
14 }
}
✆
✞
<< of 4, 2 is 16.
>> of 4, 2 is 1.
✆
In the following example, bitwise relation is used to add two number.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int x = 30, y = 1, sum, carry;
/*---------------------------**
8 Decimal 30 is binary 11110
Decimal 01 is binary 00001
10 OR Operation is
11110
12 00001
----------
14 S= 11111
**---------------------------*/
16 sum = x ^ y;
28 CHAPTER 1. INTRODUCTION
/*---------------------------**
18 Decimal 30 is binary 11110
Decimal 01 is binary 00001
20 OR Operation is
11110
22 00001
--------
24 C = 00000
**---------------------------*/
26 carry = x & y;
/*Performed loop until last carry is not zero.*/
28 while (carry != 0) {
/*----------------------------------------**
30 Left shift of carry is
C_s = 000000
32 This operation is performed to shift
the carry left hand side by one place
34 to add it with next higher place value.
**----------------------------------------*/
36 carry = carry << 1;
/*Take x as sum value from OR Operation.*/
38 x = sum;
/*Take y as carry value form *
40 *left shift of AND Operation.*/
y = carry;
42 /*Take OR Operation of x and y*/
sum = x ^ y;
44 /*Get the next carry.*/
carry = x & y;
46 }
/*Print the sum 31.*/
48 System.out.println("Sum of " + x + " and " + y + " is : " + sum);
}
50 }
✆
✞
Sum of 30 and 1 is 31
✆
Binary shift operation can be performed in characters and strings. It is explained
in the example given below.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
char a = ’a’;/*Binary equivalent-1100001*/
7 char b = ’b’;/*Binary equivalent-1100010*/
char c = ’c’;/*Binary equivalent-1100011*/
9 /*-------------------------------------------------------*
Shift of a by 16 bit left side--11000010000000000000000
1.2. JAVA OPERATORS 29
11 Shift of b by 8 bit left side-----------110001000000000
Shift of c by 0 bit left side-------------------1100011
13 -------------------------------------------------------
OR Operation -------------------11000010110001001100011
15 It is equivalent to Decimal---------------------6382179
*-------------------------------------------------------*/
17 System.out.println("Left binary bit shift " + (a << 16 | b << 8 |
c));
}
19 }
✆
✞
Left binary bit shift is 6382179
✆
The unary operator ‘∼’ returns the one’s complements of an integer by changing
bit ‘0’ into ‘1’ and viceversa.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int j = 0;
7 System.out.println("Bitwise ~ operation on an integer.");
while (j < 3) {
9 System.out.println(j + " => " + (~j));
j++;
11 }
}
13 }
✆
✞
Bitwise ~ operation on an integer.
0 => -1
1 => -2
2 => -3
✆
1.2.8 Condition & Relation
If a condition is true then successive value is taken otherwise next value. The
simplest form of this operator is
✞
x ? y : z
✆
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 1, j = 0;
30 CHAPTER 1. INTRODUCTION
7 while (j < 3) {
System.out.println(i + " < " + j + " " + (i < j ? "YES" : "NO"
));
9 j++;
}
11 }
}
✆
✞
1 < 0 NO
1 < 1 NO
1 < 2 YES
✆
1.2.9 Arithmetic Operators
Arithmetic operators are
1. + known as addition operator. It adds the right value with left value.
2. − known as subtraction operator. It subtracts the right value from left
value.
3. / known as division operator. It divides the left value with right value.
Returns the quotient. If, both left and right values are integer then decimal
part of the result is truncated.
4. ∗ known as multiplication operator. It multiply the left value with right
value. Returns product of two numbers.
5. % known as modulo operator. Returns the remainder in division.
6. = known as assignment operator. A variable at left side to it is assigned
the value at the right side of it.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
float i = 1, j = 3;
7 System.out.println(i + " + " + j + "=" + (i + j));
System.out.println(i + " - " + j + "=" + (i - j));
9 System.out.println(i + " * " + j + "=" + (i * j));
System.out.println(i + " / " + j + "=" + (i / j));
11 System.out.println(i + " % " + j + "=" + (i % j));
}
13 }
✆
1.2. JAVA OPERATORS 31
✞
1.0 + 3.0=4.0
1.0 - 3.0=-2.0
1.0 * 3.0=3.0
1.0 / 3.0=0.33333334
1.0 % 3.0=1.0
✆
1.2.10 Precedence of Arithmatic Operators
Arithmatic problems are not solved from left to right in the sequence the expres-
sion is written. But some rules are used. For example, parentheses are solved
first, then division, multiplication, addition and subtraction. Thus, arithmatic
operators have some precedence. Operators in order of decreasing precedence
are given in table below.
Operators Associativity
() Left to right
+ – (unary) Right to left
* / Left to right
+ – (binary) Left to right
= Right to left
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int y;
7 /* Order of arithmatic operators *
* are /, *, +, -, =. So first 12*
9 * is divided by 5 and answer is *
* 2.4. 6 is multiply by 2.4 and *
11 * result is 14.4. It is added to*
* 20 and 10 is subtracted *
13 * The answer is 14.4+20-10=24.4 */
y = 6 * 12 / 5 + 20 - 10;
15 /* In result only 24 is printed. *
* Decimal is truncated. */
17 System.out.println("Expression result is " + y);
}
19 }
✆
✞
Expression result is 24
✆
32 CHAPTER 1. INTRODUCTION
1.2.11 Relational Operators
The assignment operators are
1. == known as equal.
2. ∗ = known as product and equal.
3. / = known as divide mode and equal.
4. + = known as add and equal.
5. − = known as subtract and equal.
6. <<= known as left shift and equal.
7. >>= known as right shift and equal.
8. & = known as AND and equal.
9. ˆ= known as exclusive OR and equal.
10. | = known as inclusive OR and equal.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int y = 2;
7 y += 2;
System.out.println("y += 2 is " + y);
9 y &= 2;
System.out.println("y &= 2 is " + y);
11 y ^= 2;
System.out.println("y ^= 2 is " + y);
13 y |= 2;
System.out.println("y |= 2 is " + y);
15 y <<= 2;
System.out.println("y <<= 2 is " + y);
17 }
}
✆
✞
y += 2 is 4
y &= 2 is 0
y ^= 2 is 2
y |= 2 is 2
y <<= 2 is 8
✆
1.3. CONDITIONS 33
1.3 Conditions
Conditions are the comparison statements those controls the execution of codes
inside the conditional blocks.
1.3.1 if condition
if () provides a way to instruct the program to execute a block of code only if
certain conditions have been met. The syntax of if () construct is
✞
1 if(/*conditions*/) // if condition is true then
statement // execute the condition.
✆
A simple example is
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i=0;
while (i < 5) {
8 if (i == 2) {
System.out.printf("i is %dn", i);
10 }
i++;
12 }
}
14 }
✆
✞
i is 2
✆
1.3.2 if-else condition
if-else provides a way to instruct the program to execute a block of code only
if certain conditions have been met otherwise execute other block. The syntax
of if-else construct is
✞
1 if(/*conditions*/) // if condition is true then
statement one // execute the statement one.
3 else // otherwise if condition is false
statement two // execute the statement two.
✆
A simple example is
✞
package jscript;
2
public class Jscript {
4
34 CHAPTER 1. INTRODUCTION
public static void main(String[] args) {
6 int i=0;
while (i < 5) {
8 if (i == 2) {
System.out.printf("i is %dn", i);
10 } else {
System.out.printf("i is NOT %dn", 2);
12 }
i++;
14 }
}
16 }
✆
✞
i is NOT 2
i is NOT 2
i is 2
i is NOT 2
i is NOT 2
✆
A short hand for of if-else condition is
✞
1 int a=(b > c) ? d : e;
✆
Above statement is similar to the statement of “return d if b is greater than c
else return e”. if - else - if - else - if - else statement can be used successively.
1.3.3 switch
Use of a long chain of if-else-if-else-if-else is very complex and less readable.
There’s a solution by using the Switch-Case construct. The basic syntax of this
construction is given below.
✞
1 switch (<case variable>) {
case 1:
3 statements one
break;
5 case 2:
statements two
7 break;
case 3:
9 statements three
break;
11 default:
default statement
13 break;
}
✆
Here default case is executed if none of the cases is matched with case variable
value. Following is working example
1.3. CONDITIONS 35
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i = 0;
while (i < 5) {
8 switch (i) {
case 1:
10 System.out.printf("i is %dn", i);
break;
12 case 2:
System.out.printf("i is %dn", i);
14 break;
case 3:
16 System.out.printf("i is %dn", i);
break;
18 default:
System.out.printf("either i<1 or i>3n");
20 break;
}
22 i++;
}
24 }
}
✆
✞
either i<1 or i>3
i is 1
i is 2
i is 3
either i<1 or i>3
✆
Here operator ‘break’ plays an important role. If break operator is not used
in block of ‘case’ then all the successive blocks are executed successively. The
reason behind is that, ‘break’ inside the ‘case’ exits from the switch block from
the current loop.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 0;
7 while (i < 5) {
switch (i) {
9 case 1:
System.out.printf("i is %dn", i);
11 case 2:
System.out.printf("i is %dn", i);
36 CHAPTER 1. INTRODUCTION
13 case 3:
System.out.printf("i is %dn", i);
15 break;
default:
17 System.out.printf("either i<1 or i>3n");
break;
19 }
i++;
21 }
}
23 }
✆
✞
either i<1 or i>3
i is 1
i is 1
i is 1
i is 2
i is 2
i is 3
either i<1 or i>3
✆
1.4 Iteration
Iteration is a process in which code statements are executed more than once.
For example, to print a line ten times, either the line is writem ten times one
after another or a loop is used to print the line ten times. Most common
iteration/loop functions are for and while.
1.4.1 for loop
The syntax of for loop is
✞
for(initialization; test; increment) {
2 /* code */
}
✆
The working example is
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int a, b;
7 b = 15;
for (a = 10; a < b; a++) {
9 System.out.printf("The number a is %d.n", a);
}
1.4. ITERATION 37
11 }
}
✆
The output is
✞
The number a is 10.
The number a is 11.
The number a is 12.
The number a is 13.
The number a is 14.
✆
The initialization statement is executed exactly once. It is used to assign an
initial value to some variable. The test expression is evaluated each time before
the code in the for loop executes. If this expression evaluates as 0 (false), the
loop is not (re)enter into the for loop. And execution of program carry on to
the code immediately following the for loop. If the expression is non-zero (ie
true), the loop is (re)enter inside the for loop. After each iteration of the loop,
the increment statement is executed. This often is used to increment the loop
index. An infinite loop is executed if for is defined as shown below.
✞
1 for(;;) {
/* statements / codes */
3 }
✆
Multiple initialization can be used by separating them by comma.
✞
1 for(initialization one, /*First var initialized*/
initialization two; /*Second var initialized*/
3 test of initializers;/*Test the condition of variables*/
increment one , /*Increment of first variable*/
5 increment two) { /*Increment of second variable*/
7 /* expressions / statements / codes */
9 }
✆
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i, j;
7 for (i = 6, j = 1; j < i; i++, j = (j + 2)) {
System.out.printf("Product of i=%d & j=%d is %dn", i, j, i *
j);
9 }
}
11 }
✆
38 CHAPTER 1. INTRODUCTION
✞
Product of i=6 & j=1 is 6
Product of i=7 & j=3 is 21
Product of i=8 & j=5 is 40
Product of i=9 & j=7 is 63
Product of i=10 & j=9 is 90
✆
1.4.2 while loop
A while() loop is the most basic type of loop. It will run as long as the condition
retun non-zero (ie true) value. At false state, while loop exits.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 0;
7 while (i < 5) {
System.out.printf("i*i is %dn", i * i);
9 i++;
}
11 }
}
✆
✞
i*i is 0
i*i is 1
i*i is 4
i*i is 9
i*i is 16
✆
1.4.3 For Loop Like While Loop
The syntax of for loop as
✞
1 for(; <test> ; )
✆
is similar to the while loop
✞
1 while (<test>)
✆
Following is an example which shows that for loop is similar to the while loop.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 0;
1.5. PARSING ARGUMENTS 39
7 for (; i < 5;) {
System.out.printf("%dt", i);
9 i++;
}
11 System.out.printf("n");
int j = 0;
13 while (j < 5) {
System.out.printf("%dt", j);
15 j++;
}
17 System.out.printf("n");
}
19 }
✆
✞
0 1 2 3 4
0 1 2 3 4
✆
1.5 Parsing Arguments
When a program is being executed via another program internally, arguments
are required to be passed to the executable ie the program. These arguments
are considered as inputs for the executable. To pass the values we define main()
function as
✞
public static void main(String[] args)
✆
Here ‘args’ are the array of input strings.
✞
1 package jscript;
3 class Jscript {
5 public static void main(String args[]) {
System.out.println(args[1]);
7 }
}
✆
After compiling and executing the executable as
✞
Jscript.jar a b c
✆
Output is
✞
a
✆
Here Jscript.jar in commandline is also considered as an argument. This is
why there are four arguments and first argument, ie 0th
argument, is Jscript.jar
itself and rest of the arguments are a, b and c respectively.
40 CHAPTER 1. INTRODUCTION
1.6 Mathematical Operator
In C programming addition, subtraction, multiplication and division mathemat-
ical operators can be directly used. Modulus is another mathematical operators
that gives the remainder value. Application of these operators are a + b, a − b,
a ∗ b, a/b and a%b respectively.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
float i = 1, j = 3;
7 System.out.println(i + " + " + j + "=" + (i + j));
System.out.println(i + " - " + j + "=" + (i - j));
9 System.out.println(i + " * " + j + "=" + (i * j));
System.out.println(i + " / " + j + "=" + (i / j));
11 System.out.println(i + " % " + j + "=" + (i % j));
}
13 }
✆
✞
1.0 + 3.0=4.0
1.0 - 3.0=-2.0
1.0 * 3.0=3.0
1.0 / 3.0=0.33333334
1.0 % 3.0=1.0
✆
1.6.1 Trigonometric Functions
“math.h” preprocessor file provides the mathematical functions that can be used
directly in the program. Some of them are defined in following sections.
cos, sin & tan
The cos, sin, and tan functions return the cosine, sine, and tangent of the
argument, expressed in radians. The domain of arguments of sin, cos and tan
are [−π/2, π/2], [0, π] and [−π/2, π/2] respectively. The numerical range of sin,
cos and tan are [−1, 1], [−1, 1] and [−∞, ∞].
✞
1 double cos(double x);
double sin(double x);
3 double tan(double x);
✆
A simple example is
✞
1 package jscript;
3 public class Jscript {
1.6. MATHEMATICAL OPERATOR 41
5 public static void main(String[] args) {
System.out.printf("Cosine at 22/7 radian is : %f n", Math.cos(22
/ 7));
7 System.out.printf("Sine at 22/7 radian is : %f n", Math.sin(22 /
7));
System.out.printf("Tangent at 22/7 radian is : %f n", Math.tan
(22 / 7));
9 }
}
✆
✞
Cosine at 22/7 radian is : -0.989992
Sine at 22/7 radian is : 0.141120
Tangent at 22/7 radian is : -0.142547
✆
acos, asin & atan
The acos() functions return the arccosine of their arguments in radians, and the
asin() functions return the arcsine of their arguments in radians. All functions
expect the argument in the range [−1, +1]. The arccosine returns a value in
the range [0, π]; the arcsine returns a value in the range
h
−
π
2
,
π
2
i
. The atan()
returns their argument value in radian in the range
h
−
π
2
,
π
2
i
. Method of use of
inverse function in following systems.
✞
1 double asin(double x);
double acos(double x);
3 double atan(double x);
✆
A simple example is
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.printf("Arc cosine at argument 0.5 is : %f n", Math.
acos(0.5));
7 System.out.printf("Arc sine at argument 0.5 is : %f n", Math.
asin(0.5));
System.out.printf("Arc tangent at argument 1.5 is : %f n", Math.
atan(1.5));
9 }
}
✆
✞
Arc cosine at argument 0.5 is : 1.047198
Arc sine at argument 0.5 is : 0.523599
Arc tangent at argument 1.5 is : 0.982794
✆
42 CHAPTER 1. INTRODUCTION
cosh, sinh & tanh
The cosh(), sinh() and tanh() functions compute the hyperbolic cosine, the
hyperbolic sine and the hyperbolic tangent of the argument respectively.
✞
1 double cosh(double x);
double sinh(double x);
3 double tanh(double x);
✆
A simple example is
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.printf("Hyperbolic cosine of 0.5 is : %f n", Math.
cosh(0.5));
7 System.out.printf("Hyperbolic sine of 0.5 is : %f n", Math.sinh
(0.5));
System.out.printf("Hyperbolic tangent of 1.5 is : %f n", Math.
tanh(1.5));
9 }
}
✆
✞
Hyperbolic cosine at argument 0.5 is : 1.127626
Hyperbolic sine at argument 0.5 is : 0.521095
Hyperbolic tangent at argument 1.5 is : 0.905148
✆
1.6.2 Logarithm Function
exp, log
exp() represents the exponential of a value x with base ‘e’. log() represents the
logarithm of a value in natural base ‘e’.
✞
1 double exp(double x);
double log(double x);
✆
A simple example is
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 System.out.printf("Exponential of 0.5 is : %f n", Math.exp(0.5))
;
System.out.printf("logarithm of 0.5 at base 10 is : %f n", Math.
log(0.5));
1.6. MATHEMATICAL OPERATOR 43
8 }
}
✆
✞
Exponential of 0.5 is : 1.648721
logarithm of 0.5 at base 10 is : -0.693147
✆
1.6.3 Arithmatic Function
pow, sqrt, floor, ceil & round
pow() makes second variable in power over the first variable. sqrt returns the
square root of a variable value. floor() rounded fraction to down. ceil() rounded
fraction to up and round() rounded up the number if fraction is equal or more
than 0.5.
✞
double pow(double x, double y);
2 double sqrt(double x);
double floor(double x);
4 double ceil(double x);
double round(double x);
✆
A simple example is
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.printf("Power of 2 on base 3 is : %f n", Math.pow(3,
2));
7 System.out.printf("Square root of 1.45 is : %f n", Math.sqrt
(1.45));
System.out.printf("Ceiling of 1.45 is : %f n", Math.ceil(1.45));
9 System.out.printf("Flooring of 1.4855 is : %f n", Math.floor
(1.4855));
System.out.printf("Rounding of 6.157 is : %d n", Math.round
(6.157));
11 }
}
✆
✞
Power of 2 on base 3 is : 9.000000
Square root of 1.45 is : 1.204159
Ceiling of 1.45 is : 2.000000
Flooring of 1.4855 is : 1.000000
Rounding of 6.157 is : 6
✆
44 CHAPTER 1. INTRODUCTION
Chapter 2
String & Arrays
2.1 Strings
The string constant “x” is not the same as the character constant i.e. ‘x’. One
difference is that ‘x’ is a basic type (charcode), but “x” is a derived type, an
array of char. A String class type deals specifically with sequences of character
data. A string is declared and intialized as
✞
1 /*Declaration of string*/
String s=new String();
3 /*Initialization of string*/
char chars[] = { ’a’, ’b’, ’c’, ’d’, ’e’ };
5 String s = new String(chars);
✆
A substring can also be intialized if String class is used like
✞
1 char chars[] = { ’a’, ’b’, ’c’, ’d’, ’e’ };
String s = new String(chars, <pos index>, <number of chars>);
✆
In String objects length() method returns the number of characters in the string.
✞
String s = new String();
2 int n=s.length();/*Length of string.*/
✆
Characters are indexed from 0 to length()-1, and can be accessed with the
✞
charAt(<index>)
✆
method. String objects are read-only.
✞
1 char ch;
ch = "abcdedf".charAt(1);/*character at index 1.*/
✆
45
46 CHAPTER 2. STRING & ARRAYS
2.2 Array
Arrays in Java stores data in a single variable name with an index, also known
as a subscript. It is simply a list or ordered grouping for variables of the same
type. Arrays often help a programmer in organize collections of data efficiently
and intuitively.
Declaring an Array In Java an array is declared by using keyword new like
✞
int[] ia = new int[3];
2 float[] ia = new float[3];
String[] sa=new String[10];
✆
Initialization an Array In java, an array can be initialized at the time of
declaration or later the time. Synopsis for the initialization of an array during
the time of declaration is
✞
1 int[] ia = new int[3]{1, 2, 3};
✆
✞
1 package jscript;
3 public class Jscript {
public static void main(String[] args) {
5 int[] ia = new int[]{1, 2, 3};
System.out.println(ia.length);
7 }
}
✆
✞
3
✆
Dynamic Array Size If the array is declared as shown below then size of
array is determined at the execution time.
✞
1 int[] ia=new int[/*No value here*/];
✆
✞
1 package jscript;
3 public class Jscript {
public static void main(String[] args) {
5 int[] ia = new int[/*No value here*/]{1, 2, 3, 1, 2, 3};
System.out.println(ia.length);
7 }
}
✆
✞
6
✆
2.2. ARRAY 47
2.2.1 Dyanmic Array
2.2.2 Uni-dimensional Array
Arrays are declared and initialized like
✞
1 int numbers[6]; // array declared
int point[6]={0,0,1,0,0,0}; // array initialized
✆
The square brackets [] identify ‘numbers’ or ‘points’ and the rest as arrays,
and the number enclosed in the brackets indicates the number of elements in
the array. An element of the array can be accessed by its index number. In
following example, each element of the array is accessed by its index number.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int i = 0;
int[] anArray = new int[4];
8 while (i < 4) {
anArray[i] = i;
10 System.out.println(anArray[i]);
i++;
12 }
}
14 }
✆
✞
0
1
2
3
✆
In the above example, the size of the array was not explicitly specified. The
compiler knows the size of array from the initialized list. The size of ‘anArray’
is ‘4’ because ‘anArray’ has four elements. Addition of an additional element
to the list will increase its size to five. Static declaration of the size of an array,
the array list will be overflow. To overcome this problem array is declared with
dynamic size.
2.2.3 Multi-dimensional Array
A multi-dimensional array can be declared as the synopsis given below.
✞
int[][] ia = new int[2][3];
2 /*OR*/
int[][] ia = new int[][]{{5, 2, 1},
4 {6, 7, 8}};
/*OR*/
48 CHAPTER 2. STRING & ARRAYS
6 int ia[][][] = new int[3][4][5];
✆
Where [2] represents to the number of rows and [3] represents to the number of
columns of the two dimensional array. Multi-dimensional array can be used to
add, subtract and product (either dot or cross) of two vectors or matrices.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) {
6 int ix, iy;
8 int[][] anArray = new int[5][5];
for (ix = 0; ix < 5; ++ix) {
10 for (iy = 0; iy < 5; ++iy) {
anArray[ix][iy] = ix * iy;
12 };
}
14 for (ix = 0; ix < 5; ++ix) {
for (iy = 0; iy < 5; ++iy) {
16 System.out.printf("%2dt", anArray[ix][iy]);
};
18 System.out.printf("n");
}
20 }
}
✆
✞
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
✆
2.2.4 Size of Array
In Java, size of array is obtained by using length object.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
int i = 0;
7 int[] anArray = new int[4];
System.out.println(anArray.length);
9 }
}
✆
2.3. CLASS, OBJECT & FUNCTION 49
✞
4
✆
2.3 Class, Object & Function
Like struct in C, java has classes and objects. Every object has a class that
defines its data and behavior. A class has (i) fields which are data variables
associated with a class and its objects. They stores results. (ii) Methods are
build from expressions and contain the executable code of a class. A public class
should be declared in a separate file having name as public class name. A class
is declared as
✞
1 class <class name>{
<scope> <data type> <var a>, <var b>;
3 }
✆
In following lines, class Trees is declared with two variables or fields.
✞
1 class Trees{
public char name;
3 public double length;
}
✆
Objects are created by expressions containing the new keyword. Creating an
object from a class definition is also known as instantiation; thus, objects are
often called instances.
✞
Trees t=new Trees();
✆
The members may be assigned a value as
✞
1 t.name="a";
✆
Again, the value of a class member can also be accessed by using
✞
1 t.name
/*or*/
3 t.length
✆
See example below:
✞
1 package jscript;
3 class Trees {
5 public char name;
public double length;
7 }
9 public class Jscript {
50 CHAPTER 2. STRING & ARRAYS
11 public static void main(String[] args) {
Trees t = new Trees();
13 t.name = 120;
t.length = 2;
15 System.out.println("Name of tree is " + t.name);
System.out.println("Length of tree is " + t.length);
17 }
}
✆
✞
Name of tree is x
Length of tree is 2.0
✆
A class can also have a return value to the caller by object method.
✞
package jscript;
2
class Box {
4
int length;
6 int width;
int height;
8
int Volume() {
10 return length * width * height;
}
12 }
14 public class Jscript {
16 public static void main(String[] args) {
Box b = new Box();
18 b.length = 2;
b.width = 1;
20 b.height = 3;
int vol = b.Volume();
22 System.out.printf("Volume of Box is %dn", vol);
}
24 }
✆
✞
Volume of Box is 6
✆
✞
1 package jscript;
/*Class*/
3
class myClass {
5
private String name;
7 private int age;
2.3. CLASS, OBJECT & FUNCTION 51
/*Object of the class and its initialization*/
9
public myClass(String name, int age) {
11 this.name = name;
this.age = age;
13 }
/*Object get name*/
15
public String getName() {
17 return name;
}
19 /*Object get age*/
21 public Object getAge() {
return age;
23 }
}
25
public class Jscript {
27
public static void main(String[] args) {
29 myClass sun = new myClass("Sooraj", 15);
System.out.printf("Name of person is %s.n", sun.getName());
31 System.out.printf("Name of person is %s.n", sun.getAge());
}
33 }
✆
✞
Name of person is Sooraj.
Name of person is 15.
✆
A class can also be accessed with arguments as shown in example below.
✞
package jscript;
2
class myClass {
4
public String name;
6 public int dis;
8 public myClass(String n, int d) {
name = n;
10 dis = d;
}
12 }
14 public class Jscript {
16 public static void main(String[] args) {
myClass sun = new myClass("Sooraj", 15);
18 System.out.printf("Distance of %s is %d.n", sun.name, sun.dis);
52 CHAPTER 2. STRING & ARRAYS
}
20 }
✆
✞
Distance of Sooraj is 15.
✆
Function in Java a group of statements and expressions which accepts inputs,
analyse them according to the statements and expressions and return the result.
There are no global functions in Java. The equivalent is to define static methods
in a class. Function overloading is allowed in java.
✞
1 public class <class name>{
public static <data type> <function name>(argument a, argument b) {
3 <expression>
}
5 }
✆
A function can be called by calling class name and envoking function name like
✞
1 <class name>.<function name>(argument a, argument b);
✆
Here, class name is the name of java file in which function is written. In the
following example, two files, Jscript.java and Sum.java are placed inside the
package jscript. The file containing main class is Jscrip.java and it contains the
codes given below.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.println("Sum of 2 and 3 is " + Sum.sum(2, 3));
7 }
}
✆
While the file containing Sum class and sum function is Sum.java and it contains
the codes given below.
✞
package jscript;
2
public class Sum {
4
public static int sum(int a, int b) {
6 return a + b;
}
8 }
✆
We call the sum function from main class as
✞
Sum.sum(2, 3)
✆
and the result given by program is
2.3. CLASS, OBJECT & FUNCTION 53
✞
Sum of 2 and 3 is 5
✆
2.3.1 Arguments
A functions accepts inputs through its arguments. A function with two argu-
ments is defined as
✞
1 public static int sum(int a, int b);
✆
Here, int a, int b are known as formal arguments. During the defining of a
function, each argument must be identified by its type. For example, to supply
two integer arguments to a function, it shall be defined like
✞
1 public static int sum(int a, int b);
✆
while, the definition of function as given below is illegal.
✞
1 public static int sum(int a, b);//Illegal definition
✆
Here, second argument ‘b’ is type unidentified. In Java, a function can be called
from anywhere by supplying actual arguments as
✞
1 Sum.sum(2, 3);
✆
See example below. Jscript.java contains the codes given below.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
System.out.println("Sum of 2 and 3 is " + Sum.sum(2, 3));
7 }
}
✆
Sum.java contains the codes given below.
✞
package jscript;
2
public class Sum {
4
public static int sum(int a, int b) {
6 return a + b;
}
8 }
✆
We call the sum function from the main class as
✞
Sum.sum(2, 3)
✆
and the result given by program is
54 CHAPTER 2. STRING & ARRAYS
✞
Sum of 2 and 3 is 5
✆
2.3.2 Prototyping
Function prototype allows to omit the variable name in its arguments. The legal
function prototyping are
✞
1 public static int sum(int, int); /*Illegal prototype.*/
public static int sum(int a, int b); /*Legal prototype.*/
3 public static int sum(a, int b); /*Illegal prototype.*/
✆
2.3.3 this Reference
The this reference is most commonly used as a way to pass a reference to the
current object as an argument to other methods or when the name of the field
are needed to access is hidden by a local variable or parameter declaration.
✞
1 package jscript;
3 class myClass {
5 public String name;/*Name field*/
public int dis; /*Distance field*/
7 /*Passed argument names are similar to field name.*/
public myClass(String name, int dis) {
9 /*To distict the field name from *
*argument this reference is used.*/
11 this.name = name;
this.dis = dis;
13 }
}
15
public class Jscript {
17
public static void main(String[] args) {
19 myClass sun = new myClass("Sooraj", 15);
System.out.printf("Distance of %s is %d.n", sun.name, sun.dis);
21 }
}
✆
✞
Distance of Sooraj is 15.
✆
If this reference is not used then code and result shall be looked like
✞
1 package jscript;
3 class myClass {
2.3. CLASS, OBJECT & FUNCTION 55
5 public String name;/*Name field*/
public int dis; /*Distance field*/
7 /*Passed argument names are similar to field name.*/
public myClass(String name, int dis) {
9 /*To distict the field name from argument *
*this reference is used. Here no reference*
11 *is used so that the field parameter does *
*not store the values of name and distance*/
13 name = name;
dis = dis;
15 }
}
17
public class Jscript {
19
public static void main(String[] args) {
21 myClass sun = new myClass("Sooraj", 15);
System.out.printf("Distance of %s is %d.n", sun.name, sun.dis);
23 }
}
✆
✞
Distance of null is 0.
✆
2.3.4 Field Declaration
A field can be declared as either annotations, access, static, final, transient or
volatile. A field cannot be both final and volatile. A static field is shared only
one instance by all objects of a class. A final variable is one whose value cannot
be changed after it has been initialized.
2.3.5 Inheritance
To inherit a class, one class is incorporate and defined in another class by using
the extends keyword.
✞
1 package jscript;
/*Creatign a super class*/
3 class BoxVol {
int l, w, h;
5 int Volume() {
return l * w * h;
7 }
}
9 /*Creating subclass extending to super class.*
*Here the variables and members of super are*
11 *accessed by object created for sub class. */
class BoxSur extends BoxVol {
56 CHAPTER 2. STRING & ARRAYS
13 int Surface() {
return 2 * (l * w + w * h + l * h);
15 }
}
17 public class Jscript {
public static void main(String[] args) {
19 /*Object cerated for box surface.*
*The scope of BoxSur is extende *
21 *to the BoxVol, hence variables *
*and all members of BoxVol are *
23 *accessible from created object.*/
BoxSur a = new BoxSur();
25 /*Access varibles of super class.*/
a.l = 2;
27 a.w = 1;
a.h = 3;
29 /*Fetch the member value of super class.*/
int vol = a.Volume();
31 System.out.printf("Volume of Box is %dn", vol);
/*Fetch the member value of sub class.*/
33 int sur = a.Surface();
System.out.printf("Surface Area of Box is %dn", sur);
35 }
}
✆
✞
Volume of Box is 6
Surface Area of Box is 22
✆
2.3.6 Function
In Java a function is defined as in language C. The return value of a function
may be integer, double, float, boolean or void type. A function is defined inside
the class as subclass. The synopsis of the function is
✞
int MyFunc(){
2 <expression>
}
✆
In following example, when a function is called it reset the value of ‘s’. And the
global value of ‘s’ is printed in output stream.
✞
1 package jscript;
3 public class Jscript {
/*To use s as global, it should be defined as static.*/
5 static double s = 0.0;
7 double MyFunc() {
s = 10;
2.4. THREADING 57
9 return s;
}
11
public static void main(String args[]) {
13
Jscript j = new Jscript();
15 j.MyFunc();
System.out.printf("s is %fn", s);
17 }
}
✆
✞
s is 10.000000
✆
2.3.7 Type of Objects
2.4 Threading
A thread is initiated by Thread object like
✞
1 Thread th = new Thread();
✆
In following example a thread is created.
✞
1 package jscript;
3 public class Jscript {
5 public static void main(String[] args) {
Thread th = new Thread();
7 System.out.println(th);
}
9 }
✆
✞
Thread[Thread-0,5,main]
✆
In following example,Jscript class is extended to Thread object.
✞
1 package jscript;
/*Class extended to Thread*/
3 public class Jscript extends Thread {
5 public static void main(String[] args) throws InterruptedException {
int i = 1;
7 for (;;) {
/*sleep method throws InterruptedException.*/
9 Thread.sleep(1000);
System.out.printf("Seconds passed %dn", i);
11 i++;
58 CHAPTER 2. STRING & ARRAYS
}
13 }
}
✆
✞
Seconds passed 1
Seconds passed 2
........
........
✆
Above example is rewritten and a new thread is initiated by using Thread object.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args) throws InterruptedException {
6 int i = 1;
/*Independent Thread is initiated.*/
8 Thread th = new Thread();
for (;;) {
10 /*sleep method throws InterruptedException.*/
th.sleep(1000);
12 System.out.printf("Seconds passed %dn", i);
i++;
14 }
}
16 }
✆
✞
Seconds passed 1
Seconds passed 2
........
........
✆
After a Thread object is created, it can be configured and run. A thread is
invoked by start() method. The virtual machine invokes the new thread’s run()
method, making the thread active. A thread can be invoked only once. Multiple
invoking of same thread results IllegalThreadStateException.
✞
package jscript;
2
public class Jscript {
4
public static void main(String[] args){
6 Thread th = new Thread();
System.out.printf("Invoking same thread multiple times.n");
8 /*Multiple involke throws IllegalThreadStateException.*/
th.start();
10 th.start();
}
12 }
✆
2.4. THREADING 59
While a thread is running we can interact with it in other ways. After activating
the thread, we need to perform some action. The Runnable interface declares a
single method:
✞
public void run();
✆
Actually the code inside the run() object does the real job.
✞
1 package jscript;
3 public class Jscript extends Thread {
5 private String word;
private int delay;
7
public Jscript(String w, int d) {
9 word = w;
delay = d;
11 }
13 @Override
public void run() {
15 try {
for (;;) {
17 System.out.printf(word + " n");
Thread.sleep(delay);
19 }
} catch (InterruptedException e) {
21 return;
}
23 }
25 public static void main(String[] args) {
new Jscript("ping", 1000).start();
27 new Jscript("PONG", 3000).start();
}
29 }
✆
✞
ping
PONG
ping
ping
PONG
✆
wait(), notify() and notifyAll() methods tells waiting threads that something
has occurred that might satisfy that condition. The wait() and notification
methods are defined in class Object and are inherited by all classes.
Name of thread can be changes by setName() method. See the example
below.
60 CHAPTER 2. STRING & ARRAYS
✞
1 package jscript;
3 public class Jscript extends Thread {
5 @Override
public void run() {
7 System.out.println("Running....");
}
9
public static void main(String args[]) {
11 Jscript th1 = new Jscript();
Jscript th2 = new Jscript();
13 System.out.println("Name of first thread is :" + th1.getName());
System.out.println("Name of second thread is :" + th2.getName());
15
th1.start();
17 th2.start();
/*Change the name of first thread.*/
19 th1.setName("Konark");
System.out.println("After changing name of first thread:" + th1.
getName());
21 /*Change the name of second thread.*/
th1.setName("Khajuraho");
23 System.out.println("After changing name of second thread :" + th1
.getName());
}
25 }
✆
✞
Name of first thread is :Thread-0
Name of second thread is :Thread-1
After changing name of first thread:Konark
After changing name of second thread :Khajuraho
Running....
Running....
✆
Priority of a thread is set by using setPriority() method. There are three types
of priorities - MIN PRIORITY, NORM PRIORITY and MAX PRIORITY.
✞
package jscript;
2
public class Jscript extends Thread {
4
@Override
6 public void run() {
/*Current thread tells the current running thread*/
8 System.out.println(Thread.currentThread().getPriority());
}
10
public static void main(String args[]) {
2.4. THREADING 61
12 Jscript th1 = new Jscript();
Jscript th2 = new Jscript();
14 System.out.println("Name of first thread is :" + th1.getName());
System.out.println("Name of second thread is :" + th2.getName());
16 /*Change the name of first thread.*/
th1.setName("Konark");
18 th1.setPriority(MIN_PRIORITY);
System.out.println("After changing name of first thread:" + th1.
getName());
20 /*Change the name of second thread.*/
th1.setName("Khajuraho");
22 th1.setPriority(MAX_PRIORITY);
System.out.println("After changing name of second thread :" + th1
.getName());
24 th1.start();
th2.start();
26 }
}
✆
✞
Name of first thread is :Thread-0
Name of second thread is :Thread-1
After changing name of first thread:Konark
After changing name of second thread :Khajuraho
10
5
✆
A running thread is joined by using join() method.
✞
package jscript;
2
public class Jscript extends Thread {
4
public void run() {
6 System.out.println("Running..");
}
8
public static void main(String args[]) {
10 Jscript th1 = new Jscript();
Jscript th2 = new Jscript();
12 Jscript th3 = new Jscript();
th1.start();
14 try {
th1.join();
16 } catch (Exception e) {
System.out.println(e);
18 }
th2.start();
20 th3.start();
}
22 }
✆
62 CHAPTER 2. STRING & ARRAYS
✞
Running..
Running..
Running..
✆
2.4.1 Exception Handling
In Java, when compiler encounters with errors it throws an exceptions. To run
the program, these errors must be caught by the invoking code. This invoking
code can handle the exception as needed and then continue executing. Uncaught
exceptions result in the termination of the thread of execution. Uncaught excep-
tions are reported by compiler. Exception objects are the Exception class, which
provides a string field to describe the error. All exceptions must be subclasses
of the class Throwable, which is the superclass of Exception. try-catch-finally
sequence is used to catch an Exception.
✞
1 package jscript;
3 public class Jscript extends Thread {
5 public static void main(String[] args) {
int i = 1;
7 Thread th = new Thread();
for (;;) {
9 try {/*Try to invoke thread by start method.*/
try {/*Try to invoke sleep thread.*/
11 th.sleep(2000);
}/*If any internal error occured *
13 *then catch the exception handle.*/
catch (InterruptedException ex) {
15 System.out.println("Sleep Interrupt Exception.");
}
17 th.start();
th.start();
19 } /*If any internal state error occured*
* then catch the exception handle. */
21 catch (IllegalThreadStateException ex) {
System.out.println("Illegal Thread State Exception.");
23 }
}
25 }
}
✆
✞
Illegal Thread State Exception.
Illegal Thread State Exception.
............
............
✆
Chapter 3
Accessing System Files
Standard Input-Output and access of files is a main part of computer program-
ming. In this chapter we shall discuss the importance and methodology of
accessing system and user define files.
3.1 Input Output
A Java program under execution opens automatically input and output streams.
The first standard stream is used for input buffering and the other used for
outputs. These streams are sequences of bytes. To read a character from a
BufferedReader, read() is used. Each time that read() is called, it reads a
character from the input stream and returns it as an integer value. It returns
-1 when the end of the stream is encountered.
✞
package jscript;
2 import java.io.*;
public class Jscript {
4 public static void main(String[] args) throws IOException {
char c;
6 BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter characters, ’q’ to quit.");
8 do {
c = (char) br.read();
10 System.out.println(c);
} while (c != ’q’);
12 }
}
✆
To read a line from input console, readLine() is used as shown in example below.
✞
1 package jscript;
import java.io.*;
3 public class Jscript {
63
64 CHAPTER 3. ACCESSING SYSTEM FILES
5 public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
7 String str;
System.out.println("Enter contents in each line.");
9 System.out.println("Enter ’stop’ to quit.");
do {
11 str = br.readLine();
System.out.println(str);
13 } while (!str.equals("stop"));
}
15 }
✆
Buffer space is created by the allocate() method at ByteBuffer class. To create
one megabyte buffer space, allocate() method is used as
✞
1 ByteBuffer buff = ByteBuffer.allocate(1024 * 1024);
✆
This method is in nio.* class.
✞
1 package jscript;
3 import java.nio.*;
5 public class Jscript {
7 public static void main(String[] args) {
ByteBuffer buff = ByteBuffer.allocate(1024 * 1024);
9 System.out.println(buff);
}
11 }
✆
✞
java.nio.HeapByteBuffer[pos=0 lim=1048576 cap=1048576]
✆
The read() method is used to place read data into buffer by using as
✞
1 inf.read(buff);
✆
If there is requirement to write data in ‘buff’ in out stream it must be converted
into write mode by using flip() method.
✞
1 buff.flip();
outf.write(buff);
✆
Other buffer types are ShortBuffer, IntBuffer, CharBuffer, FloatBuffer, Double-
Buffer and LongBuffer.
3.1.1 File Handling
Some times it is required to read, write and access a file to read or write some
contents to it.
3.1. INPUT OUTPUT 65
Open a File
FileInputStream class is used to open a file as shown in the following syntax.
✞
FileInputStream(String <file name>) throws FileNotFoundException
✆
Here, ‘file name’ specifies the name of the file that needed to be open. If file
does not exist to open FileNotFoundException is thrown.
✞
1 import java.io.*;
public class Jscript {
3 public static void main(String[] args) throws IOException {
int i;
5 FileInputStream fin;
try {
7 fin = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
9 System.out.println("File Not Found");
return;
11 }
fin.close();
13 }
}
✆
Again a new file can be created by using createNewFile() method. This method
first checks whether a named file is pre-exists or not. If exists, it does not
create new file with same name and returns false and throws an IOException.
If created then it returns true.
✞
package jscript;
2
import java.io.*;
4
public class Jscript {
6
public static void main(String[] args) throws IOException {
8 File f = new File("newfile.dat");
boolean success;
10 success = f.createNewFile();
if(success){
12 System.out.println("Created new file.");
}else{
14 System.out.println("Unable to create new file.");
}
16 }
}
✆
✞
Created new file.
✆
66 CHAPTER 3. ACCESSING SYSTEM FILES
Close a File
Any opened file shall be closed when it is not required or required by other
program to access it. Opened file is closed by using
✞
1 fin.close();
✆
Reading File
The contents of the file are read by using object read(). It returns the character
code read from the file. read() returns ‘-1’ when it encounters EOF.
✞
1 package jscript;
3 import java.io.*;
5 public class Jscript {
public static void main(String[] args) throws IOException {
7 int i;
FileInputStream fin;
9 try {
fin = new FileInputStream("test.txt");
11 } catch (FileNotFoundException e) {
System.out.println("File Not Found");
13 return;
}
15 do {
i = fin.read();
17 if (i != -1) {
System.out.print((char) i);
19 }
} while (i != -1);
21 fin.close();
}
23 }
✆
Writing File
FileOutputStream is used to create and write a file. The syntax for this class is
✞
1 FileOutputStream(String <file name>) throws FileNotFoundException
✆
Here, ‘file name’ specifies the name of the file that is to be created. If it is
unable to create a new file to write, FileNotFoundException is thrown. Any
pre-existing file is destroyed or overwritten. The contents are written to the file
by using write() method.
✞
1 package jscript;
3.1. INPUT OUTPUT 67
3 import java.io.*;
5 public class Jscript {
7 public static void main(String[] args) throws IOException {
int i = 0;
9 FileOutputStream fout;
try {
11 fout = new FileOutputStream("text.txt");
} catch (FileNotFoundException e) {
13 System.out.println("Unable to open a file");
return;
15 }
try {
17 do {
fout.write(i);
19 i++;
} while (i < 10);
21 } catch (IOException e) {
System.out.println("File Error");
23 }
fout.close();
25 }
}
✆
Temporary File
In Java, a temporary file is created by method createTempFile(). Compiler
throws errors if we try to create two temporary files with same name. To create
the temporary file in current temporary file, use following synopsis
✞
File <temp file name> = File.createTempFile(<name>, <ext>, cwd);
✆
✞
1 package jscript;
3 import java.io.*;
5 public class Jscript {
7 public static void main(String[] args) throws IOException {
File temp = File.createTempFile("tmp", ".tmp");
9 System.out.println(temp);
}
11 }
✆
✞
C:DOCUME~1ADMINI~1LOCALS~1Temptmp1895285192040487408.tmp
✆
To create temporary file anywhere you want then use following synopsis.
68 CHAPTER 3. ACCESSING SYSTEM FILES
✞
1 File loc = new File(<path>);
File <temp file name> = File.createTempFile(<name>, <ext>, loc);
✆
✞
package jscript;
2
import java.io.*;
4
public class Jscript {
6
public static void main(String[] args) throws IOException {
8 File loc = new File("d:/");
File temp = File.createTempFile("temp", ".tmp", loc);
10 System.out.println(temp);
}
12 }
✆
✞
d:temp7521897237899708714.tmp
✆
Before creation of temporary file of specific size, the required space in the direc-
tory should be known. To get the size of destination, getTotalSpace() method
is used.
✞
1 package jscript;
3 import java.io.*;
5 public class Jscript {
7 public static void main(String[] args){
File d = new File("d:/");
9 long ds = d.getTotalSpace();
System.out.println("Size of root D:/ is " + ds + "bytes.");
11 File e = new File("e:/");
long es = e.getTotalSpace();
13 System.out.println("Size of root E:/ is " + es + "bytes.");
}
15 }
✆
✞
Size of root D:/ is 110637346816bytes.
Size of root E:/ is 117942775808bytes.
✆
Memory Mapped I/O
In the nio.* class, The MappedByteBuffer class maps a file directly into a Byte-
Buffer. It can be operatred by using put( ), get( ), putInt( ), getInt( ) and other
methods. put( ) and get( ) access the file directly without copying a lot of data
to and from RAM. The synopsis of it is
3.1. INPUT OUTPUT 69
✞
MappedByteBuffer buff
2 = <file channel>.map(FileChannel.MapMode.<file mode>, <position>, <
size>);
✆
The ‘file mode’ operations are READ ONLY, READ WRITE and PRIVATE.
✞
package jscript;
2
import java.io.*;
4 import java.nio.*;
import java.nio.channels.*;
6
public class Jscript {
8
public static void main(String[] args) throws IOException {
10 /*Open new file.*/
File file = new File("test.txt");
12 /*Get file stream.*/
FileInputStream fis = new FileInputStream(file);
14 /*Try to get the channel of the opened file stream.*/
try (FileChannel fc = fis.getChannel()) {
16 /*Get the size of file.*/
long size = fc.size();
18 /*Map the file data from the file channel.*/
MappedByteBuffer bb =
20 fc.map(FileChannel.MapMode.READ_ONLY, 0, size);
22 for (int i = 0; i < size; i++) {
try {
24 /*Do what you need the mapped data.*/
System.out.println(i+" -> "+bb.get(i));
26 } catch (Exception e) {
}
28 }
}
30 }
}
✆
MappedByteBuffer has three methods, force( ), load( ), and isLoaded( ). The
load( ) method attempts to load the entire buffer into main memory. If the
data is larger than Java’s heap size, this is likely to cause some page faults and
disk thrashing. The isLoaded( ) method tells whether a buffer is loaded. To put
data in a MappedByteBuffer, force( ) method is used.
Random Access File
In Java, normally a file stream is started accessing data from beginning. To
access the data of a file from a specific position, RandomAccessFile class is
used. The synopsis of it is
70 CHAPTER 3. ACCESSING SYSTEM FILES
✞
1 RandomAccessFile rs=new RandomAccessFile(<file name>, <access mode>);
✆
In Java, there is no write only access mode, so read and write both mode are
used commonly. The getFilePointer( ) and seek( ) methods allow to query and
change the position in the file at which reads and writes occur.
✞
1 package jscript;
3 import java.io.*;
5 public class Jscript {
7 public static void main(String[] args) throws IOException {
File file = new File("test.txt");
9 RandomAccessFile rf = new RandomAccessFile(file, "rw");
rf.seek(10);
11 long rfp1 = rf.getFilePointer();
System.out.println("Current position of file is " + rfp1);
13 rf.seek(0);
long rfp2 = rf.getFilePointer();
15 System.out.println("Current position of file is " + rfp2);
rf.close();
17 }
}
✆
✞
Current position of file is 10
Current position of file is 0
✆
✞
skipBytes(<bytes number>)
✆
skipBytes() skips a file by ‘n’ bytes from the current position of the file. close()
method is used to close the current open file.
✞
1 package jscript;
3 import java.io.*;
5 public class Jscript {
7 public static void main(String[] args) throws IOException {
File file = new File("test.txt");
9 RandomAccessFile rf = new RandomAccessFile(file, "rw");
rf.seek(10);
11 long rfp1 = rf.getFilePointer();
System.out.println("Current position of file is " + rfp1);
13 rf.skipBytes(10);
long rfp2 = rf.getFilePointer();
15 System.out.println("Current position of file is " + rfp2);
rf.close();
3.1. INPUT OUTPUT 71
17 }
}
✆
✞
Current position of file is 10
Current position of file is 20
✆
File Pointer to Class
3.1.2 File Directory
Sometimes user needs to read, create, delete or change a directory. In this
section we will use specific functions related with handling of a directory.
Finding Roots
To get the system partitions, listRoots() method is used for listing of roots. This
method returns the array of all disk partitions, i.e. roots.
✞
package jscript;
2
import java.io.*;
4 public class Jscript {
public static void main(String[] args) {
6 /*Get the array of roots.*/
File[] roots = File.listRoots( );
8 /*Print all root names.*/
for (int i = 0; i < roots.length; i++) {
10 System.out.println(roots[i]);
}
12 }
}
✆
✞
C:
D:
E:
F:
H:
✆
File Object
File deals directly with files and the file system. The File class describes the
properties of a file itself. A File object is used to obtain or manipulate the
information associated with a disk file, such as the permissions, time, date, and
directory path, and to navigate subdirectory hierarchies. The syntax of File is
✞
1 File(<path or URI of file>);
✆
72 CHAPTER 3. ACCESSING SYSTEM FILES
There are several objects which tell information about the file’s name, its path,
its size, is a file, is a directory, is readable, is writable, make directory etc. Few
of then are used in the following example for file “test.txt”.
✞
1 package jscript;
3 import java.io.File;
5 public class Jscript {
7 public static void main(String[] args) {
File f1 = new File("test.txt");
9 System.out.println(f1.getName());/*test.txt*/
System.out.println(f1.getPath());/*test.txt*/
11 System.out.println(f1.canRead());/*true*/
System.out.println(f1.canWrite());/*true*/
13 System.out.println(f1.exists());/*true*/
System.out.println(f1.isFile());/*true*/
15 System.out.println(f1.length());/*210 (in bytes)*/
}
17 }
✆
✞
test.txt
test.txt
true
true
true
true
210
✆
Directory
A directory is a File that contains a list of other files and directories. We can
create a File object and checked whether its is a directory or not by isDirectory()
method. Other files can be listed by using method list() on the object to extract
the list of other files and directories inside. Its synopsis is
✞
1 <file object>.list();
✆
The list of files is returned in an array of String objects.
✞
1 package jscript;
3 import java.io.File;
5 public class Jscript {
7 public static void main(String[] args) {
File f1 = new File("./");
3.1. INPUT OUTPUT 73
9 if (f1.isDirectory()) {
String flist[] = f1.list();
11 for (int i = 0; i < flist.length; i++) {
System.out.println(flist[i]);
13 }
}
15 }
}
✆
✞
build
build.xml
manifest.mf
nbproject
src
test.txt
text.txt
✆
mkdir( ) method creates a directory, returning true on success and false on
failure. Failure indicates that the path specified in the File object already exists,
or that the directory cannot be created because the entire path does not exist
yet. To create a directory for which no path exists, use the mkdirs() method.
It creates both a directory and all the parents of the directory.
✞
1 package jscript;
3 import java.io.File;
5 public class Jscript {
7 public static void main(String[] args) {
File f1 = new File("ak");
9 boolean i = f1.mkdir();
System.out.println(i);
11 }
}
✆
A file or directory can be delete by delete() method. It returns true on successful
and false on failure. Failure indicates either file or directory does not exist.
✞
package jscript;
2
import java.io.File;
4
public class Jscript {
6
public static void main(String[] args) {
8 File f1 = new File("ak");
boolean i = f1.mkdir();
10 System.out.println(i);
}
74 CHAPTER 3. ACCESSING SYSTEM FILES
12 }
✆
A file or directory can be rename by renameTo() method. It returns true on
successful and false on failure. Failure indicates either file or directory either
does not exist or can not be renamed.
✞
package jscript;
2
import java.io.File;
4
public class Jscript {
6
public static void main(String[] args) {
8 File f1 = new File("test.txt");
File f2 = new File("ab.txt");
10 f1.mkdir();
boolean i = f1.renameTo(f2);
12 System.out.println(i);
}
14 }
✆
3.2 JNI

More Related Content

What's hot

Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Principle of Angular Motion - Physics - An Introduction by Arun Umrao
Principle of Angular Motion - Physics - An Introduction by Arun UmraoPrinciple of Angular Motion - Physics - An Introduction by Arun Umrao
Principle of Angular Motion - Physics - An Introduction by Arun Umraossuserd6b1fd
 
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimization
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimizationDavid_Mateos_Núñez_thesis_distributed_algorithms_convex_optimization
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimizationDavid Mateos
 
Principle of Derivative Calculus - Differential Calculus - An Introduction by...
Principle of Derivative Calculus - Differential Calculus - An Introduction by...Principle of Derivative Calculus - Differential Calculus - An Introduction by...
Principle of Derivative Calculus - Differential Calculus - An Introduction by...ssuserd6b1fd
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...ssuserd6b1fd
 
Reading Materials for Operational Research
Reading Materials for Operational Research Reading Materials for Operational Research
Reading Materials for Operational Research Derbew Tesfa
 
Morton john canty image analysis and pattern recognition for remote sensing...
Morton john canty   image analysis and pattern recognition for remote sensing...Morton john canty   image analysis and pattern recognition for remote sensing...
Morton john canty image analysis and pattern recognition for remote sensing...Kevin Peña Ramos
 
Principles of Linear Motion of Objects - Physics - Explained by Arun Umrao
Principles of Linear Motion of Objects - Physics - Explained by Arun UmraoPrinciples of Linear Motion of Objects - Physics - Explained by Arun Umrao
Principles of Linear Motion of Objects - Physics - Explained by Arun Umraossuserd6b1fd
 
Location In Wsn
Location In WsnLocation In Wsn
Location In Wsnnetfet
 

What's hot (12)

Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Principle of Angular Motion - Physics - An Introduction by Arun Umrao
Principle of Angular Motion - Physics - An Introduction by Arun UmraoPrinciple of Angular Motion - Physics - An Introduction by Arun Umrao
Principle of Angular Motion - Physics - An Introduction by Arun Umrao
 
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimization
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimizationDavid_Mateos_Núñez_thesis_distributed_algorithms_convex_optimization
David_Mateos_Núñez_thesis_distributed_algorithms_convex_optimization
 
Principle of Derivative Calculus - Differential Calculus - An Introduction by...
Principle of Derivative Calculus - Differential Calculus - An Introduction by...Principle of Derivative Calculus - Differential Calculus - An Introduction by...
Principle of Derivative Calculus - Differential Calculus - An Introduction by...
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
 
Thats How We C
Thats How We CThats How We C
Thats How We C
 
Reading Materials for Operational Research
Reading Materials for Operational Research Reading Materials for Operational Research
Reading Materials for Operational Research
 
Morton john canty image analysis and pattern recognition for remote sensing...
Morton john canty   image analysis and pattern recognition for remote sensing...Morton john canty   image analysis and pattern recognition for remote sensing...
Morton john canty image analysis and pattern recognition for remote sensing...
 
Principles of Linear Motion of Objects - Physics - Explained by Arun Umrao
Principles of Linear Motion of Objects - Physics - Explained by Arun UmraoPrinciples of Linear Motion of Objects - Physics - Explained by Arun Umrao
Principles of Linear Motion of Objects - Physics - Explained by Arun Umrao
 
MSC-2013-12
MSC-2013-12MSC-2013-12
MSC-2013-12
 
Location In Wsn
Location In WsnLocation In Wsn
Location In Wsn
 

Similar to Java Programming Notes for Beginners by Arun Umrao

Francois fleuret -_c++_lecture_notes
Francois fleuret -_c++_lecture_notesFrancois fleuret -_c++_lecture_notes
Francois fleuret -_c++_lecture_noteshamza239523
 
Fortran programming help book
Fortran programming help bookFortran programming help book
Fortran programming help bookArun Umrao
 
Modelica programming help book
Modelica programming help bookModelica programming help book
Modelica programming help bookArun Umrao
 
Introduction to Programming Using Java v. 7 - David J Eck - Inglês
Introduction to Programming Using Java v. 7 - David J Eck - InglêsIntroduction to Programming Using Java v. 7 - David J Eck - Inglês
Introduction to Programming Using Java v. 7 - David J Eck - InglêsMarcelo Negreiros
 
javanotes5.pdf
javanotes5.pdfjavanotes5.pdf
javanotes5.pdfkmspega
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..python learn basic tutorial learn easy..
python learn basic tutorial learn easy..MURTHYVENKAT2
 
Introduction to c++ (cpp)
Introduction to c++ (cpp)Introduction to c++ (cpp)
Introduction to c++ (cpp)Arun Umrao
 
Algorithmic Problem Solving with Python.pdf
Algorithmic Problem Solving with Python.pdfAlgorithmic Problem Solving with Python.pdf
Algorithmic Problem Solving with Python.pdfEmily Smith
 
Learn python the right way
Learn python the right wayLearn python the right way
Learn python the right wayDianaLaCruz2
 
Uni leicester
Uni leicesterUni leicester
Uni leicesterN/A
 
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
 
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfPython_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfjankoabel2022
 
C++ For Quantitative Finance
C++ For Quantitative FinanceC++ For Quantitative Finance
C++ For Quantitative FinanceASAD ALI
 
Xcos simulation
Xcos simulationXcos simulation
Xcos simulationArun Umrao
 

Similar to Java Programming Notes for Beginners by Arun Umrao (20)

tutorial.pdf
tutorial.pdftutorial.pdf
tutorial.pdf
 
Francois fleuret -_c++_lecture_notes
Francois fleuret -_c++_lecture_notesFrancois fleuret -_c++_lecture_notes
Francois fleuret -_c++_lecture_notes
 
Fortran programming help book
Fortran programming help bookFortran programming help book
Fortran programming help book
 
Modelica programming help book
Modelica programming help bookModelica programming help book
Modelica programming help book
 
Javanotes6 linked
Javanotes6 linkedJavanotes6 linked
Javanotes6 linked
 
Introduction to Programming Using Java v. 7 - David J Eck - Inglês
Introduction to Programming Using Java v. 7 - David J Eck - InglêsIntroduction to Programming Using Java v. 7 - David J Eck - Inglês
Introduction to Programming Using Java v. 7 - David J Eck - Inglês
 
javanotes5.pdf
javanotes5.pdfjavanotes5.pdf
javanotes5.pdf
 
python learn basic tutorial learn easy..
python learn basic tutorial learn easy..python learn basic tutorial learn easy..
python learn basic tutorial learn easy..
 
Javanotes5 linked
Javanotes5 linkedJavanotes5 linked
Javanotes5 linked
 
Introduction to c++ (cpp)
Introduction to c++ (cpp)Introduction to c++ (cpp)
Introduction to c++ (cpp)
 
Algorithmic Problem Solving with Python.pdf
Algorithmic Problem Solving with Python.pdfAlgorithmic Problem Solving with Python.pdf
Algorithmic Problem Solving with Python.pdf
 
Learn python the right way
Learn python the right wayLearn python the right way
Learn python the right way
 
Perltut
PerltutPerltut
Perltut
 
Uni leicester
Uni leicesterUni leicester
Uni leicester
 
c programming
c programmingc programming
c programming
 
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
 
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfPython_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
 
C++ For Quantitative Finance
C++ For Quantitative FinanceC++ For Quantitative Finance
C++ For Quantitative Finance
 
Xcos simulation
Xcos simulationXcos simulation
Xcos simulation
 
Programming
ProgrammingProgramming
Programming
 

More from ssuserd6b1fd

Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraossuserd6b1fd
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umraossuserd6b1fd
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraossuserd6b1fd
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umraossuserd6b1fd
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...ssuserd6b1fd
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...ssuserd6b1fd
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umraossuserd6b1fd
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umraossuserd6b1fd
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umraossuserd6b1fd
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umraossuserd6b1fd
 
Limit & Continuity of Functions - Differential Calculus by Arun Umrao
Limit & Continuity of Functions - Differential Calculus by Arun UmraoLimit & Continuity of Functions - Differential Calculus by Arun Umrao
Limit & Continuity of Functions - Differential Calculus by Arun Umraossuserd6b1fd
 
Principle of Integration - Basic Introduction - by Arun Umrao
Principle of Integration - Basic Introduction - by Arun UmraoPrinciple of Integration - Basic Introduction - by Arun Umrao
Principle of Integration - Basic Introduction - by Arun Umraossuserd6b1fd
 
Principle of Integral Applications - Integral Calculus - by Arun Umrao
Principle of Integral Applications - Integral Calculus - by Arun UmraoPrinciple of Integral Applications - Integral Calculus - by Arun Umrao
Principle of Integral Applications - Integral Calculus - by Arun Umraossuserd6b1fd
 
Principle of Function Analysis - by Arun Umrao
Principle of Function Analysis - by Arun UmraoPrinciple of Function Analysis - by Arun Umrao
Principle of Function Analysis - by Arun Umraossuserd6b1fd
 

More from ssuserd6b1fd (19)

Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umrao
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umrao
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umrao
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umrao
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umrao
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
 
Limit & Continuity of Functions - Differential Calculus by Arun Umrao
Limit & Continuity of Functions - Differential Calculus by Arun UmraoLimit & Continuity of Functions - Differential Calculus by Arun Umrao
Limit & Continuity of Functions - Differential Calculus by Arun Umrao
 
Principle of Integration - Basic Introduction - by Arun Umrao
Principle of Integration - Basic Introduction - by Arun UmraoPrinciple of Integration - Basic Introduction - by Arun Umrao
Principle of Integration - Basic Introduction - by Arun Umrao
 
Principle of Integral Applications - Integral Calculus - by Arun Umrao
Principle of Integral Applications - Integral Calculus - by Arun UmraoPrinciple of Integral Applications - Integral Calculus - by Arun Umrao
Principle of Integral Applications - Integral Calculus - by Arun Umrao
 
Principle of Function Analysis - by Arun Umrao
Principle of Function Analysis - by Arun UmraoPrinciple of Function Analysis - by Arun Umrao
Principle of Function Analysis - by Arun Umrao
 

Recently uploaded

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 

Recently uploaded (20)

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 

Java Programming Notes for Beginners by Arun Umrao

  • 2. 2
  • 3. Contents 1 Introduction 7 1.1 Data In & Data Out . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.1.1 Print Output . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.1.2 Formatted Output . . . . . . . . . . . . . . . . . . . . . . 8 1.1.3 Escape Characters . . . . . . . . . . . . . . . . . . . . . . 10 1.1.4 Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.1.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.1.6 Variables & Data Type . . . . . . . . . . . . . . . . . . . 12 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Character . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Short . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Float Decimals . . . . . . . . . . . . . . . . . . . . . . . . 14 Double Decimals . . . . . . . . . . . . . . . . . . . . . . . 15 Declaration, Initialization & Assignment . . . . . . . . . . 15 Signed & Unsigned Integer . . . . . . . . . . . . . . . . . 16 Overflow of Data . . . . . . . . . . . . . . . . . . . . . . . 17 Cast Operators . . . . . . . . . . . . . . . . . . . . . . . . 17 Scope of Variables . . . . . . . . . . . . . . . . . . . . . . 18 1.1.7 Access Controll . . . . . . . . . . . . . . . . . . . . . . . . 19 private . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 package . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 protected . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 public . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.2 Java Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.2.1 Expression . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.2.2 Unary Operaors . . . . . . . . . . . . . . . . . . . . . . . 19 1.2.3 Binary Relations . . . . . . . . . . . . . . . . . . . . . . . 20 1.2.4 Logical Relations . . . . . . . . . . . . . . . . . . . . . . . 22 1.2.5 Precedence of Relational Operators . . . . . . . . . . . . . 24 1.2.6 Bitwise Operator . . . . . . . . . . . . . . . . . . . . . . . 25 1.2.7 Shift Operator . . . . . . . . . . . . . . . . . . . . . . . . 27 1.2.8 Condition & Relation . . . . . . . . . . . . . . . . . . . . 29 3
  • 4. 4 CONTENTS 1.2.9 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . 30 1.2.10 Precedence of Arithmatic Operators . . . . . . . . . . . . 31 1.2.11 Relational Operators . . . . . . . . . . . . . . . . . . . . . 32 1.3 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 1.3.1 if condition . . . . . . . . . . . . . . . . . . . . . . . . . . 33 1.3.2 if-else condition . . . . . . . . . . . . . . . . . . . . . . . . 33 1.3.3 switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 1.4 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 1.4.1 for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 1.4.2 while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 1.4.3 For Loop Like While Loop . . . . . . . . . . . . . . . . . . 38 1.5 Parsing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 39 1.6 Mathematical Operator . . . . . . . . . . . . . . . . . . . . . . . 40 1.6.1 Trigonometric Functions . . . . . . . . . . . . . . . . . . . 40 cos, sin & tan . . . . . . . . . . . . . . . . . . . . . . . . . 40 acos, asin & atan . . . . . . . . . . . . . . . . . . . . . . . 41 cosh, sinh & tanh . . . . . . . . . . . . . . . . . . . . . . . 42 1.6.2 Logarithm Function . . . . . . . . . . . . . . . . . . . . . 42 exp, log . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 1.6.3 Arithmatic Function . . . . . . . . . . . . . . . . . . . . . 43 pow, sqrt, floor, ceil & round . . . . . . . . . . . . . . . . 43 2 String & Arrays 45 2.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.2 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.2.1 Dyanmic Array . . . . . . . . . . . . . . . . . . . . . . . . 46 2.2.2 Uni-dimensional Array . . . . . . . . . . . . . . . . . . . . 46 2.2.3 Multi-dimensional Array . . . . . . . . . . . . . . . . . . . 47 2.2.4 Size of Array . . . . . . . . . . . . . . . . . . . . . . . . . 48 2.3 Class, Object & Function . . . . . . . . . . . . . . . . . . . . . . 49 2.3.1 Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 53 2.3.2 Prototyping . . . . . . . . . . . . . . . . . . . . . . . . . . 54 2.3.3 this Reference . . . . . . . . . . . . . . . . . . . . . . . . . 54 2.3.4 Field Declaration . . . . . . . . . . . . . . . . . . . . . . . 55 2.3.5 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 55 2.3.6 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 2.3.7 Type of Objects . . . . . . . . . . . . . . . . . . . . . . . 57 2.4 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 2.4.1 Exception Handling . . . . . . . . . . . . . . . . . . . . . 62 3 Accessing System Files 63 3.1 Input Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 3.1.1 File Handling . . . . . . . . . . . . . . . . . . . . . . . . . 64 Open a File . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Close a File . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Reading File . . . . . . . . . . . . . . . . . . . . . . . . . 66
  • 5. CONTENTS 5 Writing File . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Temporary File . . . . . . . . . . . . . . . . . . . . . . . . 67 Memory Mapped I/O . . . . . . . . . . . . . . . . . . . . 68 Random Access File . . . . . . . . . . . . . . . . . . . . . 69 File Pointer to Class . . . . . . . . . . . . . . . . . . . . . 71 3.1.2 File Directory . . . . . . . . . . . . . . . . . . . . . . . . . 71 Finding Roots . . . . . . . . . . . . . . . . . . . . . . . . 71 File Object . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.2 JNI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
  • 7. Chapter 1 Introduction Here we have use Netbean IDE for java programming. 1.1 Data In & Data Out In Java, input and output is received and sent through standard input and output stream. The input is accepted via in stream while output is sent via out stream. Java has strong grouping convention. Function or block domain are limited by curly braces, ie {...}. All the variable defined inside the {...} have local scope. A semicolon is used to terminate the line. 1.1.1 Print Output We can print the output in out stream via system i/o class. Se example below, in which “Hi” is printed in output stream. ✞ 1 package jscript; /*Jscript is main class name. It shall be same as* 3 *file name. i.e. file name must be jscript.java*/ public class Jscript { 5 public static void main(String[] args) { 7 System.out.println("Hi"); } 9 } ✆ ✞ Hi ✆ When a java program is run, it starts execution from the main() function. This main() function is defined here as public so that it can be executed from anywhere. Its return type is void, i.e. no return value. In the following line ✞ 1 public static void main(String[] args) {} ✆ 7
  • 8. 8 CHAPTER 1. INTRODUCTION (String[] args) receives the string array from the commandline. Number of input arrays are counted by using length object. In java, class name shall be same as its file name where it is declared. Here println is similar to the printf of C. 1.1.2 Formatted Output In Java, values or variables can be placed inside the string by using ‘+’ sign as shown in example below. ✞ 1 package jscript; /*Jscript is main class name. It shall be same as* 3 *file name. i.e. file name must be jscript.java*/ public class Jscript { 5 public static void main(String[] args) { 7 System.out.println("Hi "+10+" ."); } 9 } ✆ ✞ Hi 10 . ✆ Here, println is short form of print a line and it prints the string at output stream. printf is short form of print formatted and it can be used in place of println for formatted output. ✞ 1 package jscript; /*Jscript is main class name. It shall be same as* 3 *file name. i.e. file name must be jscript.java*/ 5 public class Jscript { 7 public static void main(String[] args) { System.out.printf("Hi %d.n", 10); 9 } } ✆ ✞ Hi 10. ✆ In Java, modifiers are used to print formatted outputs. A modifier ‘%s’ simply puts the string by creating space equal to the length of string. If this modifier is redefined like ‘%20s’ (a positive integer between % and ‘s’ symbols), then space for 20 characters is created. If string length is less than 20 characters then ‘ ’ (space) is prefixed to the string to increase its length to 20. If number in modifier is less than the length of string then nothing is done. ✞ 1 package jscript; 3 public class Jscript {
  • 9. 1.1. DATA IN & DATA OUT 9 Symbolic Constant Represents %a Floating-point number, hexadecimal digits and p- notation. %A Floating-point number, hexadecimal digits and P- notation. %c Single character. %d Signed decimal integer. %e Floating-point number in e-notation form. %E Floating-point number in e-notation form. %f Floating-point number in decimal notation form. %g If the exponent is less than 4 or greater than or equal to the precision %e used otherwise %f is used. %G If the exponent is less than 4 or greater than or equal to the precision %E used otherwise %F is used. %i Signed decimal integer. %o Unsigned octal integer. %p A pointer. %s Character string. %u Unsigned decimal integer. %x Unsigned hexadecimal integer using hex digits 0f. %X Unsigned hexadecimal integer using hex digits 0F. %% Prints a percent sign. Table 1.1: Conversion specifiers.
  • 10. 10 CHAPTER 1. INTRODUCTION 5 public static void main(String[] args) { System.out.printf(""%s" secured numbers "%d"n", "Arun Kumar" , 100); 7 System.out.printf(""%20s" secured numbers "%5d"n", "Arun Kumar", 100); } 9 } ✆ ✞ "Arun Kumar" secured numbers "100" " Arun Kumar" secured numbers " 100" ✆ For numeric modifiers, total spaces and filled space can also be used simulta- neously if modifier is modified like ‘%10.6d’. Here number ‘10’ will create 10 spaces for placing a number and if digits in number is less than ‘6’ then ‘0’ will be prefixed with the number. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i; System.out.printf("%5s%10s%10sn", "Num", "Square", "Cubic"); 8 for (i = 90; i < 92; i++) { System.out.printf("%5d%10d%10dn", i, i * i, i * i * i); 10 } } 12 } ✆ ✞ Num Square Cubic 90 8100 729000 91 8281 753571 ✆ 1.1.3 Escape Characters Escape characters are used to perform action even if they are used as string. For example ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.println("Rajasthan"); 7 } } ✆ n at the end of println function would add a new line after “Rajasthan!”. The output of the program is
  • 11. 1.1. DATA IN & DATA OUT 11 ✞ Rajasthan ✆ Other escape characters are Escape Character Meaning t Adding a tab n Start a new line 1.1.4 Quotes In Java, double quotes is used to represents a group of character as a string. Single quote represents to character code in decimal equivalent. ✞ package jscript; 2 /*Jscript is main class name. It shall be same as* *file name. i.e. file name must be jscript.java*/ 4 public class Jscript { 6 public static void main(String[] args) { System.out.println("Uttar Pradesh."); 8 } } ✆ ✞ Uttar Pradesh. ✆ ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { char a = ’a’; 7 System.out.println(a); } 9 } ✆ ✞ a ✆ 1.1.5 Comments Commenting is most useful feature of the Java programming. It is used to write comments before or after a function or variable. Stuff within the commenting delimiters is ignored during compilation of the program. There are two type of commenting delimiters. First, single line commenting delimiter and second, multi-line commenting delimiter. For single line commenting ‘//’ is used and for multi-line commenting ‘/* ... */’ is used.
  • 12. 12 CHAPTER 1. INTRODUCTION ✞ 1 /* * Multiline comments 3 */ package jscript; 5 public class Jscript { 7 public static void main(String[] args) { 9 //Print cost of pen System.out.println("Cost of pen is "+10); 11 } } ✆ The output of above program is ✞ Cost of pen is 10 ✆ 1.1.6 Variables & Data Type Variables are multicharacter names used to refer to some locations in memory that holds a value to which we are working. A variable is equivalent to its assigned value. A variable may be alphanumeric name with underscope charac- ter. First numeric character of a variable name is not acceptable. Spaces and special characters which are reserved for internal operations of Java are illegal. Similarly, use of comma, dot, symbol of question mark, symbols reserved for realtion operations, symbols reserved for bitwise operations, colon and line ter- minating symbol are also considered as illegal if used in variable names. Key words specially reserved for internal programming of Java, can not be used like variable name. A list of reserved keyword is given in section ??. ✞ 1 int A1; // Legal and acceptable. int 1A; // Illegal, first character is numeric 3 int A_1;// Legal, _ is acceptable int A$1;// Legal, $ is not reserved character 5 int A 1;// Illegal, space is not acceptable int for;// Illegal, for is reserved keyword ✆ A variable declared once can not be declared again. Boolean Java has dedicated boolean type. Its value is either true or false. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) {
  • 13. 1.1. DATA IN & DATA OUT 13 6 System.out.println("Function is " + false); } 8 } ✆ ✞ Function is false ✆ Character char is used to initialize a 18 bit unsigned unicode character. ✞ 1 char *<var name>=<char code>; ✆ A char variable without initialization is not acceptable in java. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { char A1=100; 7 System.out.println("Char is " + A1); 9 } } ✆ ✞ Char is d ✆ Byte It is one byte long integer value. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { byte i = 120; 7 System.out.println("i is " + i); } 9 } ✆ ✞ i is 120 ✆ If the variable ‘i’ is assigned the integer value larger than 8 bits then compiler shows error and refuse to compile the program.
  • 14. 14 CHAPTER 1. INTRODUCTION Short It is two byte long integer value. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { byte i = 510; 7 System.out.println("i is " + i); } 9 } ✆ ✞ i is 510 ✆ If the variable ‘i’ is assigned the integer value larger than 16 bits then compiler shows error and refuse to compile the program. Integer A 4 byte long numerical value is declared and initialized by using primitive data type int. If an integer variable is initialized as decimal number, then compiler refuse to compile the program. ✞ 1 int <var name>; int <var name>=<value>; ✆ ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i=10; System.out.println("i is " + i); 8 } } ✆ ✞ i is 10 ✆ Float Decimals This data type is floating-point type. It usually referred to as a single-precision floating-point. Float-to-integer or integer-to-float type conversion of numbers take place by casting the number. It is 4 byte long. Its range is from 1.2×10−38 to 1.2 × 1038 . Syntax for the float data type is
  • 15. 1.1. DATA IN & DATA OUT 15 ✞ 1 float <var name>; float <var name>= (float) <decimal value>; ✆ See the example below. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 float i = (float) 10.126; System.out.println("i is " + i); 8 } } ✆ ✞ i is 10.126 ✆ Double Decimals This data type is floating-point type. It usually referred to as a double-precision floating-point. Double-to-integer or integer-to-double type conversion of num- bers take place by casting the number. It is 8 bytes long. Its range is from 2.3 × 10−308 to 2.3 × 10308 . Syntax for the double data type is ✞ 1 double <var name>; double <var name>=<decimal value>; ✆ See the example below. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 double i = 1.12416; System.out.println("i is " + i); 8 } } ✆ ✞ i is 1.12416 ✆ Declaration, Initialization & Assignment A variable in Java can be assigned as integer, if syntax is defined as given below: ✞ 1 int variable_name; ✆
  • 16. 16 CHAPTER 1. INTRODUCTION It means there is some space declared in data to store integer value. Multiple variables can be assigned in single line or successive way like ✞ 1 int variable_a, variable_b, variable_c; ✆ A variable in Java is said to be initialized if a numeric or an alphabatic value is assigned to it. For example variable a is initialized by ✞ 1 int variable_a = <value>; ✆ To distinct the words of a variable, underscore symbol (‘ ’) is used. Anytime within a program in which we specify a value explicitly instead of referring to a variable or some other form of data, that value is referred as a literal. Literals can either take a form defined by their type, or one can use hexadecimal (hex) notation to directly insert data into a variable regardless of its type. Hex numbers are always preceded with ‘0x’. The length of data type is measured its byte length. The datatype may be signed or unsigned. In signed data type, the MSB is used for sign declaration and rest of the bits are used for data value. In unsigned data type, all the bits are used for data value. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 0x50; 7 System.out.println("i is " + i); } 9 } ✆ ✞ i is 80 ✆ Signed & Unsigned Integer A byte is 8 bit long. The size of int is 4 byte, i.e. 32 bits. A signed integer is that integer whose first bit, i.e. MSB is taken as sign bit. If integer is defined as signed then MSB is sign bit and remaining 31 bits are used for storing an integer. If integer is defined as unsigned then all 32 bits are used for storing an integer. ✞ 1 //+---------------------Sign bit (1)1111111b =>-127d // Signed 7 bit integer 3 11111111b => 255d // Unsigned 8 bit integer ✆ A signed integer ranges from -2147483647 to 2147483647 while unsigned integer ranges from 0 to 4294967294. In the Java, bit ‘0’ is used as positive sign and bit ‘1’ is used as negative sign.
  • 17. 1.1. DATA IN & DATA OUT 17 Overflow of Data A variable declared as integer, long, float or double integer and character has capacity to store a specific size of data. An integer variable can not store data as long as float variable. This is why, a variable shall be declared of proper size for storing a data. To understand the overflow, consider a virtual datatype that can store only one byte long data. This datatype may be signed or unsiged. First assume it is unsigned, then the largest decimal value, that can be stored by it is 255. Initially, datatype has initialized with decimal value 254. ✞ 1 datatype k = 254d = 11111110b ✆ datatype is incremented by 1, it becomes ✞ 1 datatype k = 255d = 11111111b ✆ Again, datatype is incremented by 1, it becomes ✞ 1 datatype k = 255d = 1 00000000b ✆ The size of result is larger than one byte. The value of datatype reset to zero due to overflow. Here, overflow carry is ‘1’. Similarly a positive signed value becomes negative signed value if it is incremented beyond the signed data range. Taking the same datatype with signed value. ✞ 1 /* Bit inside parentheses represents to sign.*/ datatype k = 127d = (0)1111111b ✆ It is incremented by 1, it becomes ✞ /* Bit inside parentheses represents to sign.*/ 2 datatype k = -0d = (1)0000000b ✆ It becomes negative zero. Again, if increment by 1, the result is ✞ /* Bit inside parentheses represents to sign.*/ 2 datatype k = -1d = (1)0000001b ✆ Which is -1. Here, again datatype variable is overflowed. In java, overflow values shows errors and program is not compiled. Cast Operators Cast operators are used in conversion of one type data into other type data. Type casting may be of two types: (i) Implicit type casting and (ii) Explicit type casting. Implicit type casting is automatically handled by compiler i.e. when two or more data types are under execution. The final data-type will be that data type which is declared. An explicit type cast is a cast that should we specifically invoked with either of the cast. The compiler does not automatically invoke to resolve the data type conversion.
  • 18. 18 CHAPTER 1. INTRODUCTION ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 float i = (int) 10.2; System.out.println("i is " + i); 8 } } ✆ Here, at first, 10.2 is converted into integer by truncating its decimal part and then it is converted into float data type. Hence the 10.0 shall be final output of above program. ✞ i is 10.0 ✆ String can be converted to character array by using toCharArray() method. ✞ 1 /*Convert string into char code.*/ char[] c = s.toCharArray(); ✆ Here, ‘c’ represents to character array. A string is converted into string array by using split() method. To split string by space, synopsis is used like ✞ String[] sArray=s.split(" ");/*Space by " "*/ ✆ To split the string from each character, split() method is used like ✞ 1 String[] sArray=s.split("");/*No space by ""*/ ✆ ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String args[]) { String str = "This is my room"; 7 String[] k = str.split(" "); System.out.printf("i is in string : %sn", k[0]); 9 } } ✆ ✞ i is in string : This ✆ Scope of Variables Local variables are undefined prior to initialization. We can declare a variable without initialization. But if it is try to use local variables before assigning a value, the compiler will refuse to compile the program.
  • 19. 1.2. JAVA OPERATORS 19 1.1.7 Access Controll All members of a class are accessible to the class itself. To control access from other classes, class members have four possible access modifiers: private Private members declared private and they are accessible only in the same class. package Package members declared with no access modifier are accessible in classes in the same package, as well as in the class itself. protected Protected members declared protected are accessible in subclasses of the class, in classes in the same package, and in the class itself. public Public members declared public are accessible anywhere the class is accessible. The private and protected access modifiers apply only to members not to the classes or interfaces themselves. For a member to be accessible from a section of code in some class, the member’s class must first be accessible from that code. 1.2 Java Operators There are following types of Java operators. 1.2.1 Expression An expression is a combination of one or more explicit values, constants, vari- ables, operators, and functions. The evaluated value of expression is assigned to another variable or printed in output stream. A function declared as void type returns void value the this return value is discarded in an expression. 1.2.2 Unary Operaors In a unary operation, operator has only one operand. The unary operators used in Java are given in table below.
  • 20. 20 CHAPTER 1. INTRODUCTION Table 1.2: Unary operators. Type Representation Increment ++x, x++ Decrement - - x, x - - Positive +x Negative -x Ones‘ complement ∼ x Logical negation !x Cast (type-name) cast-expression ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i=10; 7 System.out.println("Name of tree is " + (-i)); } 9 } ✆ ✞ Name of tree is -10 ✆ 1.2.3 Binary Relations Binary operators are those operators which require two operands. These oper- ators are addition, subtraction, multiplication, division, less than, greater than, equals to etc. The relational binary operators are 1. < known as less than. 2. > known as greater than. 3. ≤ known as less than or equal to. 4. ≥ known as greater than or equal to. 5. == known as equals. 6. ! = known as not equals.
  • 21. 1.2. JAVA OPERATORS 21 ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int a = 10; 7 int b = 20; int c = 5; 9 if (a < b) { System.out.println(a + " is less than " + b); 11 } if (a > b) { 13 System.out.println(a + " is greater than " + b); } 15 if (a <= c) { System.out.println(a + " is less than or equal to " + c); 17 } if (a == c) { 19 System.out.println(a + " is exactly equal to " + c); } 21 if (a != b) { System.out.println(a + " is not equal to " + b); 23 } } 25 } ✆ Output of above program is ✞ 10 is less than 20 10 is not equal to 20 ✆ Remember that ‘=’ and ‘==’ are not same. For example, ‘c=20’ assigned the value 20 to variable c and returns true in output rather than comparison of c and 20. Reason behind is that c does not have a dedicated boolean type. So ‘0’ means false and anything else is true. In Java, the coditions like ✞ int a = 20; //constant initialized 2 if (a = 10) //incompatible integer type System.out.println("Stuff"); ✆ ✞ 1 if (0 < v < 10) {//bad operand type for < System.out.println("Stuff"); 3 } ✆ are not acceptable. The compiler shows error expressing ‘incompatible integer type’ or ‘bad operand type for <’. The appropriate form of comparison is shown in below example. ✞ 1 package jscript;
  • 22. 22 CHAPTER 1. INTRODUCTION 3 public class Jscript { 5 public static void main(String[] args) { int v = 7; 7 if (v == 7) { System.out.println("v is " + v); 9 } } 11 } ✆ ✞ v is 7 ✆ ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int v = 7; 7 if (0 < v && v < 10) { System.out.println("v=" + v +" is less than 20"); 9 } } 11 } ✆ ✞ v=7 is less than 20 ✆ 1.2.4 Logical Relations Logical relations sometimes known as boolear relations also. Logical operators are those operators which compare the variables or results logically. 1. && known as logical AND. If both the operands are non-zero, then con- dition becomes true. 2. || known as logical OR. If any of the two operands is non-zero, then con- dition becomes true. 3. ! known as logical NOT. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) {
  • 23. 1.2. JAVA OPERATORS 23 System.out.printf("6 != 6 && 6 / 2 < 5 is %bn", 6 != 6 && 6 / 2 < 5); 7 System.out.printf("6 != 6 || 6 / 2 < 5 is %bn", 6 != 6 || 6 / 2 < 5); System.out.printf("6 != 6 is %bn", 6 != 6); 9 } } ✆ ✞ 6 != 6 && 6 / 2 < 5 is false 6 != 6 || 6 / 2 < 5 is true 6 != 6 is false ✆ Logical expressions are evaluated from left to right. Evaluation stops as soon as something is discovered that renders the expression false. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.printf("(2 < 3) && (4 > 5) is %bn", (2 < 3) && (4 > 5)); 7 System.out.printf("(2 < 3) && (4 < 5) is %bn", (2 < 3) && (4 < 5)); } 9 } ✆ ✞ (2 < 3) && (4 > 5) is false (2 < 3) && (4 < 5) is true ✆ ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int x = 6; /* Here x is equal to 6. So, the relation* 8 * x != 6 is false. Now second relation* * x / 2 < 5 is not evaluated here. So, * 10 * the result is 0. */ System.out.printf("Expression result is %bn", x != 6 && x / 2 < 5); 12 } } ✆ ✞ Expression result is false ✆
  • 24. 24 CHAPTER 1. INTRODUCTION ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int x = 4; 7 /* Here x is not equal to 6. So, that * * x != 4 is true. Now second relation* 9 * x / 2 < 5 is logically ANDED with * * the result of x != 6. Here x/2 is 2* 11 * and 2 is less than 5, so logical * * AND of left and right values is 1 */ 13 System.out.printf("Expression result is %bn", x != 6 && x / 2 < 5); } 15 } ✆ ✞ Expression result is true ✆ 1.2.5 Precedence of Relational Operators The precedence of the binary relational operators is less than that of the arith- metic operators. This means, for example, x > y + 2 is same as x > (y + 2) and x = y > 2 is same as x = (y > 2). It means, in an expression, order of evalu- ation of operators is arithamtic operators, relational operators and assignment operators respectively. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int x = 4, y = 1; 7 /*x > y + 2*/ /*x > 1 + 2*/ 9 /*x > 3 */ /*4 > 3 (true)*/ 11 if (x > y + 2) { System.out.println("Expression Passed."); 13 } else { System.out.println("Expression Failed."); 15 } } 17 } ✆ ✞ Expression Passed. ✆
  • 25. 1.2. JAVA OPERATORS 25 1.2.6 Bitwise Operator A bitwise OR (|) gives result ‘1’ if either one or both bits are ‘1’ otherwise result is zero. A bitwise AND (&) gives result ‘1’ if both bits are ‘1’ otherwise result is zero. A bitwise XOR (ˆ) results ‘1’ if only either of two bits1 are ‘1’ otherwise result is zero. A bitwise NOT (∼) or complement, is a unary operation that performs logical negation on each bit, forming the ones’ complement of the given binary value. Bits those are 0 become 1, and those that are 1 become 0. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { /*10 is Binary equivalent to 1010*/ 7 int i = 10; /*5 is Binary equivalent to 0101*/ 9 int j = 5; /*-------------------------** 11 Bitwise OR Operation is 1010 13 0101 ------ 15 1111 = 15 **------------------------*/ 17 System.out.println("Bitwise OR of " + i + ", " + j + " is " + (i | j)); /*-------------------------** 19 Bitwise AND Operation is 1010 21 0101 ------ 23 0000 = 0 **------------------------*/ 25 System.out.println("Bitwise AND of " + i + ", " + j + " is " + (i & j)); /*-------------------------** 27 Bitwise XOR Operation is 1010 29 0101 ------ 31 1111 = 15 **------------------------*/ 33 System.out.println("Bitwise XOR of " + i + ", " + j + " is " + (i ^ j)); /*-------------------------** 35 Bitwise NOT Operation is 1010 1 If both bits are opposite bits.
  • 26. 26 CHAPTER 1. INTRODUCTION 37 --------- 0101 = -11 39 **------------------------*/ System.out.println("Bitwise NOT of " + i + " is " + (~i)); 41 } } ✆ ✞ Bitwise OR of 10, 5 is 15 Bitwise AND of 10, 5 is 0 Bitwise XOR of 10, 5 is 15 Bitwise NOT of 10 is -11 ✆ Normally, bitwise & operator returns the value equal to or less than the lesser operand. This is why & operator is used to restric the upper limit of the random result. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i = 0; while (i < 10) { 8 System.out.println("i&" + i + " => " + (i & 5)); i++; 10 } } 12 } ✆ ✞ 0&5 => 0, 1&5 => 1, 2&5 => 0, 3&5 => 1, 4&5 => 4, 5&5 => 5, 6&5 => 4, 7&5 => 5, 8&5 => 0, 9&5 => 1, ✆ While bitwise | operator returns the value equal to or larger than the largest operand. This is why | operator is used to restrict the lower limit of random result. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i = 0; while (i < 10) { 8 System.out.println("i|" + i + " => " + (i | 5)); i++; 10 } } 12 } ✆
  • 27. 1.2. JAVA OPERATORS 27 ✞ 0|5=>5, 1|5=>5, 2|5=>7, 3|5=>7, 4|5=>5 5|5=>5, 6|5=>7, 7|5=>7, 8|5=>13, 9|5=>13 ✆ 1.2.7 Shift Operator Logical shift operators are 1. << known as left shift 2. >> known as right shift ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 /*Bit pattern of Decimal 4 is equivalent to binary 100*/ int i = 4; 8 /*Number of places take place by binary shift.*/ int j = 2; 10 /*<< makes 100 to 10000, i.e. 16 in decimal*/ System.out.println("<< of " + i + ", " + j + " is " + (i << j)); 12 /*>> makes 100 to 1, i.e. 1 in decimal*/ System.out.println(">> of " + i + ", " + j + " is " + (i >> j)); 14 } } ✆ ✞ << of 4, 2 is 16. >> of 4, 2 is 1. ✆ In the following example, bitwise relation is used to add two number. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int x = 30, y = 1, sum, carry; /*---------------------------** 8 Decimal 30 is binary 11110 Decimal 01 is binary 00001 10 OR Operation is 11110 12 00001 ---------- 14 S= 11111 **---------------------------*/ 16 sum = x ^ y;
  • 28. 28 CHAPTER 1. INTRODUCTION /*---------------------------** 18 Decimal 30 is binary 11110 Decimal 01 is binary 00001 20 OR Operation is 11110 22 00001 -------- 24 C = 00000 **---------------------------*/ 26 carry = x & y; /*Performed loop until last carry is not zero.*/ 28 while (carry != 0) { /*----------------------------------------** 30 Left shift of carry is C_s = 000000 32 This operation is performed to shift the carry left hand side by one place 34 to add it with next higher place value. **----------------------------------------*/ 36 carry = carry << 1; /*Take x as sum value from OR Operation.*/ 38 x = sum; /*Take y as carry value form * 40 *left shift of AND Operation.*/ y = carry; 42 /*Take OR Operation of x and y*/ sum = x ^ y; 44 /*Get the next carry.*/ carry = x & y; 46 } /*Print the sum 31.*/ 48 System.out.println("Sum of " + x + " and " + y + " is : " + sum); } 50 } ✆ ✞ Sum of 30 and 1 is 31 ✆ Binary shift operation can be performed in characters and strings. It is explained in the example given below. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { char a = ’a’;/*Binary equivalent-1100001*/ 7 char b = ’b’;/*Binary equivalent-1100010*/ char c = ’c’;/*Binary equivalent-1100011*/ 9 /*-------------------------------------------------------* Shift of a by 16 bit left side--11000010000000000000000
  • 29. 1.2. JAVA OPERATORS 29 11 Shift of b by 8 bit left side-----------110001000000000 Shift of c by 0 bit left side-------------------1100011 13 ------------------------------------------------------- OR Operation -------------------11000010110001001100011 15 It is equivalent to Decimal---------------------6382179 *-------------------------------------------------------*/ 17 System.out.println("Left binary bit shift " + (a << 16 | b << 8 | c)); } 19 } ✆ ✞ Left binary bit shift is 6382179 ✆ The unary operator ‘∼’ returns the one’s complements of an integer by changing bit ‘0’ into ‘1’ and viceversa. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int j = 0; 7 System.out.println("Bitwise ~ operation on an integer."); while (j < 3) { 9 System.out.println(j + " => " + (~j)); j++; 11 } } 13 } ✆ ✞ Bitwise ~ operation on an integer. 0 => -1 1 => -2 2 => -3 ✆ 1.2.8 Condition & Relation If a condition is true then successive value is taken otherwise next value. The simplest form of this operator is ✞ x ? y : z ✆ ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 1, j = 0;
  • 30. 30 CHAPTER 1. INTRODUCTION 7 while (j < 3) { System.out.println(i + " < " + j + " " + (i < j ? "YES" : "NO" )); 9 j++; } 11 } } ✆ ✞ 1 < 0 NO 1 < 1 NO 1 < 2 YES ✆ 1.2.9 Arithmetic Operators Arithmetic operators are 1. + known as addition operator. It adds the right value with left value. 2. − known as subtraction operator. It subtracts the right value from left value. 3. / known as division operator. It divides the left value with right value. Returns the quotient. If, both left and right values are integer then decimal part of the result is truncated. 4. ∗ known as multiplication operator. It multiply the left value with right value. Returns product of two numbers. 5. % known as modulo operator. Returns the remainder in division. 6. = known as assignment operator. A variable at left side to it is assigned the value at the right side of it. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { float i = 1, j = 3; 7 System.out.println(i + " + " + j + "=" + (i + j)); System.out.println(i + " - " + j + "=" + (i - j)); 9 System.out.println(i + " * " + j + "=" + (i * j)); System.out.println(i + " / " + j + "=" + (i / j)); 11 System.out.println(i + " % " + j + "=" + (i % j)); } 13 } ✆
  • 31. 1.2. JAVA OPERATORS 31 ✞ 1.0 + 3.0=4.0 1.0 - 3.0=-2.0 1.0 * 3.0=3.0 1.0 / 3.0=0.33333334 1.0 % 3.0=1.0 ✆ 1.2.10 Precedence of Arithmatic Operators Arithmatic problems are not solved from left to right in the sequence the expres- sion is written. But some rules are used. For example, parentheses are solved first, then division, multiplication, addition and subtraction. Thus, arithmatic operators have some precedence. Operators in order of decreasing precedence are given in table below. Operators Associativity () Left to right + – (unary) Right to left * / Left to right + – (binary) Left to right = Right to left ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int y; 7 /* Order of arithmatic operators * * are /, *, +, -, =. So first 12* 9 * is divided by 5 and answer is * * 2.4. 6 is multiply by 2.4 and * 11 * result is 14.4. It is added to* * 20 and 10 is subtracted * 13 * The answer is 14.4+20-10=24.4 */ y = 6 * 12 / 5 + 20 - 10; 15 /* In result only 24 is printed. * * Decimal is truncated. */ 17 System.out.println("Expression result is " + y); } 19 } ✆ ✞ Expression result is 24 ✆
  • 32. 32 CHAPTER 1. INTRODUCTION 1.2.11 Relational Operators The assignment operators are 1. == known as equal. 2. ∗ = known as product and equal. 3. / = known as divide mode and equal. 4. + = known as add and equal. 5. − = known as subtract and equal. 6. <<= known as left shift and equal. 7. >>= known as right shift and equal. 8. & = known as AND and equal. 9. ˆ= known as exclusive OR and equal. 10. | = known as inclusive OR and equal. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int y = 2; 7 y += 2; System.out.println("y += 2 is " + y); 9 y &= 2; System.out.println("y &= 2 is " + y); 11 y ^= 2; System.out.println("y ^= 2 is " + y); 13 y |= 2; System.out.println("y |= 2 is " + y); 15 y <<= 2; System.out.println("y <<= 2 is " + y); 17 } } ✆ ✞ y += 2 is 4 y &= 2 is 0 y ^= 2 is 2 y |= 2 is 2 y <<= 2 is 8 ✆
  • 33. 1.3. CONDITIONS 33 1.3 Conditions Conditions are the comparison statements those controls the execution of codes inside the conditional blocks. 1.3.1 if condition if () provides a way to instruct the program to execute a block of code only if certain conditions have been met. The syntax of if () construct is ✞ 1 if(/*conditions*/) // if condition is true then statement // execute the condition. ✆ A simple example is ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i=0; while (i < 5) { 8 if (i == 2) { System.out.printf("i is %dn", i); 10 } i++; 12 } } 14 } ✆ ✞ i is 2 ✆ 1.3.2 if-else condition if-else provides a way to instruct the program to execute a block of code only if certain conditions have been met otherwise execute other block. The syntax of if-else construct is ✞ 1 if(/*conditions*/) // if condition is true then statement one // execute the statement one. 3 else // otherwise if condition is false statement two // execute the statement two. ✆ A simple example is ✞ package jscript; 2 public class Jscript { 4
  • 34. 34 CHAPTER 1. INTRODUCTION public static void main(String[] args) { 6 int i=0; while (i < 5) { 8 if (i == 2) { System.out.printf("i is %dn", i); 10 } else { System.out.printf("i is NOT %dn", 2); 12 } i++; 14 } } 16 } ✆ ✞ i is NOT 2 i is NOT 2 i is 2 i is NOT 2 i is NOT 2 ✆ A short hand for of if-else condition is ✞ 1 int a=(b > c) ? d : e; ✆ Above statement is similar to the statement of “return d if b is greater than c else return e”. if - else - if - else - if - else statement can be used successively. 1.3.3 switch Use of a long chain of if-else-if-else-if-else is very complex and less readable. There’s a solution by using the Switch-Case construct. The basic syntax of this construction is given below. ✞ 1 switch (<case variable>) { case 1: 3 statements one break; 5 case 2: statements two 7 break; case 3: 9 statements three break; 11 default: default statement 13 break; } ✆ Here default case is executed if none of the cases is matched with case variable value. Following is working example
  • 35. 1.3. CONDITIONS 35 ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i = 0; while (i < 5) { 8 switch (i) { case 1: 10 System.out.printf("i is %dn", i); break; 12 case 2: System.out.printf("i is %dn", i); 14 break; case 3: 16 System.out.printf("i is %dn", i); break; 18 default: System.out.printf("either i<1 or i>3n"); 20 break; } 22 i++; } 24 } } ✆ ✞ either i<1 or i>3 i is 1 i is 2 i is 3 either i<1 or i>3 ✆ Here operator ‘break’ plays an important role. If break operator is not used in block of ‘case’ then all the successive blocks are executed successively. The reason behind is that, ‘break’ inside the ‘case’ exits from the switch block from the current loop. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 0; 7 while (i < 5) { switch (i) { 9 case 1: System.out.printf("i is %dn", i); 11 case 2: System.out.printf("i is %dn", i);
  • 36. 36 CHAPTER 1. INTRODUCTION 13 case 3: System.out.printf("i is %dn", i); 15 break; default: 17 System.out.printf("either i<1 or i>3n"); break; 19 } i++; 21 } } 23 } ✆ ✞ either i<1 or i>3 i is 1 i is 1 i is 1 i is 2 i is 2 i is 3 either i<1 or i>3 ✆ 1.4 Iteration Iteration is a process in which code statements are executed more than once. For example, to print a line ten times, either the line is writem ten times one after another or a loop is used to print the line ten times. Most common iteration/loop functions are for and while. 1.4.1 for loop The syntax of for loop is ✞ for(initialization; test; increment) { 2 /* code */ } ✆ The working example is ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int a, b; 7 b = 15; for (a = 10; a < b; a++) { 9 System.out.printf("The number a is %d.n", a); }
  • 37. 1.4. ITERATION 37 11 } } ✆ The output is ✞ The number a is 10. The number a is 11. The number a is 12. The number a is 13. The number a is 14. ✆ The initialization statement is executed exactly once. It is used to assign an initial value to some variable. The test expression is evaluated each time before the code in the for loop executes. If this expression evaluates as 0 (false), the loop is not (re)enter into the for loop. And execution of program carry on to the code immediately following the for loop. If the expression is non-zero (ie true), the loop is (re)enter inside the for loop. After each iteration of the loop, the increment statement is executed. This often is used to increment the loop index. An infinite loop is executed if for is defined as shown below. ✞ 1 for(;;) { /* statements / codes */ 3 } ✆ Multiple initialization can be used by separating them by comma. ✞ 1 for(initialization one, /*First var initialized*/ initialization two; /*Second var initialized*/ 3 test of initializers;/*Test the condition of variables*/ increment one , /*Increment of first variable*/ 5 increment two) { /*Increment of second variable*/ 7 /* expressions / statements / codes */ 9 } ✆ ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i, j; 7 for (i = 6, j = 1; j < i; i++, j = (j + 2)) { System.out.printf("Product of i=%d & j=%d is %dn", i, j, i * j); 9 } } 11 } ✆
  • 38. 38 CHAPTER 1. INTRODUCTION ✞ Product of i=6 & j=1 is 6 Product of i=7 & j=3 is 21 Product of i=8 & j=5 is 40 Product of i=9 & j=7 is 63 Product of i=10 & j=9 is 90 ✆ 1.4.2 while loop A while() loop is the most basic type of loop. It will run as long as the condition retun non-zero (ie true) value. At false state, while loop exits. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 0; 7 while (i < 5) { System.out.printf("i*i is %dn", i * i); 9 i++; } 11 } } ✆ ✞ i*i is 0 i*i is 1 i*i is 4 i*i is 9 i*i is 16 ✆ 1.4.3 For Loop Like While Loop The syntax of for loop as ✞ 1 for(; <test> ; ) ✆ is similar to the while loop ✞ 1 while (<test>) ✆ Following is an example which shows that for loop is similar to the while loop. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 0;
  • 39. 1.5. PARSING ARGUMENTS 39 7 for (; i < 5;) { System.out.printf("%dt", i); 9 i++; } 11 System.out.printf("n"); int j = 0; 13 while (j < 5) { System.out.printf("%dt", j); 15 j++; } 17 System.out.printf("n"); } 19 } ✆ ✞ 0 1 2 3 4 0 1 2 3 4 ✆ 1.5 Parsing Arguments When a program is being executed via another program internally, arguments are required to be passed to the executable ie the program. These arguments are considered as inputs for the executable. To pass the values we define main() function as ✞ public static void main(String[] args) ✆ Here ‘args’ are the array of input strings. ✞ 1 package jscript; 3 class Jscript { 5 public static void main(String args[]) { System.out.println(args[1]); 7 } } ✆ After compiling and executing the executable as ✞ Jscript.jar a b c ✆ Output is ✞ a ✆ Here Jscript.jar in commandline is also considered as an argument. This is why there are four arguments and first argument, ie 0th argument, is Jscript.jar itself and rest of the arguments are a, b and c respectively.
  • 40. 40 CHAPTER 1. INTRODUCTION 1.6 Mathematical Operator In C programming addition, subtraction, multiplication and division mathemat- ical operators can be directly used. Modulus is another mathematical operators that gives the remainder value. Application of these operators are a + b, a − b, a ∗ b, a/b and a%b respectively. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { float i = 1, j = 3; 7 System.out.println(i + " + " + j + "=" + (i + j)); System.out.println(i + " - " + j + "=" + (i - j)); 9 System.out.println(i + " * " + j + "=" + (i * j)); System.out.println(i + " / " + j + "=" + (i / j)); 11 System.out.println(i + " % " + j + "=" + (i % j)); } 13 } ✆ ✞ 1.0 + 3.0=4.0 1.0 - 3.0=-2.0 1.0 * 3.0=3.0 1.0 / 3.0=0.33333334 1.0 % 3.0=1.0 ✆ 1.6.1 Trigonometric Functions “math.h” preprocessor file provides the mathematical functions that can be used directly in the program. Some of them are defined in following sections. cos, sin & tan The cos, sin, and tan functions return the cosine, sine, and tangent of the argument, expressed in radians. The domain of arguments of sin, cos and tan are [−π/2, π/2], [0, π] and [−π/2, π/2] respectively. The numerical range of sin, cos and tan are [−1, 1], [−1, 1] and [−∞, ∞]. ✞ 1 double cos(double x); double sin(double x); 3 double tan(double x); ✆ A simple example is ✞ 1 package jscript; 3 public class Jscript {
  • 41. 1.6. MATHEMATICAL OPERATOR 41 5 public static void main(String[] args) { System.out.printf("Cosine at 22/7 radian is : %f n", Math.cos(22 / 7)); 7 System.out.printf("Sine at 22/7 radian is : %f n", Math.sin(22 / 7)); System.out.printf("Tangent at 22/7 radian is : %f n", Math.tan (22 / 7)); 9 } } ✆ ✞ Cosine at 22/7 radian is : -0.989992 Sine at 22/7 radian is : 0.141120 Tangent at 22/7 radian is : -0.142547 ✆ acos, asin & atan The acos() functions return the arccosine of their arguments in radians, and the asin() functions return the arcsine of their arguments in radians. All functions expect the argument in the range [−1, +1]. The arccosine returns a value in the range [0, π]; the arcsine returns a value in the range h − π 2 , π 2 i . The atan() returns their argument value in radian in the range h − π 2 , π 2 i . Method of use of inverse function in following systems. ✞ 1 double asin(double x); double acos(double x); 3 double atan(double x); ✆ A simple example is ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.printf("Arc cosine at argument 0.5 is : %f n", Math. acos(0.5)); 7 System.out.printf("Arc sine at argument 0.5 is : %f n", Math. asin(0.5)); System.out.printf("Arc tangent at argument 1.5 is : %f n", Math. atan(1.5)); 9 } } ✆ ✞ Arc cosine at argument 0.5 is : 1.047198 Arc sine at argument 0.5 is : 0.523599 Arc tangent at argument 1.5 is : 0.982794 ✆
  • 42. 42 CHAPTER 1. INTRODUCTION cosh, sinh & tanh The cosh(), sinh() and tanh() functions compute the hyperbolic cosine, the hyperbolic sine and the hyperbolic tangent of the argument respectively. ✞ 1 double cosh(double x); double sinh(double x); 3 double tanh(double x); ✆ A simple example is ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.printf("Hyperbolic cosine of 0.5 is : %f n", Math. cosh(0.5)); 7 System.out.printf("Hyperbolic sine of 0.5 is : %f n", Math.sinh (0.5)); System.out.printf("Hyperbolic tangent of 1.5 is : %f n", Math. tanh(1.5)); 9 } } ✆ ✞ Hyperbolic cosine at argument 0.5 is : 1.127626 Hyperbolic sine at argument 0.5 is : 0.521095 Hyperbolic tangent at argument 1.5 is : 0.905148 ✆ 1.6.2 Logarithm Function exp, log exp() represents the exponential of a value x with base ‘e’. log() represents the logarithm of a value in natural base ‘e’. ✞ 1 double exp(double x); double log(double x); ✆ A simple example is ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 System.out.printf("Exponential of 0.5 is : %f n", Math.exp(0.5)) ; System.out.printf("logarithm of 0.5 at base 10 is : %f n", Math. log(0.5));
  • 43. 1.6. MATHEMATICAL OPERATOR 43 8 } } ✆ ✞ Exponential of 0.5 is : 1.648721 logarithm of 0.5 at base 10 is : -0.693147 ✆ 1.6.3 Arithmatic Function pow, sqrt, floor, ceil & round pow() makes second variable in power over the first variable. sqrt returns the square root of a variable value. floor() rounded fraction to down. ceil() rounded fraction to up and round() rounded up the number if fraction is equal or more than 0.5. ✞ double pow(double x, double y); 2 double sqrt(double x); double floor(double x); 4 double ceil(double x); double round(double x); ✆ A simple example is ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.printf("Power of 2 on base 3 is : %f n", Math.pow(3, 2)); 7 System.out.printf("Square root of 1.45 is : %f n", Math.sqrt (1.45)); System.out.printf("Ceiling of 1.45 is : %f n", Math.ceil(1.45)); 9 System.out.printf("Flooring of 1.4855 is : %f n", Math.floor (1.4855)); System.out.printf("Rounding of 6.157 is : %d n", Math.round (6.157)); 11 } } ✆ ✞ Power of 2 on base 3 is : 9.000000 Square root of 1.45 is : 1.204159 Ceiling of 1.45 is : 2.000000 Flooring of 1.4855 is : 1.000000 Rounding of 6.157 is : 6 ✆
  • 44. 44 CHAPTER 1. INTRODUCTION
  • 45. Chapter 2 String & Arrays 2.1 Strings The string constant “x” is not the same as the character constant i.e. ‘x’. One difference is that ‘x’ is a basic type (charcode), but “x” is a derived type, an array of char. A String class type deals specifically with sequences of character data. A string is declared and intialized as ✞ 1 /*Declaration of string*/ String s=new String(); 3 /*Initialization of string*/ char chars[] = { ’a’, ’b’, ’c’, ’d’, ’e’ }; 5 String s = new String(chars); ✆ A substring can also be intialized if String class is used like ✞ 1 char chars[] = { ’a’, ’b’, ’c’, ’d’, ’e’ }; String s = new String(chars, <pos index>, <number of chars>); ✆ In String objects length() method returns the number of characters in the string. ✞ String s = new String(); 2 int n=s.length();/*Length of string.*/ ✆ Characters are indexed from 0 to length()-1, and can be accessed with the ✞ charAt(<index>) ✆ method. String objects are read-only. ✞ 1 char ch; ch = "abcdedf".charAt(1);/*character at index 1.*/ ✆ 45
  • 46. 46 CHAPTER 2. STRING & ARRAYS 2.2 Array Arrays in Java stores data in a single variable name with an index, also known as a subscript. It is simply a list or ordered grouping for variables of the same type. Arrays often help a programmer in organize collections of data efficiently and intuitively. Declaring an Array In Java an array is declared by using keyword new like ✞ int[] ia = new int[3]; 2 float[] ia = new float[3]; String[] sa=new String[10]; ✆ Initialization an Array In java, an array can be initialized at the time of declaration or later the time. Synopsis for the initialization of an array during the time of declaration is ✞ 1 int[] ia = new int[3]{1, 2, 3}; ✆ ✞ 1 package jscript; 3 public class Jscript { public static void main(String[] args) { 5 int[] ia = new int[]{1, 2, 3}; System.out.println(ia.length); 7 } } ✆ ✞ 3 ✆ Dynamic Array Size If the array is declared as shown below then size of array is determined at the execution time. ✞ 1 int[] ia=new int[/*No value here*/]; ✆ ✞ 1 package jscript; 3 public class Jscript { public static void main(String[] args) { 5 int[] ia = new int[/*No value here*/]{1, 2, 3, 1, 2, 3}; System.out.println(ia.length); 7 } } ✆ ✞ 6 ✆
  • 47. 2.2. ARRAY 47 2.2.1 Dyanmic Array 2.2.2 Uni-dimensional Array Arrays are declared and initialized like ✞ 1 int numbers[6]; // array declared int point[6]={0,0,1,0,0,0}; // array initialized ✆ The square brackets [] identify ‘numbers’ or ‘points’ and the rest as arrays, and the number enclosed in the brackets indicates the number of elements in the array. An element of the array can be accessed by its index number. In following example, each element of the array is accessed by its index number. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int i = 0; int[] anArray = new int[4]; 8 while (i < 4) { anArray[i] = i; 10 System.out.println(anArray[i]); i++; 12 } } 14 } ✆ ✞ 0 1 2 3 ✆ In the above example, the size of the array was not explicitly specified. The compiler knows the size of array from the initialized list. The size of ‘anArray’ is ‘4’ because ‘anArray’ has four elements. Addition of an additional element to the list will increase its size to five. Static declaration of the size of an array, the array list will be overflow. To overcome this problem array is declared with dynamic size. 2.2.3 Multi-dimensional Array A multi-dimensional array can be declared as the synopsis given below. ✞ int[][] ia = new int[2][3]; 2 /*OR*/ int[][] ia = new int[][]{{5, 2, 1}, 4 {6, 7, 8}}; /*OR*/
  • 48. 48 CHAPTER 2. STRING & ARRAYS 6 int ia[][][] = new int[3][4][5]; ✆ Where [2] represents to the number of rows and [3] represents to the number of columns of the two dimensional array. Multi-dimensional array can be used to add, subtract and product (either dot or cross) of two vectors or matrices. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) { 6 int ix, iy; 8 int[][] anArray = new int[5][5]; for (ix = 0; ix < 5; ++ix) { 10 for (iy = 0; iy < 5; ++iy) { anArray[ix][iy] = ix * iy; 12 }; } 14 for (ix = 0; ix < 5; ++ix) { for (iy = 0; iy < 5; ++iy) { 16 System.out.printf("%2dt", anArray[ix][iy]); }; 18 System.out.printf("n"); } 20 } } ✆ ✞ 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16 ✆ 2.2.4 Size of Array In Java, size of array is obtained by using length object. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { int i = 0; 7 int[] anArray = new int[4]; System.out.println(anArray.length); 9 } } ✆
  • 49. 2.3. CLASS, OBJECT & FUNCTION 49 ✞ 4 ✆ 2.3 Class, Object & Function Like struct in C, java has classes and objects. Every object has a class that defines its data and behavior. A class has (i) fields which are data variables associated with a class and its objects. They stores results. (ii) Methods are build from expressions and contain the executable code of a class. A public class should be declared in a separate file having name as public class name. A class is declared as ✞ 1 class <class name>{ <scope> <data type> <var a>, <var b>; 3 } ✆ In following lines, class Trees is declared with two variables or fields. ✞ 1 class Trees{ public char name; 3 public double length; } ✆ Objects are created by expressions containing the new keyword. Creating an object from a class definition is also known as instantiation; thus, objects are often called instances. ✞ Trees t=new Trees(); ✆ The members may be assigned a value as ✞ 1 t.name="a"; ✆ Again, the value of a class member can also be accessed by using ✞ 1 t.name /*or*/ 3 t.length ✆ See example below: ✞ 1 package jscript; 3 class Trees { 5 public char name; public double length; 7 } 9 public class Jscript {
  • 50. 50 CHAPTER 2. STRING & ARRAYS 11 public static void main(String[] args) { Trees t = new Trees(); 13 t.name = 120; t.length = 2; 15 System.out.println("Name of tree is " + t.name); System.out.println("Length of tree is " + t.length); 17 } } ✆ ✞ Name of tree is x Length of tree is 2.0 ✆ A class can also have a return value to the caller by object method. ✞ package jscript; 2 class Box { 4 int length; 6 int width; int height; 8 int Volume() { 10 return length * width * height; } 12 } 14 public class Jscript { 16 public static void main(String[] args) { Box b = new Box(); 18 b.length = 2; b.width = 1; 20 b.height = 3; int vol = b.Volume(); 22 System.out.printf("Volume of Box is %dn", vol); } 24 } ✆ ✞ Volume of Box is 6 ✆ ✞ 1 package jscript; /*Class*/ 3 class myClass { 5 private String name; 7 private int age;
  • 51. 2.3. CLASS, OBJECT & FUNCTION 51 /*Object of the class and its initialization*/ 9 public myClass(String name, int age) { 11 this.name = name; this.age = age; 13 } /*Object get name*/ 15 public String getName() { 17 return name; } 19 /*Object get age*/ 21 public Object getAge() { return age; 23 } } 25 public class Jscript { 27 public static void main(String[] args) { 29 myClass sun = new myClass("Sooraj", 15); System.out.printf("Name of person is %s.n", sun.getName()); 31 System.out.printf("Name of person is %s.n", sun.getAge()); } 33 } ✆ ✞ Name of person is Sooraj. Name of person is 15. ✆ A class can also be accessed with arguments as shown in example below. ✞ package jscript; 2 class myClass { 4 public String name; 6 public int dis; 8 public myClass(String n, int d) { name = n; 10 dis = d; } 12 } 14 public class Jscript { 16 public static void main(String[] args) { myClass sun = new myClass("Sooraj", 15); 18 System.out.printf("Distance of %s is %d.n", sun.name, sun.dis);
  • 52. 52 CHAPTER 2. STRING & ARRAYS } 20 } ✆ ✞ Distance of Sooraj is 15. ✆ Function in Java a group of statements and expressions which accepts inputs, analyse them according to the statements and expressions and return the result. There are no global functions in Java. The equivalent is to define static methods in a class. Function overloading is allowed in java. ✞ 1 public class <class name>{ public static <data type> <function name>(argument a, argument b) { 3 <expression> } 5 } ✆ A function can be called by calling class name and envoking function name like ✞ 1 <class name>.<function name>(argument a, argument b); ✆ Here, class name is the name of java file in which function is written. In the following example, two files, Jscript.java and Sum.java are placed inside the package jscript. The file containing main class is Jscrip.java and it contains the codes given below. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.println("Sum of 2 and 3 is " + Sum.sum(2, 3)); 7 } } ✆ While the file containing Sum class and sum function is Sum.java and it contains the codes given below. ✞ package jscript; 2 public class Sum { 4 public static int sum(int a, int b) { 6 return a + b; } 8 } ✆ We call the sum function from main class as ✞ Sum.sum(2, 3) ✆ and the result given by program is
  • 53. 2.3. CLASS, OBJECT & FUNCTION 53 ✞ Sum of 2 and 3 is 5 ✆ 2.3.1 Arguments A functions accepts inputs through its arguments. A function with two argu- ments is defined as ✞ 1 public static int sum(int a, int b); ✆ Here, int a, int b are known as formal arguments. During the defining of a function, each argument must be identified by its type. For example, to supply two integer arguments to a function, it shall be defined like ✞ 1 public static int sum(int a, int b); ✆ while, the definition of function as given below is illegal. ✞ 1 public static int sum(int a, b);//Illegal definition ✆ Here, second argument ‘b’ is type unidentified. In Java, a function can be called from anywhere by supplying actual arguments as ✞ 1 Sum.sum(2, 3); ✆ See example below. Jscript.java contains the codes given below. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { System.out.println("Sum of 2 and 3 is " + Sum.sum(2, 3)); 7 } } ✆ Sum.java contains the codes given below. ✞ package jscript; 2 public class Sum { 4 public static int sum(int a, int b) { 6 return a + b; } 8 } ✆ We call the sum function from the main class as ✞ Sum.sum(2, 3) ✆ and the result given by program is
  • 54. 54 CHAPTER 2. STRING & ARRAYS ✞ Sum of 2 and 3 is 5 ✆ 2.3.2 Prototyping Function prototype allows to omit the variable name in its arguments. The legal function prototyping are ✞ 1 public static int sum(int, int); /*Illegal prototype.*/ public static int sum(int a, int b); /*Legal prototype.*/ 3 public static int sum(a, int b); /*Illegal prototype.*/ ✆ 2.3.3 this Reference The this reference is most commonly used as a way to pass a reference to the current object as an argument to other methods or when the name of the field are needed to access is hidden by a local variable or parameter declaration. ✞ 1 package jscript; 3 class myClass { 5 public String name;/*Name field*/ public int dis; /*Distance field*/ 7 /*Passed argument names are similar to field name.*/ public myClass(String name, int dis) { 9 /*To distict the field name from * *argument this reference is used.*/ 11 this.name = name; this.dis = dis; 13 } } 15 public class Jscript { 17 public static void main(String[] args) { 19 myClass sun = new myClass("Sooraj", 15); System.out.printf("Distance of %s is %d.n", sun.name, sun.dis); 21 } } ✆ ✞ Distance of Sooraj is 15. ✆ If this reference is not used then code and result shall be looked like ✞ 1 package jscript; 3 class myClass {
  • 55. 2.3. CLASS, OBJECT & FUNCTION 55 5 public String name;/*Name field*/ public int dis; /*Distance field*/ 7 /*Passed argument names are similar to field name.*/ public myClass(String name, int dis) { 9 /*To distict the field name from argument * *this reference is used. Here no reference* 11 *is used so that the field parameter does * *not store the values of name and distance*/ 13 name = name; dis = dis; 15 } } 17 public class Jscript { 19 public static void main(String[] args) { 21 myClass sun = new myClass("Sooraj", 15); System.out.printf("Distance of %s is %d.n", sun.name, sun.dis); 23 } } ✆ ✞ Distance of null is 0. ✆ 2.3.4 Field Declaration A field can be declared as either annotations, access, static, final, transient or volatile. A field cannot be both final and volatile. A static field is shared only one instance by all objects of a class. A final variable is one whose value cannot be changed after it has been initialized. 2.3.5 Inheritance To inherit a class, one class is incorporate and defined in another class by using the extends keyword. ✞ 1 package jscript; /*Creatign a super class*/ 3 class BoxVol { int l, w, h; 5 int Volume() { return l * w * h; 7 } } 9 /*Creating subclass extending to super class.* *Here the variables and members of super are* 11 *accessed by object created for sub class. */ class BoxSur extends BoxVol {
  • 56. 56 CHAPTER 2. STRING & ARRAYS 13 int Surface() { return 2 * (l * w + w * h + l * h); 15 } } 17 public class Jscript { public static void main(String[] args) { 19 /*Object cerated for box surface.* *The scope of BoxSur is extende * 21 *to the BoxVol, hence variables * *and all members of BoxVol are * 23 *accessible from created object.*/ BoxSur a = new BoxSur(); 25 /*Access varibles of super class.*/ a.l = 2; 27 a.w = 1; a.h = 3; 29 /*Fetch the member value of super class.*/ int vol = a.Volume(); 31 System.out.printf("Volume of Box is %dn", vol); /*Fetch the member value of sub class.*/ 33 int sur = a.Surface(); System.out.printf("Surface Area of Box is %dn", sur); 35 } } ✆ ✞ Volume of Box is 6 Surface Area of Box is 22 ✆ 2.3.6 Function In Java a function is defined as in language C. The return value of a function may be integer, double, float, boolean or void type. A function is defined inside the class as subclass. The synopsis of the function is ✞ int MyFunc(){ 2 <expression> } ✆ In following example, when a function is called it reset the value of ‘s’. And the global value of ‘s’ is printed in output stream. ✞ 1 package jscript; 3 public class Jscript { /*To use s as global, it should be defined as static.*/ 5 static double s = 0.0; 7 double MyFunc() { s = 10;
  • 57. 2.4. THREADING 57 9 return s; } 11 public static void main(String args[]) { 13 Jscript j = new Jscript(); 15 j.MyFunc(); System.out.printf("s is %fn", s); 17 } } ✆ ✞ s is 10.000000 ✆ 2.3.7 Type of Objects 2.4 Threading A thread is initiated by Thread object like ✞ 1 Thread th = new Thread(); ✆ In following example a thread is created. ✞ 1 package jscript; 3 public class Jscript { 5 public static void main(String[] args) { Thread th = new Thread(); 7 System.out.println(th); } 9 } ✆ ✞ Thread[Thread-0,5,main] ✆ In following example,Jscript class is extended to Thread object. ✞ 1 package jscript; /*Class extended to Thread*/ 3 public class Jscript extends Thread { 5 public static void main(String[] args) throws InterruptedException { int i = 1; 7 for (;;) { /*sleep method throws InterruptedException.*/ 9 Thread.sleep(1000); System.out.printf("Seconds passed %dn", i); 11 i++;
  • 58. 58 CHAPTER 2. STRING & ARRAYS } 13 } } ✆ ✞ Seconds passed 1 Seconds passed 2 ........ ........ ✆ Above example is rewritten and a new thread is initiated by using Thread object. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args) throws InterruptedException { 6 int i = 1; /*Independent Thread is initiated.*/ 8 Thread th = new Thread(); for (;;) { 10 /*sleep method throws InterruptedException.*/ th.sleep(1000); 12 System.out.printf("Seconds passed %dn", i); i++; 14 } } 16 } ✆ ✞ Seconds passed 1 Seconds passed 2 ........ ........ ✆ After a Thread object is created, it can be configured and run. A thread is invoked by start() method. The virtual machine invokes the new thread’s run() method, making the thread active. A thread can be invoked only once. Multiple invoking of same thread results IllegalThreadStateException. ✞ package jscript; 2 public class Jscript { 4 public static void main(String[] args){ 6 Thread th = new Thread(); System.out.printf("Invoking same thread multiple times.n"); 8 /*Multiple involke throws IllegalThreadStateException.*/ th.start(); 10 th.start(); } 12 } ✆
  • 59. 2.4. THREADING 59 While a thread is running we can interact with it in other ways. After activating the thread, we need to perform some action. The Runnable interface declares a single method: ✞ public void run(); ✆ Actually the code inside the run() object does the real job. ✞ 1 package jscript; 3 public class Jscript extends Thread { 5 private String word; private int delay; 7 public Jscript(String w, int d) { 9 word = w; delay = d; 11 } 13 @Override public void run() { 15 try { for (;;) { 17 System.out.printf(word + " n"); Thread.sleep(delay); 19 } } catch (InterruptedException e) { 21 return; } 23 } 25 public static void main(String[] args) { new Jscript("ping", 1000).start(); 27 new Jscript("PONG", 3000).start(); } 29 } ✆ ✞ ping PONG ping ping PONG ✆ wait(), notify() and notifyAll() methods tells waiting threads that something has occurred that might satisfy that condition. The wait() and notification methods are defined in class Object and are inherited by all classes. Name of thread can be changes by setName() method. See the example below.
  • 60. 60 CHAPTER 2. STRING & ARRAYS ✞ 1 package jscript; 3 public class Jscript extends Thread { 5 @Override public void run() { 7 System.out.println("Running...."); } 9 public static void main(String args[]) { 11 Jscript th1 = new Jscript(); Jscript th2 = new Jscript(); 13 System.out.println("Name of first thread is :" + th1.getName()); System.out.println("Name of second thread is :" + th2.getName()); 15 th1.start(); 17 th2.start(); /*Change the name of first thread.*/ 19 th1.setName("Konark"); System.out.println("After changing name of first thread:" + th1. getName()); 21 /*Change the name of second thread.*/ th1.setName("Khajuraho"); 23 System.out.println("After changing name of second thread :" + th1 .getName()); } 25 } ✆ ✞ Name of first thread is :Thread-0 Name of second thread is :Thread-1 After changing name of first thread:Konark After changing name of second thread :Khajuraho Running.... Running.... ✆ Priority of a thread is set by using setPriority() method. There are three types of priorities - MIN PRIORITY, NORM PRIORITY and MAX PRIORITY. ✞ package jscript; 2 public class Jscript extends Thread { 4 @Override 6 public void run() { /*Current thread tells the current running thread*/ 8 System.out.println(Thread.currentThread().getPriority()); } 10 public static void main(String args[]) {
  • 61. 2.4. THREADING 61 12 Jscript th1 = new Jscript(); Jscript th2 = new Jscript(); 14 System.out.println("Name of first thread is :" + th1.getName()); System.out.println("Name of second thread is :" + th2.getName()); 16 /*Change the name of first thread.*/ th1.setName("Konark"); 18 th1.setPriority(MIN_PRIORITY); System.out.println("After changing name of first thread:" + th1. getName()); 20 /*Change the name of second thread.*/ th1.setName("Khajuraho"); 22 th1.setPriority(MAX_PRIORITY); System.out.println("After changing name of second thread :" + th1 .getName()); 24 th1.start(); th2.start(); 26 } } ✆ ✞ Name of first thread is :Thread-0 Name of second thread is :Thread-1 After changing name of first thread:Konark After changing name of second thread :Khajuraho 10 5 ✆ A running thread is joined by using join() method. ✞ package jscript; 2 public class Jscript extends Thread { 4 public void run() { 6 System.out.println("Running.."); } 8 public static void main(String args[]) { 10 Jscript th1 = new Jscript(); Jscript th2 = new Jscript(); 12 Jscript th3 = new Jscript(); th1.start(); 14 try { th1.join(); 16 } catch (Exception e) { System.out.println(e); 18 } th2.start(); 20 th3.start(); } 22 } ✆
  • 62. 62 CHAPTER 2. STRING & ARRAYS ✞ Running.. Running.. Running.. ✆ 2.4.1 Exception Handling In Java, when compiler encounters with errors it throws an exceptions. To run the program, these errors must be caught by the invoking code. This invoking code can handle the exception as needed and then continue executing. Uncaught exceptions result in the termination of the thread of execution. Uncaught excep- tions are reported by compiler. Exception objects are the Exception class, which provides a string field to describe the error. All exceptions must be subclasses of the class Throwable, which is the superclass of Exception. try-catch-finally sequence is used to catch an Exception. ✞ 1 package jscript; 3 public class Jscript extends Thread { 5 public static void main(String[] args) { int i = 1; 7 Thread th = new Thread(); for (;;) { 9 try {/*Try to invoke thread by start method.*/ try {/*Try to invoke sleep thread.*/ 11 th.sleep(2000); }/*If any internal error occured * 13 *then catch the exception handle.*/ catch (InterruptedException ex) { 15 System.out.println("Sleep Interrupt Exception."); } 17 th.start(); th.start(); 19 } /*If any internal state error occured* * then catch the exception handle. */ 21 catch (IllegalThreadStateException ex) { System.out.println("Illegal Thread State Exception."); 23 } } 25 } } ✆ ✞ Illegal Thread State Exception. Illegal Thread State Exception. ............ ............ ✆
  • 63. Chapter 3 Accessing System Files Standard Input-Output and access of files is a main part of computer program- ming. In this chapter we shall discuss the importance and methodology of accessing system and user define files. 3.1 Input Output A Java program under execution opens automatically input and output streams. The first standard stream is used for input buffering and the other used for outputs. These streams are sequences of bytes. To read a character from a BufferedReader, read() is used. Each time that read() is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of the stream is encountered. ✞ package jscript; 2 import java.io.*; public class Jscript { 4 public static void main(String[] args) throws IOException { char c; 6 BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); System.out.println("Enter characters, ’q’ to quit."); 8 do { c = (char) br.read(); 10 System.out.println(c); } while (c != ’q’); 12 } } ✆ To read a line from input console, readLine() is used as shown in example below. ✞ 1 package jscript; import java.io.*; 3 public class Jscript { 63
  • 64. 64 CHAPTER 3. ACCESSING SYSTEM FILES 5 public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); 7 String str; System.out.println("Enter contents in each line."); 9 System.out.println("Enter ’stop’ to quit."); do { 11 str = br.readLine(); System.out.println(str); 13 } while (!str.equals("stop")); } 15 } ✆ Buffer space is created by the allocate() method at ByteBuffer class. To create one megabyte buffer space, allocate() method is used as ✞ 1 ByteBuffer buff = ByteBuffer.allocate(1024 * 1024); ✆ This method is in nio.* class. ✞ 1 package jscript; 3 import java.nio.*; 5 public class Jscript { 7 public static void main(String[] args) { ByteBuffer buff = ByteBuffer.allocate(1024 * 1024); 9 System.out.println(buff); } 11 } ✆ ✞ java.nio.HeapByteBuffer[pos=0 lim=1048576 cap=1048576] ✆ The read() method is used to place read data into buffer by using as ✞ 1 inf.read(buff); ✆ If there is requirement to write data in ‘buff’ in out stream it must be converted into write mode by using flip() method. ✞ 1 buff.flip(); outf.write(buff); ✆ Other buffer types are ShortBuffer, IntBuffer, CharBuffer, FloatBuffer, Double- Buffer and LongBuffer. 3.1.1 File Handling Some times it is required to read, write and access a file to read or write some contents to it.
  • 65. 3.1. INPUT OUTPUT 65 Open a File FileInputStream class is used to open a file as shown in the following syntax. ✞ FileInputStream(String <file name>) throws FileNotFoundException ✆ Here, ‘file name’ specifies the name of the file that needed to be open. If file does not exist to open FileNotFoundException is thrown. ✞ 1 import java.io.*; public class Jscript { 3 public static void main(String[] args) throws IOException { int i; 5 FileInputStream fin; try { 7 fin = new FileInputStream("test.txt"); } catch (FileNotFoundException e) { 9 System.out.println("File Not Found"); return; 11 } fin.close(); 13 } } ✆ Again a new file can be created by using createNewFile() method. This method first checks whether a named file is pre-exists or not. If exists, it does not create new file with same name and returns false and throws an IOException. If created then it returns true. ✞ package jscript; 2 import java.io.*; 4 public class Jscript { 6 public static void main(String[] args) throws IOException { 8 File f = new File("newfile.dat"); boolean success; 10 success = f.createNewFile(); if(success){ 12 System.out.println("Created new file."); }else{ 14 System.out.println("Unable to create new file."); } 16 } } ✆ ✞ Created new file. ✆
  • 66. 66 CHAPTER 3. ACCESSING SYSTEM FILES Close a File Any opened file shall be closed when it is not required or required by other program to access it. Opened file is closed by using ✞ 1 fin.close(); ✆ Reading File The contents of the file are read by using object read(). It returns the character code read from the file. read() returns ‘-1’ when it encounters EOF. ✞ 1 package jscript; 3 import java.io.*; 5 public class Jscript { public static void main(String[] args) throws IOException { 7 int i; FileInputStream fin; 9 try { fin = new FileInputStream("test.txt"); 11 } catch (FileNotFoundException e) { System.out.println("File Not Found"); 13 return; } 15 do { i = fin.read(); 17 if (i != -1) { System.out.print((char) i); 19 } } while (i != -1); 21 fin.close(); } 23 } ✆ Writing File FileOutputStream is used to create and write a file. The syntax for this class is ✞ 1 FileOutputStream(String <file name>) throws FileNotFoundException ✆ Here, ‘file name’ specifies the name of the file that is to be created. If it is unable to create a new file to write, FileNotFoundException is thrown. Any pre-existing file is destroyed or overwritten. The contents are written to the file by using write() method. ✞ 1 package jscript;
  • 67. 3.1. INPUT OUTPUT 67 3 import java.io.*; 5 public class Jscript { 7 public static void main(String[] args) throws IOException { int i = 0; 9 FileOutputStream fout; try { 11 fout = new FileOutputStream("text.txt"); } catch (FileNotFoundException e) { 13 System.out.println("Unable to open a file"); return; 15 } try { 17 do { fout.write(i); 19 i++; } while (i < 10); 21 } catch (IOException e) { System.out.println("File Error"); 23 } fout.close(); 25 } } ✆ Temporary File In Java, a temporary file is created by method createTempFile(). Compiler throws errors if we try to create two temporary files with same name. To create the temporary file in current temporary file, use following synopsis ✞ File <temp file name> = File.createTempFile(<name>, <ext>, cwd); ✆ ✞ 1 package jscript; 3 import java.io.*; 5 public class Jscript { 7 public static void main(String[] args) throws IOException { File temp = File.createTempFile("tmp", ".tmp"); 9 System.out.println(temp); } 11 } ✆ ✞ C:DOCUME~1ADMINI~1LOCALS~1Temptmp1895285192040487408.tmp ✆ To create temporary file anywhere you want then use following synopsis.
  • 68. 68 CHAPTER 3. ACCESSING SYSTEM FILES ✞ 1 File loc = new File(<path>); File <temp file name> = File.createTempFile(<name>, <ext>, loc); ✆ ✞ package jscript; 2 import java.io.*; 4 public class Jscript { 6 public static void main(String[] args) throws IOException { 8 File loc = new File("d:/"); File temp = File.createTempFile("temp", ".tmp", loc); 10 System.out.println(temp); } 12 } ✆ ✞ d:temp7521897237899708714.tmp ✆ Before creation of temporary file of specific size, the required space in the direc- tory should be known. To get the size of destination, getTotalSpace() method is used. ✞ 1 package jscript; 3 import java.io.*; 5 public class Jscript { 7 public static void main(String[] args){ File d = new File("d:/"); 9 long ds = d.getTotalSpace(); System.out.println("Size of root D:/ is " + ds + "bytes."); 11 File e = new File("e:/"); long es = e.getTotalSpace(); 13 System.out.println("Size of root E:/ is " + es + "bytes."); } 15 } ✆ ✞ Size of root D:/ is 110637346816bytes. Size of root E:/ is 117942775808bytes. ✆ Memory Mapped I/O In the nio.* class, The MappedByteBuffer class maps a file directly into a Byte- Buffer. It can be operatred by using put( ), get( ), putInt( ), getInt( ) and other methods. put( ) and get( ) access the file directly without copying a lot of data to and from RAM. The synopsis of it is
  • 69. 3.1. INPUT OUTPUT 69 ✞ MappedByteBuffer buff 2 = <file channel>.map(FileChannel.MapMode.<file mode>, <position>, < size>); ✆ The ‘file mode’ operations are READ ONLY, READ WRITE and PRIVATE. ✞ package jscript; 2 import java.io.*; 4 import java.nio.*; import java.nio.channels.*; 6 public class Jscript { 8 public static void main(String[] args) throws IOException { 10 /*Open new file.*/ File file = new File("test.txt"); 12 /*Get file stream.*/ FileInputStream fis = new FileInputStream(file); 14 /*Try to get the channel of the opened file stream.*/ try (FileChannel fc = fis.getChannel()) { 16 /*Get the size of file.*/ long size = fc.size(); 18 /*Map the file data from the file channel.*/ MappedByteBuffer bb = 20 fc.map(FileChannel.MapMode.READ_ONLY, 0, size); 22 for (int i = 0; i < size; i++) { try { 24 /*Do what you need the mapped data.*/ System.out.println(i+" -> "+bb.get(i)); 26 } catch (Exception e) { } 28 } } 30 } } ✆ MappedByteBuffer has three methods, force( ), load( ), and isLoaded( ). The load( ) method attempts to load the entire buffer into main memory. If the data is larger than Java’s heap size, this is likely to cause some page faults and disk thrashing. The isLoaded( ) method tells whether a buffer is loaded. To put data in a MappedByteBuffer, force( ) method is used. Random Access File In Java, normally a file stream is started accessing data from beginning. To access the data of a file from a specific position, RandomAccessFile class is used. The synopsis of it is
  • 70. 70 CHAPTER 3. ACCESSING SYSTEM FILES ✞ 1 RandomAccessFile rs=new RandomAccessFile(<file name>, <access mode>); ✆ In Java, there is no write only access mode, so read and write both mode are used commonly. The getFilePointer( ) and seek( ) methods allow to query and change the position in the file at which reads and writes occur. ✞ 1 package jscript; 3 import java.io.*; 5 public class Jscript { 7 public static void main(String[] args) throws IOException { File file = new File("test.txt"); 9 RandomAccessFile rf = new RandomAccessFile(file, "rw"); rf.seek(10); 11 long rfp1 = rf.getFilePointer(); System.out.println("Current position of file is " + rfp1); 13 rf.seek(0); long rfp2 = rf.getFilePointer(); 15 System.out.println("Current position of file is " + rfp2); rf.close(); 17 } } ✆ ✞ Current position of file is 10 Current position of file is 0 ✆ ✞ skipBytes(<bytes number>) ✆ skipBytes() skips a file by ‘n’ bytes from the current position of the file. close() method is used to close the current open file. ✞ 1 package jscript; 3 import java.io.*; 5 public class Jscript { 7 public static void main(String[] args) throws IOException { File file = new File("test.txt"); 9 RandomAccessFile rf = new RandomAccessFile(file, "rw"); rf.seek(10); 11 long rfp1 = rf.getFilePointer(); System.out.println("Current position of file is " + rfp1); 13 rf.skipBytes(10); long rfp2 = rf.getFilePointer(); 15 System.out.println("Current position of file is " + rfp2); rf.close();
  • 71. 3.1. INPUT OUTPUT 71 17 } } ✆ ✞ Current position of file is 10 Current position of file is 20 ✆ File Pointer to Class 3.1.2 File Directory Sometimes user needs to read, create, delete or change a directory. In this section we will use specific functions related with handling of a directory. Finding Roots To get the system partitions, listRoots() method is used for listing of roots. This method returns the array of all disk partitions, i.e. roots. ✞ package jscript; 2 import java.io.*; 4 public class Jscript { public static void main(String[] args) { 6 /*Get the array of roots.*/ File[] roots = File.listRoots( ); 8 /*Print all root names.*/ for (int i = 0; i < roots.length; i++) { 10 System.out.println(roots[i]); } 12 } } ✆ ✞ C: D: E: F: H: ✆ File Object File deals directly with files and the file system. The File class describes the properties of a file itself. A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. The syntax of File is ✞ 1 File(<path or URI of file>); ✆
  • 72. 72 CHAPTER 3. ACCESSING SYSTEM FILES There are several objects which tell information about the file’s name, its path, its size, is a file, is a directory, is readable, is writable, make directory etc. Few of then are used in the following example for file “test.txt”. ✞ 1 package jscript; 3 import java.io.File; 5 public class Jscript { 7 public static void main(String[] args) { File f1 = new File("test.txt"); 9 System.out.println(f1.getName());/*test.txt*/ System.out.println(f1.getPath());/*test.txt*/ 11 System.out.println(f1.canRead());/*true*/ System.out.println(f1.canWrite());/*true*/ 13 System.out.println(f1.exists());/*true*/ System.out.println(f1.isFile());/*true*/ 15 System.out.println(f1.length());/*210 (in bytes)*/ } 17 } ✆ ✞ test.txt test.txt true true true true 210 ✆ Directory A directory is a File that contains a list of other files and directories. We can create a File object and checked whether its is a directory or not by isDirectory() method. Other files can be listed by using method list() on the object to extract the list of other files and directories inside. Its synopsis is ✞ 1 <file object>.list(); ✆ The list of files is returned in an array of String objects. ✞ 1 package jscript; 3 import java.io.File; 5 public class Jscript { 7 public static void main(String[] args) { File f1 = new File("./");
  • 73. 3.1. INPUT OUTPUT 73 9 if (f1.isDirectory()) { String flist[] = f1.list(); 11 for (int i = 0; i < flist.length; i++) { System.out.println(flist[i]); 13 } } 15 } } ✆ ✞ build build.xml manifest.mf nbproject src test.txt text.txt ✆ mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. To create a directory for which no path exists, use the mkdirs() method. It creates both a directory and all the parents of the directory. ✞ 1 package jscript; 3 import java.io.File; 5 public class Jscript { 7 public static void main(String[] args) { File f1 = new File("ak"); 9 boolean i = f1.mkdir(); System.out.println(i); 11 } } ✆ A file or directory can be delete by delete() method. It returns true on successful and false on failure. Failure indicates either file or directory does not exist. ✞ package jscript; 2 import java.io.File; 4 public class Jscript { 6 public static void main(String[] args) { 8 File f1 = new File("ak"); boolean i = f1.mkdir(); 10 System.out.println(i); }
  • 74. 74 CHAPTER 3. ACCESSING SYSTEM FILES 12 } ✆ A file or directory can be rename by renameTo() method. It returns true on successful and false on failure. Failure indicates either file or directory either does not exist or can not be renamed. ✞ package jscript; 2 import java.io.File; 4 public class Jscript { 6 public static void main(String[] args) { 8 File f1 = new File("test.txt"); File f2 = new File("ab.txt"); 10 f1.mkdir(); boolean i = f1.renameTo(f2); 12 System.out.println(i); } 14 } ✆ 3.2 JNI