Java Programming Notes for Beginners by Arun Umrao
ssuserd6b1fd
163 views
74 slides
Oct 10, 2021
Slide 1 of 74
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
About This Presentation
Shot notes for quick revision. Not explained extensively but suitable for last night preparation. Fit for CBSE Class XII board students for their last minute preparation.
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 viainstream while output is sent viaout
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 examplebelow,
in which “Hi” is printed in output stream.
✞
1packagejscript;
/*Jscript is main class name. It shall be same as*
3*file name. i.e. file name must be jscript.java*/
public classJscript {
5
public static voidmain(String[] args) {
7 System.out.println("Hi");
}
9}
✆
✞
Hi
✆
When a java program is run, it starts execution from themain() function.
Thismain() function is defined here as public so that it can be executed from
anywhere. Its return type isvoid, i.e. no return value. In the following line
✞
1public static voidmain(String[] args) {}
✆
7
8 CHAPTER 1. INTRODUCTION
(String[] args)receives the string array from the commandline. Number of input
arrays are counted by usinglengthobject. In java, class name shall be same as
its file name where it is declared. Hereprintlnis similar to theprintfof 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.
✞
1packagejscript;
/*Jscript is main class name. It shall be same as*
3*file name. i.e. file name must be jscript.java*/
public classJscript {
5
public static voidmain(String[] args) {
7 System.out.println("Hi "+10+" .");
}
9}
✆
✞
Hi 10 .
✆
Here,printlnis short form of print a line and it prints the string at output
stream.printfis short form of print formatted and it can be used in place of
printlnfor formatted output.
✞
1packagejscript;
/*Jscript is main class name. It shall be same as*
3*file name. i.e. file name must be jscript.java*/
5public classJscript {
7 public static voidmain(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. Ifthis 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 20characters
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.
✞
1packagejscript;
3public classJscript {
1.1. DATA IN & DATA OUT 9
SymbolicConstant 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 voidmain(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 usedsimulta-
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.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti;
System.out.printf("%5s%10s%10s\n","Num","Square","Cubic");
8 for(i = 90; i < 92; i++) {
System.out.printf("%5d%10d%10d\n", 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
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
System.out.println("Rajasthan");
7 }
}
✆
\nat the end ofprintlnfunction 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 CharacterMeaning
\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.
✞
packagejscript;
2/*Jscript is main class name. It shall be same as*
*file name. i.e. file name must be jscript.java*/
4public classJscript {
6 public static voidmain(String[] args) {
System.out.println("Uttar Pradesh.");
8 }
}
✆
✞
Uttar Pradesh.
✆
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
chara =’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 twotype
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*/
packagejscript;
5
public classJscript {
7
public static voidmain(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 locationsin 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 underscopecharac-
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??.
✞
1intA1;// Legal and acceptable.
int1A;// Illegal, first character is numeric
3intA_1;// Legal, _ is acceptable
intA$1;// Legal, $ is not reserved character
5intA 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 eithertrueorfalse.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
1.1. DATA IN & DATA OUT 13
6 System.out.println("Function is "+false);
}
8}
✆
✞
Function is false
✆
Character
charis used to initialize a 18 bit unsigned unicode character.
✞
1char*<var name>=<charcode>;
✆
Acharvariable without initialization is not acceptable in java.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
charA1=100;
7
System.out.println("Char is "+ A1);
9 }
}
✆
✞
Char is d
✆
Byte
It is one byte long integer value.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
bytei = 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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
bytei = 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 thencompiler
shows error and refuse to compile the program.
Integer
A 4 byte long numerical value is declared and initialized by using primitive data
typeint. If an integer variable is initialized as decimal number, then compiler
refuse to compile the program.
✞
1int<var name>;
int<var name>=<value>;
✆
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti=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 from1.2×10
−38
to 1.2×10
38
. Syntax for the float data type is
1.1. DATA IN & DATA OUT 15
✞
1float<var name>;
float<var name>= (float) <decimal value>;
✆
See the example below.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 floati = (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 rangeis from
2.3×10
−308
to 2.3×10
308
. Syntax for the double data type is
✞
1double<var name>;
double<var name>=<decimal value>;
✆
See the example below.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 doublei = 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:
✞
1intvariable_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
✞
1intvariable_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 examplevariableais initialized by
✞
1intvariable_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 aliteral.
Literals can either take a form defined by their type, or one can usehexadecimal
(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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 0x50;
7 System.out.println("i is "+ i);
}
9}
✆
✞
i is 80
✆
Signed & Unsigned Integer
A byte is 8 bit long. The size ofintis 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 storingan
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 positivesign 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 notstore 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 canbe stored
by it is 255. Initially, datatype has initialized with decimal value 254.
✞
1datatype k = 254d = 11111110b
✆
datatype is incremented by 1, it becomes
✞
1datatype k = 255d = 11111111b
✆
Again, datatype is incremented by 1, it becomes
✞
1datatype 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.*/
2datatype k = -0d = (1)0000000b
✆
It becomes negative zero. Again, if increment by 1, the result is
✞
/* Bit inside parentheses represents to sign.*/
2datatype 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 othertype data.
Type casting may be of two types: (i) Implicit type casting and (ii) Explicit
type casting. Implicit type casting is automatically handled by compileri.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
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 floati = (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 usingtoCharArray() 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 usingsplit() 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
✞
1String[] sArray=s.split("");/*No space by ""*/
✆
✞
1package jscript;
3public class Jscript {
5 publicstatic voidmain(String args[]) {
String str ="This is my room";
7 String[] k = str.split(" ");
System.out.printf("i is in string : %s\n", 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 thesame 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
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti=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 asless than.
2.>known asgreater than.
3.≤known asless than or equal to.
4.≥known asgreater than or equal to.
5. == known asequals.
6. ! = known asnot equals.
1.2. JAVA OPERATORS 21
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inta = 10;
7 intb = 20;
intc = 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 returnstruein 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
✞
inta = 20;//constant initialized
2if(a = 10)//incompatible integer type
System.out.println("Stuff");
✆
✞
1if(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.
✞
1packagejscript;
22 CHAPTER 1. INTRODUCTION
3public classJscript {
5 public static voidmain(String[] args) {
intv = 7;
7 if(v == 7) {
System.out.println("v is "+ v);
9 }
}
11}
✆
✞
v is 7
✆
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
intv = 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. Logicaloperators
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.
✞
1package jscript;
3public class Jscript {
5 publicstatic voidmain(String[] args) {
1.2. JAVA OPERATORS 23
System.out.printf("6 != 6 && 6 / 2 < 5 is %b\n", 6 != 6 && 6 / 2
< 5);
7 System.out.printf("6 != 6 || 6 / 2 < 5 is %b\n", 6 != 6 || 6 / 2
< 5);
System.out.printf("6 != 6 is %b\n", 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.
✞
1package jscript;
3public class Jscript {
5 publicstatic voidmain(String[] args) {
System.out.printf("(2 < 3) && (4 > 5) is %b\n", (2 < 3) && (4 >
5));
7 System.out.printf("(2 < 3) && (4 < 5) is %b\n", (2 < 3) && (4 <
5));
}
9}
✆
✞
(2 < 3) && (4 > 5) is false
(2 < 3) && (4 < 5) is true
✆
✞
package jscript;
2
public class Jscript {
4
publicstatic voidmain(String[] args) {
6 intx = 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 %b\n", x != 6 && x / 2 <
5);
12 }
}
✆
✞
Expression result is false
✆
24 CHAPTER 1. INTRODUCTION
✞
1package jscript;
3public class Jscript {
5 publicstatic voidmain(String[] args) {
intx = 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 %b\n", 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 asx >(y+ 2) and
x=y >2 is same asx= (y >2). It means, in an expression, order of evalu-
ation of operators is arithamtic operators, relational operatorsand assignment
operators respectively.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
intx = 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 bits
1
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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
/*10 is Binary equivalent to 1010*/
7 inti = 10;
/*5 is Binary equivalent to 0101*/
9 intj = 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 thanthe lesser
operand. This is why & operator is used to restric the upper limit of the random
result.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti = 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.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti = 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
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 /*Bit pattern of Decimal 4 is equivalent to binary 100*/
inti = 4;
8 /*Number of places take place by binary shift.*/
intj = 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.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 intx = 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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
chara =’a’;/*Binary equivalent-1100001*/
7 charb =’b’;/*Binary equivalent-1100010*/
charc =’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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
intj = 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
✆
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
floati = 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 sequencethe expres-
sion is written. But some rules are used. For example, parenthesesare 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
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inty;
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.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inty = 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 ofif() construct is
✞
1if(/*conditions*/)// if condition is true then
statement// execute the condition.
✆
A simple example is
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti=0;
while(i < 5) {
8 if(i == 2) {
System.out.printf("i is %d\n", i);
10 }
i++;
12 }
}
14}
✆
✞
i is 2
✆
1.3.2 if-else condition
if-elseprovides 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
ofif-elseconstruct is
✞
1if(/*conditions*/)// if condition is true then
statement one// execute the statement one.
3else// otherwise if condition is false
statement two// execute the statement two.
✆
A simple example is
✞
packagejscript;
2
public classJscript {
4
34 CHAPTER 1. INTRODUCTION
public static voidmain(String[] args) {
6 inti=0;
while(i < 5) {
8 if(i == 2) {
System.out.printf("i is %d\n", i);
10 }else{
System.out.printf("i is NOT %d\n", 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 ofif-elsecondition is
✞
1inta=(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 - elsestatement can be used successively.
1.3.3 switch
Use of a long chain ofif-else-if-else-if-elseis very complex and less readable.
There’s a solution by using the Switch-Case construct. The basic syntax of this
construction is given below.
✞
1switch(<casevariable>) {
case1:
3 statements one
break;
5 case2:
statements two
7 break;
case3:
9 statements three
break;
11 default:
defaultstatement
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
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti = 0;
while(i < 5) {
8 switch(i) {
case1:
10 System.out.printf("i is %d\n", i);
break;
12 case2:
System.out.printf("i is %d\n", i);
14 break;
case3:
16 System.out.printf("i is %d\n", i);
break;
18 default:
System.out.printf("either i<1 or i>3\n");
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 operatoris 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 switchblock from
the current loop.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 0;
7 while(i < 5) {
switch(i) {
9 case1:
System.out.printf("i is %d\n", i);
11 case2:
System.out.printf("i is %d\n", i);
36 CHAPTER 1. INTRODUCTION
13 case3:
System.out.printf("i is %d\n", i);
15 break;
default:
17 System.out.printf("either i<1 or i>3\n");
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 morethan 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 areforandwhile.
1.4.1 for loop
The syntax offorloop is
✞
for(initialization; test; increment) {
2 /* code */
}
✆
The working example is
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inta, 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 theforloop executes. If this expression evaluates as 0 (false), the
loop is not (re)enter into theforloop. And execution of program carry on to
the code immediately following theforloop. If the expression is non-zero (ie
true), the loop is (re)enter inside theforloop. 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 ifforis defined as shown below.
✞
1for(;;) {
/* statements / codes */
3}
✆
Multiple initialization can be used by separating them by comma.
✞
1for(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}
✆
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti, j;
7 for(i = 6, j = 1; j < i; i++, j = (j + 2)) {
System.out.printf("Product of i=%d & j=%d is %d\n", 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
Awhile() 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,whileloop exits.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 0;
7 while(i < 5) {
System.out.printf("i*i is %d\n", 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 offorloop as
✞
1for(; <test> ; )
✆
is similar to thewhileloop
✞
1while(<test>)
✆
Following is an example which shows thatforloop is similar to thewhileloop.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 0;
1.5. PARSING ARGUMENTS 39
7 for(; i < 5;) {
System.out.printf("%d\t", i);
9 i++;
}
11 System.out.printf("\n");
intj = 0;
13 while(j < 5) {
System.out.printf("%d\t", 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. Thesearguments
are considered as inputs for the executable. To pass the values wedefinemain()
function as
✞
public static voidmain(String[] args)
✆
Here ‘args’ are the array of input strings.
✞
1packagejscript;
3classJscript {
5 public static voidmain(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 0
th
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 area+b,a−b,
a∗b,a/banda%brespectively.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
floati = 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
Thecos,sin, andtanfunctions return the cosine, sine, and tangent of the
argument, expressed in radians. The domain of arguments ofsin,cosandtan
are [−π/2, π/2], [0, π] and [−π/2, π/2] respectively. The numerical range ofsin,
cosandtanare [−1,1], [−1,1] and [−∞,∞].
✞
1doublecos(doublex);
doublesin(doublex);
3doubletan(doublex);
✆
A simple example is
✞
1packagejscript;
3public classJscript {
1.6. MATHEMATICAL OPERATOR 41
5 public static voidmain(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
Theacos() 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
. Theatan()
returns their argument value in radian in the range
h
−
π
2
,
π
2
i
. Method of use of
inverse function in following systems.
✞
1doubleasin(doublex);
doubleacos(doublex);
3doubleatan(doublex);
✆
A simple example is
✞
1packagejscript;
3public classJscript {
5 public static voidmain(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
Thecosh(),sinh() andtanh() functions compute the hyperbolic cosine, the
hyperbolic sine and the hyperbolic tangent of the argument respectively.
✞
1doublecosh(doublex);
doublesinh(doublex);
3doubletanh(doublex);
✆
A simple example is
✞
1packagejscript;
3public classJscript {
5 public static voidmain(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’.
✞
1doubleexp(doublex);
doublelog(doublex);
✆
A simple example is
✞
packagejscript;
2
public classJscript {
4
public static voidmain(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.sqrtreturns the
square root of a variable value.floor() rounded fraction to down.ceil() rounded
fraction to up andround() rounded up the number if fraction is equal or more
than 0.5.
✞
doublepow(doublex,doubley);
2doublesqrt(doublex);
doublefloor(doublex);
4doubleceil(doublex);
doubleround(doublex);
✆
A simple example is
✞
1packagejscript;
3public classJscript {
5 public static voidmain(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. AStringclass type deals specifically with sequences of character
data. A string is declared and intialized as
✞
1/*Declaration of string*/
String s=newString();
3/*Initialization of string*/
charchars[] = {’a’,’b’,’c’,’d’,’e’};
5String s =newString(chars);
✆
A substring can also be intialized ifStringclass is used like
✞
1charchars[] = {’a’,’b’,’c’,’d’,’e’};
String s =newString(chars, <pos index>, <number of chars>);
✆
InStringobjectslength() method returns the number of characters in the string.
✞
String s =newString();
2intn=s.length();/*Length of string.*/
✆
Characters are indexed from 0 tolength()-1, and can be accessed with the
✞
charAt(<index>)
✆
method. String objects are read-only.
✞
1charch;
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 ArrayIn Java an array is declared by using keywordnewlike
✞
int[] ia =new int[3];
2float[] ia =new float[3];
String[] sa=newString[10];
✆
Initialization an ArrayIn 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
✞
1int[] ia =new int[3]{1, 2, 3};
✆
✞
1packagejscript;
3public classJscript {
public static voidmain(String[] args) {
5 int[] ia =new int[]{1, 2, 3};
System.out.println(ia.length);
7 }
}
✆
✞
3
✆
Dynamic Array SizeIf the array is declared as shown below then size of
array is determined at the execution time.
✞
1int[] ia=new int[/*No value here*/];
✆
✞
1packagejscript;
3public classJscript {
public static voidmain(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
✞
1intnumbers[6];// array declared
intpoint[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.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 inti = 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 additionalelement
to the list will increase its size to five. Static declaration of the size ofan 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
6intia[][][] =new int[3][4][5];
✆
Where [2] represents to the number of rows and [3] represents tothe 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 vectorsor matrices.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args) {
6 intix, 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("%2d\t", 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 usinglengthobject.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
inti = 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 aclass 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. Apublic class
should be declared in a separate file having name as public class name. Aclass
is declared as
✞
1class<classname>{
<scope> <data type> <var a>, <var b>;
3}
✆
In following lines, class Trees is declared with two variables or fields.
✞
1classTrees{
public charname;
3 public doublelength;
}
✆
Objects are created by expressions containing thenewkeyword. Creating an
object from a class definition is also known as instantiation; thus, objects are
often called instances.
✞
Trees t=newTrees();
✆
The members may be assigned a value as
✞
1t.name="a";
✆
Again, the value of a class member can also be accessed by using
✞
1t.name
/*or*/
3t.length
✆
See example below:
✞
1packagejscript;
3classTrees {
5 public charname;
public doublelength;
7}
9public classJscript {
50 CHAPTER 2. STRING & ARRAYS
11 public static voidmain(String[] args) {
Trees t =newTrees();
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.
✞
packagejscript;
2
classBox {
4
intlength;
6 intwidth;
intheight;
8
intVolume() {
10 returnlength * width * height;
}
12}
14public classJscript {
16 public static voidmain(String[] args) {
Box b =newBox();
18 b.length = 2;
b.width = 1;
20 b.height = 3;
intvol = b.Volume();
22 System.out.printf("Volume of Box is %d\n", vol);
}
24}
✆
✞
Volume of Box is 6
✆
✞
1packagejscript;
/*Class*/
3
classmyClass {
5
privateString name;
7 private intage;
2.3. CLASS, OBJECT & FUNCTION 51
/*Object of the class and its initialization*/
9
publicmyClass(String name,intage) {
11 this.name = name;
this.age = age;
13 }
/*Object get name*/
15
publicString getName() {
17 returnname;
}
19 /*Object get age*/
21 publicObject getAge() {
returnage;
23 }
}
25
public classJscript {
27
public static voidmain(String[] args) {
29 myClass sun =newmyClass("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.
✞
packagejscript;
2
classmyClass {
4
publicString name;
6 public intdis;
8 publicmyClass(String n,intd) {
name = n;
10 dis = d;
}
12}
14public classJscript {
16 public static voidmain(String[] args) {
myClass sun =newmyClass("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.
✞
1public class<classname>{
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<classname>.<function name>(argument a, argument b);
✆
Here, class name is the name of java file in which function is written. Inthe
following example, two files, Jscript.java and Sum.java are placed inside the
package jscript. The file containingmainclass is Jscrip.java and it contains the
codes given below.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(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.
✞
packagejscript;
2
public classSum {
4
public static intsum(inta,intb) {
6 returna + b;
}
8}
✆
We call the sum function frommainclass 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 withtwo argu-
ments is defined as
✞
1public static intsum(inta,intb);
✆
Here,inta,intb 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
✞
1public static intsum(inta,intb);
✆
while, the definition of function as given below is illegal.
✞
1public static intsum(inta, b);//Illegal definition
✆
Here, second argument ‘b’ is type unidentified. In Java, a functioncan be called
from anywhere by supplying actual arguments as
✞
1Sum.sum(2, 3);
✆
See example below. Jscript.java contains the codes given below.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
System.out.println("Sum of 2 and 3 is "+ Sum.sum(2, 3));
7 }
}
✆
Sum.java contains the codes given below.
✞
packagejscript;
2
public classSum {
4
public static intsum(inta,intb) {
6 returna + b;
}
8}
✆
We call the sum function from themainclass 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
✞
1public static intsum(int,int);/*Illegal prototype.*/
public static intsum(inta,intb);/*Legal prototype.*/
3public static intsum(a,intb);/*Illegal prototype.*/
✆
2.3.3 this Reference
Thethisreference 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.
✞
1packagejscript;
3classmyClass {
5 publicString name;/*Name field*/
public intdis;/*Distance field*/
7 /*Passed argument names are similar to field name.*/
publicmyClass(String name,intdis) {
9 /*To distict the field name from *
*argument this reference is used.*/
11 this.name = name;
this.dis = dis;
13 }
}
15
public classJscript {
17
public static voidmain(String[] args) {
19 myClass sun =newmyClass("Sooraj", 15);
System.out.printf("Distance of %s is %d.\n", sun.name, sun.dis);
21 }
}
✆
✞
Distance of Sooraj is 15.
✆
Ifthisreference is not used then code and result shall be looked like
✞
1packagejscript;
3classmyClass {
2.3. CLASS, OBJECT & FUNCTION 55
5 publicString name;/*Name field*/
public intdis;/*Distance field*/
7 /*Passed argument names are similar to field name.*/
publicmyClass(String name,intdis) {
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 classJscript {
19
public static voidmain(String[] args) {
21 myClass sun =newmyClass("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 sharedonly
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.
✞
1packagejscript;
/*Creatign a super class*/
3classBoxVol {
intl, w, h;
5 intVolume() {
returnl * 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. */
classBoxSurextendsBoxVol {
56 CHAPTER 2. STRING & ARRAYS
13 intSurface() {
return2 * (l * w + w * h + l * h);
15 }
}
17public classJscript {
public static voidmain(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 =newBoxSur();
25 /*Access varibles of super class.*/
a.l = 2;
27 a.w = 1;
a.h = 3;
29 /*Fetch the member value of super class.*/
intvol = a.Volume();
31 System.out.printf("Volume of Box is %d\n", vol);
/*Fetch the member value of sub class.*/
33 intsur = a.Surface();
System.out.printf("Surface Area of Box is %d\n", 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
✞
intMyFunc(){
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.
✞
1package jscript;
3public class Jscript {
/*To use s as global, it should be defined as static.*/
5 static doubles = 0.0;
7 doubleMyFunc() {
s = 10;
2.4. THREADING 57
9 returns;
}
11
publicstatic voidmain(String args[]) {
13
Jscript j = new Jscript();
15 j.MyFunc();
System.out.printf("s is %f\n", s);
17 }
}
✆
✞
s is 10.000000
✆
2.3.7 Type of Objects
2.4 Threading
A thread is initiated byThreadobject like
✞
1Thread th =newThread();
✆
In following example a thread is created.
✞
1packagejscript;
3public classJscript {
5 public static voidmain(String[] args) {
Thread th =newThread();
7 System.out.println(th);
}
9}
✆
✞
Thread[Thread-0,5,main]
✆
In following example,Jscript class is extended to Thread object.
✞
1packagejscript;
/*Class extended to Thread*/
3public classJscriptextendsThread {
5 public static voidmain(String[] args)throwsInterruptedException {
inti = 1;
7 for(;;) {
/*sleep method throws InterruptedException.*/
9 Thread.sleep(1000);
System.out.printf("Seconds passed %d\n", 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 usingThreadobject.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args)throwsInterruptedException {
6 inti = 1;
/*Independent Thread is initiated.*/
8 Thread th =newThread();
for(;;) {
10 /*sleep method throws InterruptedException.*/
th.sleep(1000);
12 System.out.printf("Seconds passed %d\n", i);
i++;
14 }
}
16}
✆
✞
Seconds passed 1
Seconds passed 2
........
........
✆
After aThreadobject is created, it can be configured and run. A thread is
invoked bystart() method. The virtual machine invokes the new thread’srun()
method, making the thread active. A thread can be invoked only once. Multiple
invoking of same thread resultsIllegalThreadStateException.
✞
packagejscript;
2
public classJscript {
4
public static voidmain(String[] args){
6 Thread th =newThread();
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 voidrun();
✆
Actually the code inside therun() object does the real job.
✞
1packagejscript;
3public classJscriptextendsThread {
5 privateString word;
private intdelay;
7
publicJscript(String w,intd) {
9 word = w;
delay = d;
11 }
13 @Override
public voidrun() {
15 try{
for(;;) {
17 System.out.printf(word +" \n");
Thread.sleep(delay);
19 }
}catch(InterruptedException e) {
21 return;
}
23 }
25 public static voidmain(String[] args) {
newJscript("ping", 1000).start();
27 newJscript("PONG", 3000).start();
}
29}
✆
✞
ping
PONG
ping
ping
PONG
✆
wait(),notify() andnotifyAll() methods tells waiting threads that something
has occurred that might satisfy that condition. Thewait() and notification
methods are defined in class Object and are inherited by all classes.
Name of thread can be changes bysetName() method. See the example
below.
60 CHAPTER 2. STRING & ARRAYS
✞
1package jscript;
3public class Jscript extends Thread {
5 @Override
publicvoidrun() {
7 System.out.println("Running....");
}
9
publicstatic voidmain(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 usingsetPriority() method. There are three types
of priorities - MINPRIORITY, NORM PRIORITY and MAX PRIORITY.
✞
package jscript;
2
public class Jscript extends Thread {
4
@Override
6 publicvoidrun() {
/*Current thread tells the current running thread*/
8 System.out.println(Thread.currentThread().getPriority());
}
10
publicstatic voidmain(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 usingjoin() method.
✞
package jscript;
2
public class Jscript extends Thread {
4
publicvoidrun() {
6 System.out.println("Running..");
}
8
publicstatic voidmain(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 besubclasses
of the class Throwable, which is the superclass of Exception. try-catch-finally
sequence is used to catch an Exception.
✞
1packagejscript;
3public classJscriptextendsThread {
5 public static voidmain(String[] args) {
inti = 1;
7 Thread th =newThread();
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 otherused for
outputs. These streams are sequences of bytes. To read a character from a
BufferedReader,read() is used. Each time thatread() 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.
✞
packagejscript;
2importjava.io.*;
public classJscript {
4 public static voidmain(String[] args)throwsIOException {
charc;
6 BufferedReader br =newBufferedReader(newInputStreamReader(
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.
✞
1packagejscript;
importjava.io.*;
3public classJscript {
63
64 CHAPTER 3. ACCESSING SYSTEM FILES
5 public static voidmain(String[] args)throwsIOException {
BufferedReader br =newBufferedReader(newInputStreamReader(
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 theallocate() method atByteBufferclass. To create
one megabyte buffer space,allocate() method is used as
✞
1ByteBuffer buff = ByteBuffer.allocate(1024 * 1024);
✆
This method is in nio.* class.
✞
1packagejscript;
3importjava.nio.*;
5public classJscript {
7 public static voidmain(String[] args) {
ByteBuffer buff = ByteBuffer.allocate(1024 * 1024);
9 System.out.println(buff);
}
11}
✆
✞
java.nio.HeapByteBuffer[pos=0 lim=1048576 cap=1048576]
✆
Theread() method is used to place read data into buffer by using as
✞
1inf.read(buff);
✆
If there is requirement to write data in ‘buff’ in out stream it must be converted
into write mode by usingflip() method.
✞
1buff.flip();
outf.write(buff);
✆
Other buffer types areShortBuffer,IntBuffer,CharBuffer,FloatBuffer,Double-
BufferandLongBuffer.
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
FileInputStreamclass is used to open a file as shown in the following syntax.
✞
FileInputStream(String <file name>)throwsFileNotFoundException
✆
Here, ‘file name’ specifies the name of the file that needed to be open. If file
does not exist to openFileNotFoundExceptionis thrown.
✞
1importjava.io.*;
public classJscript {
3 public static voidmain(String[] args)throwsIOException {
inti;
5 FileInputStream fin;
try{
7 fin =newFileInputStream("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 usingcreateNewFile() 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.
✞
packagejscript;
2
importjava.io.*;
4
public classJscript {
6
public static voidmain(String[] args)throwsIOException {
8 File f =newFile("newfile.dat");
booleansuccess;
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
✞
1fin.close();
✆
Reading File
The contents of the file are read by using objectread(). It returns the character
code read from the file.read() returns ‘-1’ when it encounters EOF.
✞
1packagejscript;
3importjava.io.*;
5public classJscript {
public static voidmain(String[] args)throwsIOException {
7 inti;
FileInputStream fin;
9 try{
fin =newFileInputStream("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
FileOutputStreamis used to create and write a file. The syntax for this class is
✞
1FileOutputStream(String <file name>)throwsFileNotFoundException
✆
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,FileNotFoundExceptionis thrown. Any
pre-existing file is destroyed or overwritten. The contents are written to the file
by usingwrite() method.
✞
1packagejscript;
3.1. INPUT OUTPUT 67
3importjava.io.*;
5public classJscript {
7 public static voidmain(String[] args)throwsIOException {
inti = 0;
9 FileOutputStream fout;
try{
11 fout =newFileOutputStream("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 methodcreateTempFile(). 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);
✆
✞
1packagejscript;
3importjava.io.*;
5public classJscript {
7 public static voidmain(String[] args)throwsIOException {
File temp = File.createTempFile("tmp",".tmp");
9 System.out.println(temp);
}
11}
✆
✞
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\tmp1895285192040487408.tmp
✆
To create temporary file anywhere you want then use following synopsis.
68 CHAPTER 3. ACCESSING SYSTEM FILES
✞
1File loc =newFile(<path>);
File <temp file name> = File.createTempFile(<name>, <ext>, loc);
✆
✞
packagejscript;
2
importjava.io.*;
4
public classJscript {
6
public static voidmain(String[] args)throwsIOException {
8 File loc =newFile("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.
✞
1packagejscript;
3importjava.io.*;
5public classJscript {
7 public static voidmain(String[] args){
File d =newFile("d:/");
9 longds = d.getTotalSpace();
System.out.println("Size of root D:/ is "+ ds +"bytes.");
11 File e =newFile("e:/");
longes = 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, TheMappedByteBufferclass maps a file directly into aByte-
Buffer. It can be operatred by usingput( ),get( ),putInt( ),getInt( ) and other
methods.put( ) andget( ) 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 READONLY, READWRITE and PRIVATE.
✞
packagejscript;
2
importjava.io.*;
4importjava.nio.*;
importjava.nio.channels.*;
6
public classJscript {
8
public static voidmain(String[] args)throwsIOException {
10 /*Open new file.*/
File file =newFile("test.txt");
12 /*Get file stream.*/
FileInputStream fis =newFileInputStream(file);
14 /*Try to get the channel of the opened file stream.*/
try(FileChannel fc = fis.getChannel()) {
16 /*Get the size of file.*/
longsize = fc.size();
18 /*Map the file data from the file channel.*/
MappedByteBuffer bb =
20 fc.map(FileChannel.MapMode.READ_ONLY, 0, size);
22 for(inti = 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 }
}
✆
MappedByteBufferhas three methods,force( ),load( ), andisLoaded( ). 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. TheisLoaded( ) method tells whether a buffer is loaded. To put
data in aMappedByteBuffer,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,RandomAccessFileclass is
used. The synopsis of it is
70 CHAPTER 3. ACCESSING SYSTEM FILES
✞
1RandomAccessFile rs=newRandomAccessFile(<file name>, <access mode>);
✆
In Java, there is no write only access mode, so read and write both mode are
used commonly. ThegetFilePointer( ) andseek( ) methods allow to query and
change the position in the file at which reads and writes occur.
✞
1packagejscript;
3importjava.io.*;
5public classJscript {
7 public static voidmain(String[] args)throwsIOException {
File file =newFile("test.txt");
9 RandomAccessFile rf =newRandomAccessFile(file,"rw");
rf.seek(10);
11 longrfp1 = rf.getFilePointer();
System.out.println("Current position of file is "+ rfp1);
13 rf.seek(0);
longrfp2 = 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.
✞
1packagejscript;
3importjava.io.*;
5public classJscript {
7 public static voidmain(String[] args)throwsIOException {
File file =newFile("test.txt");
9 RandomAccessFile rf =newRandomAccessFile(file,"rw");
rf.seek(10);
11 longrfp1 = rf.getFilePointer();
System.out.println("Current position of file is "+ rfp1);
13 rf.skipBytes(10);
longrfp2 = 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.
✞
packagejscript;
2
importjava.io.*;
4public classJscript {
public static voidmain(String[] args) {
6 /*Get the array of roots.*/
File[] roots = File.listRoots( );
8 /*Print all root names.*/
for(inti = 0; i < roots.length; i++) {
10 System.out.println(roots[i]);
}
12}
}
✆
✞
C:\
D:\
E:\
F:\
H:\
✆
File Object
Filedeals 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 ofFileis
✞
1File(<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 directoryetc. Few
of then are used in the following example for file “test.txt”.
✞
1packagejscript;
3importjava.io.File;
5public classJscript {
7 public static voidmain(String[] args) {
File f1 =newFile("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 aFilethat contains a list of other files and directories. We can
create aFileobject and checked whether its is a directory or not byisDirectory()
method. Other files can be listed by using methodlist() 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 ofStringobjects.
✞
1packagejscript;
3importjava.io.File;
5public classJscript {
7 public static voidmain(String[] args) {
File f1 =newFile("./");
3.1. INPUT OUTPUT 73
9 if(f1.isDirectory()) {
String flist[] = f1.list();
11 for(inti = 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 pathdoes not exist
yet. To create a directory for which no path exists, use themkdirs() method.
It creates both a directory and all the parents of the directory.
✞
1packagejscript;
3importjava.io.File;
5public classJscript {
7 public static voidmain(String[] args) {
File f1 =newFile("ak");
9 booleani = f1.mkdir();
System.out.println(i);
11 }
}
✆
A file or directory can be delete bydelete() method. It returns true on successful
and false on failure. Failure indicates either file or directory does notexist.
✞
packagejscript;
2
importjava.io.File;
4
public classJscript {
6
public static voidmain(String[] args) {
8 File f1 =newFile("ak");
booleani = f1.mkdir();
10 System.out.println(i);
}
74 CHAPTER 3. ACCESSING SYSTEM FILES
12}
✆
A file or directory can be rename byrenameTo() 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.
✞
packagejscript;
2
importjava.io.File;
4
public classJscript {
6
public static voidmain(String[] args) {
8 File f1 =newFile("test.txt");
File f2 =newFile("ab.txt");
10 f1.mkdir();
booleani = f1.renameTo(f2);
12 System.out.println(i);
}
14}
✆
3.2 JNI