Chapter 2 Building Blocks of The Language
Chapter 2 Building Blocks of The Language
Java defines eight simple or primitive types of data: byte, short, int, long, char, float, double, and boolean.
These can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for integer valued signed numbers.
Floating-point numbers: This group includes float and double, which represent numbers with fractional
precision.
Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false values.
1
JAVA PROGRAMMING
byte b1=2
double d1=88.88
float f1=3.2f
o Characters:
The data type used to store characters in char.char in java is not same as char in c or c++.
Java use Unicode to represent characters.
Unicode define fully international character set that represent all of the characters found in all human
languages.For this purpose in java char is a 16 bit type. range of char is 0 to 65,536.there are no negative char.
o Booleans:
Boolean is used for logical values.It can have only one of two possible values, true or false.
Ex: Boolean b1=true
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an
identifier and datatype. All variables have a scope, which defines their visibility, and a lifetime.
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value
Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.specified type, use a comma-separated list.
o Scope of variables
Most of the computer languages define two general categories of scopes: global and local.
The variables declared within the method of a class are local variable.
Variables in method arguments are also local variables.
Variables declared within the class can be used by all the methods of that class globally.
Example:
class c1
2
JAVA PROGRAMMING
{
public static void main(String args[])
{
int x=10; //known to all code within main
{ //start new scope
int y=20; //known only to this block
x=y*2; //no error
}
y=100 //error ,y is not known
System.out.println(x); // no error ,x is known
}
}
o Identifiers:
Identifiers are used for class names,method names, and variable names.
Identifier may be any name of uppercase,lowercase letters,numbers,or the underscore and dollar-sign.
They must not begin with number.
VALUE and value is different identifiers.
Ex: Avg,a_b,a4,$t
o Literals:
A constant value is called literal
literal can be used in anywhere.
Ex: 100 , 98.7 , ‘x’ , “hello”
When we assign a value of one type to a variable of another type is called type conversion.
For ex. when we assign value of int variable to float variable or float to double.
If two types are compatible then java will perform the conversion automatically and if two types are not
compatible then java will not perform the conversion automatically .
For that we must use cast,which performs explicit conversion between incompatible types.
3
JAVA PROGRAMMING
An array is a group of variables they have same data type and that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in an array is accessed by
its index.
o One dimensional Array
o Multi dimensional Array
o Non rectangular Array
o One-Dimensional Arrays
To create an array, you first must create an array variable of the desired type.
o Declare: type arrayname[]; or type [ ] arrayname;
o Ex: int a1[]; or int [] a1;
Now you must allocate memory using new keyword.
o construct: arrayname= new type [ size];
o Ex: a1= new int [ 10];
Now assign value into array.
o Assign : arrayname[size] = value;
o Ex: a1 [10] =20;
Here, type declares the base type of the array. Thus, the base type for the array determines what type of data
the array will hold.
4
JAVA PROGRAMMING
o Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array variable,
specify each additional index using another set of square brackets. For example, the following declares a two-
dimensional array variable called twoD.
class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[3][3];
int i, j, k = 0;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
5
JAVA PROGRAMMING
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
}
output:
0 1 2
34 5
6 7 8
class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[4][ ];
twoD[0]= new int [ 1] ;
twoD[1]= new int [ 2] ;
6
JAVA PROGRAMMING
{
for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
{
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
}
output:
0
1 2
34 5
The size of array that is the number of elements that an array can hold is found in its length instance variable.
All arrays have this variable,and it will always hold the size of array.
Ex:
class length
{
public static void main(String args[])
{
int a1[]={1,2,3};
int a2[]= new int[5];
System.out.println(“size of array a1=” +a1.length)
System.out.println(“size of array a2=” +a2.length)
}
}
o/p:
3
5
7
JAVA PROGRAMMING
You can pass information into a program when you run it using command line argument.
In public static void main(String args[]) In this String args[] refers the command line arguments having the
type string. args is a string array.it stores first argument in args[0],second in args[1] and so on…
Ex: cmd>java prog1 hi hello
cmd>java prog1 2 3
class cmd
{
public static void main(String args[])
{
for(i=0;i<args.length;i++)
System.out.println(“argument=”+args[i])
}
}
o/p: cmd>java prog1 hi hello
hi
hello
1. Arithmetic Operators
Arithmetic operators are used in mathematical expressions. The following table lists the arithmetic operators:
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
8
JAVA PROGRAMMING
2. Bitwise Operators
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
These operators act upon the individual bits of their operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
3. Relational Operators
The relational operators determine the relationship that one operand has to the other.
4. Logical Operators
The logical operators shown here operate only on boolean operands. All of the binary logical operators
combine two boolean values to form a resultant boolean value.
Operator Result
9
JAVA PROGRAMMING
Here, the type of var must be compatible with the type of expression. The assignment operator allows you to
create a chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
if a > b ? a = 0 : a = 1;
When Java evaluates this assignment expression, it first looks at the expression to the left of the question mark.
If a > b is true then a=0 will be evaluated else a=1 will be evaluated.
Examples:
if a>0 ? System.out.println(“a is positive”) : System.out.println(“a is negative”);
10
JAVA PROGRAMMING
5 Y=++X 6 6
5 Y= X++ 5 6
5 Y= --x 4 4
5 Y= X-- 5 4
o simple if
The if statement is Java’s conditional branch statement. It can be used to route program execution through two
different paths.
Syntax: if (condition)
statement1;
Here, each statement may be a single statement or a compound statement enclosed in curly braces. The
condition is any expression that returns a boolean value. If the condition is true, then statement1 is executed.
Otherwise, statement1 is not executed.
Ex: int a, b;
if(a < b)
System.out.println(“value of a”+a );
o if .. else
11
JAVA PROGRAMMING
The if statement is Java’s conditional branch statement. It can be used to route program execution through two
different paths.
Syntax: if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly braces. The
condition is any expression that returns a boolean value. The else clause is optional. If the condition is true, then
statement1 is executed. Otherwise, statement2 (if it exists) is executed.
Ex: int a, b;
if(a < b)
a = 0;
else
b = 0;
o Nested IF
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming.
Syntax: if (condition)
{
if(condition)
statement1;
else
statement2;
}
else
statement3;
Ex:
class IfElse
{
public static void main(String args[])
{
int i = Integer.parseInt(args[0]);
if(i > 0)
{
if(i > 3)
System.out.println("i > 0 and i > 3");
else
System.out.println("i > 0 and i <= 3");
}
12
JAVA PROGRAMMING
else
System.out.println("i <= 0");
}
}
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true,
the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed. If there is no final else and all other conditions are false,
then no action will take place.
Ex:
class IfElseLadder
{
public static void main(String args[])
{
int i = Integer.valueOf(args[0]).intValue();
if(i < 0)
System.out.print("Negative number");
else if(i == 0)
System.out.print("Zero");
else if(i == 1)
System.out.print("One");
else if(i == 2)
System.out.print("Two");
else if(i == 3)
System.out.print("Three");
else
System.out.print("Greater than three");
}
13
JAVA PROGRAMMING
o Switch statement
The switch statement is Java’s multiway branch statement. It provides an easy way to execute different parts of
your code based on the value of an expression. As such, it often provides a better alternative than a large series
of if-else-if statements.
Syntax: switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case statements must
be of a type compatible with the expression. Each case value must be a unique literal means it must be a
constant, not a variable. Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the literal values in
the case statements. If a match is found, the code sequence following that case statement is executed. If none of
the constants matches the value of the expression, then the default statement is executed. However, the default
statement is optional. If no case matches and no default is present, then no further action is taken. The break
statement is used inside the switch to terminate a statement sequence.
Ex:
class SwitchDemo
{
public static void main(String args[])
{
int i = Integer.parse Int(args[0]);
switch(i)
{
case 1:
14
JAVA PROGRAMMING
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
case 4:
System.out.println("four");
break;
default:
System.out.println("Unrecognized Number");
}
}
}
2. Loop control
15
JAVA PROGRAMMING
Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops.
As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is
met.
o while
It repeats a statement or block while its controlling expression is true. Here is its general form:
Syntax: while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional
expression is true. When condition becomes false, control passes to the next line of code immediately
following the loop. The curly braces are unnecessary if only a single statement is being repeated.
Ex: class WhileDemo
{
public static void main(String args[])
{
int i = Integer.parseInt(args[0]);
while(i > 0)
{
System.out.print(i + " ");
i--;
}
}
}
o do-while
Sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is
false to begin with. The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is
Syntax: do
{
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional
expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s
loops, condition must be a Boolean expression.
16
JAVA PROGRAMMING
o for
Syntax: for(initialization; condition; iteration)
{
// body
}
If only one statement is being repeated, there is no need for the curly braces. The for loop operates as follows.
When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that
sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to
understandthat the initialization expression is only executed once
condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a
target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates
iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop
control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of
the loop, and then executing the iteration expression with each pass. This process repeats until the controlling
expression is false.
17
JAVA PROGRAMMING
Ex: class f1
{
public static void main(String args[])
{
int a[]={10,20,30};
int s=0;
for(int x:a)
s=x+s;
System.out.print(s);
}
}
In this ,variable is store value of array element one by one during each iteration.
Ex: in first iteration x=10,in second iteration x=20 and thirs iteration x=30.
So loop is executed three times in this example.
o Using break
In Java, the break statement has three uses.
It terminates a statement sequence in a switch statement.
It can be used to exit a loop.
It can be used as a form of goto.
When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the
next statement following the loop. Here is a simple example:
Ex: class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
if(i == 3) break; // terminate loop if i is 10
System.out.println("i: " + i);
18
JAVA PROGRAMMING
}
System.out.println("Loop complete.");
}
}
output: 0 1 2 4
19
JAVA PROGRAMMING
o Using continue
you might want to continue running the loop, but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action. In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop.
20
JAVA PROGRAMMING
o Return
The return statement is used to explicitly return from a method. That is, it causes program control to transfer
back to the caller of the method. Thus, the return statement immediately terminates the method in which it is
executed. The following example illustrates this point.
21
JAVA PROGRAMMING
double Double
long Long
short short
22
JAVA PROGRAMMING
o short shortValue()
For ex. intValue() returns the value of an object as a int.
All of the numeric type wrappers define constructors that allow an object to be constructed from a given value .
Ex of numeric type wrapper class:
class wrapdemo
{
public static void main(String args[])
{
Integer iob=new Integer (100);
int i=iob.intValue();
System.out.println(i + “ “ + iob);
}
}
Java Virtual Machine allocates objects on the heap dynamically using new operator.
Other language put the burden on the programmer to free these objects using delete() or free() function when
they are no longer needed.
Java language does not provide this type of function because java runtime environment automatically reclaims
the memory for objects that are no longer associated with a reference variable.
This memory reclamation process is known as garbage collection.
Garbage collection involves:
1.keeping a count of all references to each object
2.periodically reclaiming memory for all objects with a reference count to zero.
Ex:
void a method()
{
Sum d1=new Sum():
}
new operation creates an instances of Sum,its memory address is store in d1and its reference count is
incremented to 1.when this method return or finishes reference variable d1 goes out of scope and reference
count is decrement to 0.At this point Sum instance is reclaimed by garbage collection.
Garbage collection is automatically runs periodically.you can manually invoke the garbage collection at any
time using java.lang.System.gc() method .
Generally string is a sequence of characters enclosed within double quotes ex. “java” ,”123”
23
JAVA PROGRAMMING
o Creation:
1.Using string literal
2.Using new keyword
Syntax: stringname.length()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;
24
JAVA PROGRAMMING
Syntax: stringname.toUpperCase()
stringname.toLowerCase()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello”;
Systemout.println(“uppercase=”+s1.toUpperCase());
Systemout.println(“lowercase=”+s1.toLowerCase());
25
JAVA PROGRAMMING
Systemout.println(“original string=”+s1);
}
}
Output: uppercase = HELLO
lowercase =hello
original string = Hello
o substring
A part of string is called substring. it means substring is a subset of another String.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“substring is =”+s1.substring(6));
Systemout.println(“substring is =”+s1.substring(0,7));
}
}
Output: substring is = hi how r u
substring is = Hello h
o charAt()
Syntax: stringname.charAt(index)
index:it is index of character that you want to display. index value must be integer.
Ex:
class c1
{
26
JAVA PROGRAMMING
o getChars()
startsWith(string) : this method determines whether a given string begins with a specified string.If string
begin with specified string then true is returned otherwise false is returned.
endsWith(string) : this method determines whether a given string end with a specified string. If string
end with specified string then true is returned otherwise false is returned.
Syntax: stringname.startsWith(string)
27
JAVA PROGRAMMING
stringname.endsWith(string)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“s1.startsWith(“He”) );
Systemout.println(“s1.startsWith(“ab”) );
Systemout.println(“s1.endsWith(“u”) );
Systemout.println(“s1.startsWith(“r”) );
}
}
Output: true
false
true
false
o equals
This method compare content of string .if content are same then it returns true otherwise it returns false.
Syntax: stringname1.equals(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
Systemout.println(“s1.equals(s2) );
Systemout.println(“s1.equals(s3) );
Systemout.println(“s1.equals(s4) );
28
JAVA PROGRAMMING
}
}
Output: true
true
false
o equalsIgnorCase
This method compare content of string but it will ignore case . so HELLO and hello is same.
Syntax: stringname1.equalsIgnorCase(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” HELLO “;
String s2=”hello”;
Systemout.println(“s1.equalsIgnorCase(s2) );
}
}
Output: true
o ==
The = = operator compares two object references to see whether they refer to the same instance.If two object
refer same instance the it will return true otherwise it returns false.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
29
JAVA PROGRAMMING
o compareTo
ThecompareTo methos compare values of two string and it returns integer value .
If two strings are same it will return zero
If string1 is greater than string2 then it will return greater than zero.
If string1 is less than string2 then it will return less than zero.
Syntax: stringname1.compareTo(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3=”hi”;
Systemout.println(s1.compareTo(s2);
Systemout.println (s1.compareTo(s3);
}
}
Output: 0
1
30
JAVA PROGRAMMING
1. length()
2. capacity()
3. append()
4. insert()
5. delete() & deleteCharAt()
6. reverse()
7. replace()
8. charAt()
9. substring()
10. equals()
11. indexof()
1. length()
Syntax: stringname.length()
Ex: class c1
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2= new StringBuffer(“hello”);
Systemout.println(“length of s1=”+ s1.length());
System.out.println(“length of s2=”+ s2.length());
}
}
Output: length of s1= 0
length of s2=5
2. capacity()
It return allocated capacity of String object.It means how many character can be stored by string.
31
JAVA PROGRAMMING
Syntax: stringname.capacity()
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer("hello");
StringBuffer s3=new StringBuffer(20);
System.out.println(“capacity of s1=”+s1.capacity());
System.out.println((“capacity of s2=”+s2.capacity());
System.out.println((“capacity of s3=”+s3.capacity());
}
}
3. append()
The append() method concat string that is define in(“”) to end of string.
Syntax: stringname.append(string)
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer("hello");
s1.append("how r u");
System.out.println(“s1 string=”+s1);
s2.append("hi");
System.out.println(“s2 string=”+s2);
}
}
Output: s1 string= how r u
s2 string = hellohi
32
JAVA PROGRAMMING
4. insert()
Syntax: stringname.insert(index,string)
Ex: s1.insert(2,”ab”) : insert “ab” into string s1 at 2nd index.
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I java");
System.out.println(s1.insert(2,"like"));
System.out.println(“s1 string=”+s1);
}
}
Output: s1 string= I like java
The deleteCharAt () method delete the character that is specified in the index.
The delete() method deletes sequence of characters from specified start index to end index
Syntax: stringname.deleteChatAt(index)
stringname.delete(startindex,endindex)
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.delete(4,7);
System.out.println(“s1 string=”+s1);
s1.deleteCharAt(0);
System.out.println(“string s1=”+s1);
33
JAVA PROGRAMMING
}
}
Output: s1 string= I lijava
s1 string= lijava
6. reverse()
The reverse () method reverse the character that is specified in the string.
Syntax: stringname.reverse()
Ex: class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.reverse();
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= avaj ekil I
7. replace()
The replace () method replace(change) the one set of characters with another set of characters.
Syntax: stringname.replace(startindex,endindex,string)
Ex: s1.replace(2,6,”is”) :change charactes from 2nd index to 5th index by “is” . character which has 6th
index is not changed
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.replace(2,6,”is”);
System.out.println(“string s1=”+s1);
}
}
34
JAVA PROGRAMMING
GTU QUESTION:
35