0% found this document useful (0 votes)
40 views

Chapter 2 Building Blocks of The Language

The document discusses Java programming concepts like data types, variables, arrays, and type conversion. It defines eight primitive data types in Java and explains their sizes and ranges. It also explains variable declaration and scope, identifiers and literals, one-dimensional and multi-dimensional arrays, and type conversion including automatic and explicit casting between incompatible types.

Uploaded by

xitekol233
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Chapter 2 Building Blocks of The Language

The document discusses Java programming concepts like data types, variables, arrays, and type conversion. It defines eight primitive data types in Java and explains their sizes and ranges. It also explains variable declaration and scope, identifiers and literals, one-dimensional and multi-dimensional arrays, and type conversion including automatic and explicit casting between incompatible types.

Uploaded by

xitekol233
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

JAVA PROGRAMMING

Chapter – 2 Basic Blocks Of Language

1. Explain data type in java.


2. What is variable? Explain scope of variables.
3. What is identifier and literals?
4. Explain Type conversion and Casting.
5. What Is Array?
6. Explain length instance in array.
7. What is command line argument?
8. Explain operators in java.
9. Explain different control structures.
10. Explain garbage collection.
11. Explain wrapper classes.
12. What is String class in java.
13. Explain String operation or method in java.
14. What is StringBuffer class in java and define method of StringBuffer class.

Q-1 Explain data types in Java.

 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.

o Integers and Floating-point numbers:


Name Width(bits) Range
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038

 Ex: long l1=12345678L;


int i1=40000
short 1=1900

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.

 Ex: char ch=’m’

o Booleans:
 Boolean is used for logical values.It can have only one of two possible values, true or false.
 Ex: Boolean b1=true

Q-2 What is variable. Explain scope of variables.

 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
}
}

Q-3 What is identifiers and literals.

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”

Q-4 Explain Type conversion and casting.

 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.

o Automatic type conversion:


 Automatic type conversion is performed when two conditions are met:
 The two types are compatible.
 The destination type is larger than source type.

3
JAVA PROGRAMMING

 It is called widening conversion.


 Ex: int type is larger to hold all valid byte values.so in this case, automatic conversion is possible.
 The numeric types ,including integer and floating point types are compatible with each other.
 There are no automatic conversion from numeric type to char or Boolean.
 Char and Boolean are not compatible with each other.
 Ex: int i;
byte b=12;
i=b;

o Casting incompatible types:


 If we want to assign int value to a byte variable then it will not be performed automatically,because byte is
smaller than int.It is called narrowing conversion.we must use cast for this type of conversion.
 Syntax: (targettype) value
 target type specifies the desierd type to convert the specified value to.
 Ex: int i=12;
byte b;
b= ( byte) i;

Q-5 Explain array in Java.

 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

 There is a second syntax to combine declaration and construct:


o Syntax: type[ ] var-name = new type[size];
o Ex: int al[] = new int[3];
 Arrays can be initialized when they are declared.
o Ex: int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

 Demonstrate a one-dimensional array.


class Array
{
public static void main(String args[])
{
int days[];
days = new int[5];
days[0] = 31;
days[1] = 28;
days[2] = 31;
days[3] = 30;
days[4] = 31;
System.out.println("April has " +days[3] + " days.");
}
}

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.

 int twoD[ ][ ] = new int[4][5];


 This allocates a 4 by 5 array and assigns it to twoD. The following program numbers each element in the array
from left to right, top to bottom, and then displays these values:

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

o Non rectangular Arrays


 In Java, It is compulsory to allocate memory for the first dimension in multidimensional array.
 We can allocate memory to remaining dimension afterwards.
 In non rectangular arrays number of rows elements are fixed,but number of columns for each row are different.
 EX: int arr1[][]= new int [5] [ ]; //valid
int arr1[][]= new int [] [ 5]; //invalid

class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[4][ ];
twoD[0]= new int [ 1] ;
twoD[1]= new int [ 2] ;

twoD[2]= new int [ 3] ;


twoD[3]= new int [ 4] ;
int i, j, k = 0;
for(i=0; i<4; i++)

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

Q-6 Explain length instance of array in Java.

 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

Q-7 Explain Command line argument in java.

 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

Q-8 Explain operators in Java


 Java provides a rich operator environment. Most of its operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical.

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

A B ˜A A&B A|B A^B


0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 0 1

3. Relational Operators
 The relational operators determine the relationship that one operand has to the other.

Operator Dsecription Example(x=4,y=7)


== Equal to (x= = y) false
!= Not equal to (x ! =y) true
> Greater than (x > y)  false
< Less than (x < y)  true
>= Greater than or equal to (x > = 4) true
<= Less than or equal to (y < = 2 ) false

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

^ Logical XOR (exclusive OR)


|| Logical OR
&& logical AND
! Logica NOT

&& true false || true false ^ true false ! true false


true true false true true true true false true result false true
false false false false true false false true false

5. The Assignment Operator


 The assignment operator is the single equal sign, =.
var = expression;

 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

6. The ? Operator or ternary operator.


 Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements.
The ? has this general form:
expression1 ? expression2 : expression3
 Here, expression1 can be any condition that evaluates(check) to a boolean value.
 If expression1 is true, then expression2 is evaluated or executed.
 If expression1 is false, then expression3 is evaluated or executed.
 Both expression2 and expression3 are required to return the same type, which can’t be void.

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”);

7. Auto Increment and Auto Decrement Operators


 These operators modify the values of an expression by adding and subsatracting 1.

X=5 Dsecription value of X value of Y

10
JAVA PROGRAMMING

5 Y=++X 6 6
5 Y= X++ 5 6
5 Y= --x 4 4
5 Y= X-- 5 4

Q-9 Explain Control statement in java.

1. Conditional Flow control


 simple if
 If ….else
 Nested if …else
 Ladder if .. else
 Switch
2. Loop control
 While loop
 Do while loop
 For loop
 Enhanced for loop
3. Exit loop or jump statement
 Break
 Continue
 return

1. Conditional Flow control

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");
}
}

o The if-else-if Ladder


 A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
Syntax: if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

 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");
}
}
}

o Nested switch Statements


 You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since
a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and
those in the outer switch.
switch(count)
{
case 1:
switch(target)
{
case 0:
System.out.println("target is zero");
break;
case 1:
System.out.println("target is one");
break;
}
break;
case 2:
-----

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

Ex: class fact


{
public static void main(String args[])
{
int no;
no=Integer.parseInt(args[0]);
int fact = 1;
do
{
fact=fact*no;
no--;
} while(no>0);
System.out.println(fact);
}
}

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.

Ex: class ForDemo


{
public static void main(String args[])
{
for(int num = 1; num < 11; num = num + 1)
System.out.print(num + " ");
}

17
JAVA PROGRAMMING

o Enhanced for loop


 Syntax: for(data type variable : arrayname)
{
// body
}

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.

3. Exit control or Jump statement

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

o Using break as a Form of Goto


 Java does not have a goto statement. The general form of the labeled break statement is shown here: break
label; Here, label is the name of a label that identifies a block of code. When this form of break executes,
control is transferred out of the named block of code. The labeled block of code must enclose the break
statement, but it does not need to be the immediately enclosing block. This means that you can use a labeled
break statement to exit from a set of nested blocks. But you cannot use break to transfer control to a block of
code that does not enclose the break statement. To name a block, put a label at the start of it.
 A label is any valid Java identifier followed by a colon. Once you have labeled a block, you can then use this
label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block.
The break statement causes execution to jump forward, past the end of the block labeled second, skipping the
two println( ) statements.

Ex: class Break


{
public static void main(String args[])
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}

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.

Ex: class Continue


{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}

Ex: class ContinueLabel


{
public static void main(String args[])
{
outer: for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(j > i)
{
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop
counting i.

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.

Ex: class Return


{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

Q-10 Explain wrapper class in java

 Java use primitive data type such as int ,float,double.


 But many times when you will need an object representation of primitive types for ex: you can not use method
with primitive data types.
 In java there is a wrapper class for every primitive datatype.
 The wrapper class encapsulate primitive type within an object .Ex; wrapper class for int is Integer
For float is Float so on.
 These classes offer method that allow you to use primitive types into java object.
 These are known as wrapper class because they “wrap” the primitive data type into object of that class.
 The wrapper classes are part of the java.lang package which is imported by default into all java programs.
 We wrap primitive values in an object so that primitive can do activities reserved for the objects.
 Wrapper classes provide many function for primitives like converting primitives to string objects.
 Ex: int x=23; //x is variable that store 23 value.
Integer y=new Integer(22); // y is integer object.

Primitive Wrapper class


boolean Boolean
byte Byte
char Character
int Integer
float Float

21
JAVA PROGRAMMING

double Double
long Long
short short

o Examples of wrapper class:

1. Character : Wrapper class


 Character is a wrapper around a char.
 Ex: Character(char ch) here ch specifies the character that will be wrapped by the Character object being
created.
 To obtain the char value contained in a Character object,call charvalue(),
 char charValue()

2. Boolean: Wrapper class


 Boolean is a wrapper around a Boolean value.
 Ex: Character(char ch) here ch specifies the character that will be wrapped by the Character object being
created.
 To obtain the Boolean from Boolean object use booleanValue()
 Boolean booleanValue()
 EX:
o Boolean b1=new Boolean(“true”);
o boolean b= b1.booleanValue();
 So b=true it returns Boolean object as Boolean value.

3. Numeric Type : Wrapper class


 It represent numeric value.
 These are Byte,Short,Integer,Long,Float,Double.
 Number declares methods that return the value of an object in each of the different number formats.
o byte byteValue()
o double doubleValue()
o float floatValue()
o int intValue()
o long longValue()

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);
}
}

Q-11 Explain garbage collection in java.

 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 .

Q-12 What is String class in java.

 Generally string is a sequence of characters enclosed within double quotes ex. “java” ,”123”

23
JAVA PROGRAMMING

 But in java string is an object.String class is used to create String object.


 String objects are stored in a special memory area known as string constant pool inside the Heap memory.
 In java strings are immutable it means unmodifiable or unchangeable.
 Once string object is created its data or state can not be changed but a new string object is created.

o Creation:
1.Using string literal
2.Using new keyword

1.Using string literal


 String s=”hi”;
 Each time you create a string literal ,the JVM checks the string constant pool in memory first.
 If the string already exists in memory pool, a reference to thepooled instance returns.
 If the string does not exist in the pool a new string object is created and it is placed in the pool.

2.Using new keyword.


 String s=new String(”hi”);
 JVM will create a new String object in heap memory and literal “hi” will be placed in the string constant pool.
 Variable s will refer to the object in heap.

Q-13 Explain String operation or method in java.

1. String length (length)


2. String concate (concat)
3. Changing case (toUpperCase ,toLowerCase)
4. Character extraction (substring , charAt , getChars ,startsWith , endsWith)
5. String comparision (= = , equals, equalsIgnoreCase ,compareTo)

1. String length (length)

 It return length of String object.it means total number of character in String.

Syntax: stringname.length()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;

24
JAVA PROGRAMMING

Systemout.println(“length of s1=”+ s1.length());


}
}
Output: length of s1= 5

2. String concate (concat)

 concate it means merge two string into third string.


 Using + operator
 using concat function
Syntax: string1 + string2 stringname.length()
string1.concat(string2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;
String s2= “hi” ;
String s3= s1.concat(s2);
Systemout.println(“concat string s3=”+s3);
}
}
Output: concat string s3 = hellohi

3. Changing case (toUpperCase ,toLowerCase)

 toUpperCase method is used to change case of string from lower to uppercase


 toLowerCase method is used to change case of string from luppercase to lowercase.

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

4. Character extraction (substring , charAt , getChars ,startsWith , endsWith)

o substring
 A part of string is called substring. it means substring is a subset of another String.

Syntax: stringname.substring( int startindex) or stringname.substring( int startindex , endindex)


 startindex: specify the index at which the substring will begin.
 endindex : specify the stopping point.
 string return contains all the characters from the beginning index up to ,but not including the ending index.

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()

 To extract a single character from String .


 It returns the character at a specific index of a string

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

public static void main(String args[])


{
String s1=” Hello hi how r u”;
Systemout.println(“single character is =”+s1.charAt(1));
Systemout.println(“single character is =”+s1.charAt(11));
}
}
Output: single character is =e
single character is =w

o getChars()

 To extract more than one character at a time from String .

Syntax: stringname.getChars( start, end , target[],targetstart)


start : specifies the index of beginning of the substring.
end : specifies the index of ending of substring.
target[] : specifies array that will receive the character.
targetstart : specifies at which index the substring will be copied.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
char buf[ ] =new char [4];
s1.getChars(7, 12, buf , 0);
Systemout.println(“substring is =”+ buf );
}
}
Output: substring is = hi how

o startsWith() and endsWith()

 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

5. String comparision ( equals, equalsIgnoreCase ,= = ,compareTo)

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.

 Syntax: stringname1 = = stringname2

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

Systemout.println(“s1 = = s2 ); // both s1 and s2 refer same instance.


Systemout.println(“s1 = = s3) ); //both s1 and s3 refer different instance.
}
}
Output: true
false

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

Q-14 What is StringBuffer class in java.

 StringBuffer is another class to create String object.


 Using String class we can create immutable(nomodification) string.
 So StringBuffer class is used to create mutable (modified) string.
 StringBuffer class is same as String class except it is mutable(modified).

o StringBuffer class constructors:

30
JAVA PROGRAMMING

1.StringBuffer() :- Creates empty string buffer with initial capacity of 16.


2.StringBuffer(String str) :- Creates String bufferwith specified string.
3.StringBuffer(int capacity) :- creates empty string buffer with the specified capacity as length.

Method of StringBuffer class

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()

 It return length of String object.it means total number of character in String.

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());
}
}

Output: capacity of s1= 16


capacity of s1=25
capacity of 20

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()

 The insert () method insert(add) one string into another string.

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

5. deleteCharAt() & delete()

 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)

Ex: s1.deleteCharAt(2):delete a character which index is 2.


s1.delete(4,7) :delete charactes from 4th index to 6th index. character which has 7th index is not
deleted.

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

Output: s1 string= I is java

GTU QUESTION:

1. Distinguish between break and continue statements in Java.


2. Explain any one of Java Loop Statements with program example.
3. What is Wrapper class? Explain use of any one wrapper class.
4. Explain Type Conversion and Casting.
5. List methods of String class. Explain how to use String class .
6. List methods of String Buffer class. Explain how to use String buffer class
7. Write a Java program to read two strings from command line argument and check the equality of two string using
string function.

35

You might also like