Vidya Murugendrappa Assistant Professor
Vidya Murugendrappa Assistant Professor
Assistant Professor
Example:
Switch(expression)
{
case value-1:
statements which will be executed if the value obtained
by evaluating the expression is value-1
break;
case value-2:
statements which will be executed if the value obtained
by evaluating the expression is value-2
break;
...
...
case value-n:
statements which will be executed if the value obtained
by evaluating the expression is value-n
break;
default :
statements which will be executed if the value obtained by evaluating the expression
is not matching with any of the values in value-1, value-2,...,value-n
break;
}
The expression is an integer type expression or character type expression. “value-1,
value-2, etc are constants or expressions which can be evaluated to integer constants.
In switch expression, first the expression will be evaluated. The value we get by
evaluating this expression will be first compared with value-1.
If these values are matching, the statements that follow that particular case will be
executed. After these statements, it will execute the “break;” statement and as a result
of this, control will be moved out of switch statement and the statements after the
switch block will be executed.
If these values are not matching, the value we get by evaluating the expression will be
compared with value-2 and it go on like this.
3. Explain any three iteration statements of java with an example [10 marks]
WHILE STATEMENT
a. The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while it’s controlling expression is true.
b. General form of while statement:
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.
Here is a while loop that counts down from 10, printing exactly ten lines of “tick”:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
When you run this program, it will “tick” ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
A.2.2. DO-WHILE STATEMENT
a. 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
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.
Example:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
4. List out and explain jump statements of java with an example [10 marks]
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third,
it can be used as a “civilized” form of goto. The last two uses are explained here.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop. 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:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
ii. Using continue
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.
In a for loop, control goes first to the iteration portion of the for statement and
then to the conditional expression. For all three loops, any intermediate code is
bypassed.
Here is an example program that uses continue to cause two numbers to be
printed on
each line:
// Demonstrate continue.
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("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues
without printing
a newline. Here is the output from this program:
01
23
45
67
89
iii. 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.
As such, it is categorized as a jump statement. At any time in a method the return
statement can be used to cause execution to branch 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. Here, return causes
execution to return to the Java run-time system, since it is the run-time system that
calls main( ).
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
In this example, we have created a student class that has two data members id and
name. We are creating the object of the Student class by new keyword and printing
the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Test it Now
Output:0 null
A class provides the blueprints for objects. So basically an object is created from a class.
In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Example of creating an object is given below:
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Java constructors are special methods that are called when an object is instantiated. In
other words, when you use the new keyword. The constructor initializes the newly
created object.
Types of java constructors
Default constructor (no-arg constructor)
Parameterized constructor
Java Default Constructor:
A constructor that has no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Java parameterized constructor:
A constructor that has parameters is known as parameterized constructor. Parameterized
constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
class Student4{
int id;
String name;
}
}
Test it Now
Output:
111 Karan
222 Aryan
8. Illustrate with an example how to declare variable, method and class as final in java [10
marks]
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
Java final variable:If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Test it Now
Output:Compile Time Error
Java final method:
If you make any method as final, you cannot create another method with same name.
Example of final method:
class Bike{
final void run(){System.out.println("running");}
}
9. Compare and contrast different access specifier used in java with an example [10 marks]
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
Variables that are declared private can be accessed outside the class if public getter
methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and
hide data from the outside world.
Example:
The following class uses private access control:
So to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String),
which sets its value.
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be accessed from
any other class. Therefore fields, methods, blocks declared inside a public class
can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then
the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.
Example:
The following function uses public access control:
Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.
Example:
The following parent class uses protected access control, to allow its child class
override openSpeaker() method:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be
accessible from any other class other than AudioPlayer. If we define it as public,
then it would become accessible to all the outside world. But our intension is to
expose this method to its subclass only, thats why we used protected modifier.
10. Illustrate general form of finalize method with an example [5 marks]
Finalize method:
o Finalize method in java is a special method much like main method in java.
finalize() is called before Garbage collector reclaim the Object, its last chance for
any object to perform cleanup activity i.e. releasing any system resources held,
closing connection if open etc.
o The intent is for finalize() to release system resources such as open files or open
sockets before getting collected.
o Syntax of finalize() method:
protected void finalize()
{
//finalize code here;
}
Example for finalize method
Book(boolean checkOut)
{
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
{
if (checkedOut)
novel.checkIn();
// Proper cleanup:
new Book(true);
// Drop the reference, forget to clean up:
11. Explain how to use super keyword to call superclass constructor in java with an example.
• The super keyword in java is a reference variable that is used to refer immediate
parent class object.
• Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
• Usage of java super Keyword
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.
The super keyword can also be used to invoke the parent class constructor as given
below:
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
Test it now
Output: Vehicle is created
Bike is created
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Test it Now
Output:111 Karan ITS
222 Aryan ITS
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
class Student4{
int id;
String name;