0% found this document useful (0 votes)
65 views22 pages

Vidya Murugendrappa Assistant Professor

The document discusses various selection and iteration statements in Java with examples: 1. It explains if, if-else-if, and switch statements with examples of using them to print different outputs based on conditions. 2. It describes while, do-while, and for loops for repeating blocks of code. The while loop checks the condition first, do-while always executes the body at least once, and for allows initialization, condition checking, and incrementing in one place. 3. Examples are provided to count from 10 to 1 using these different loop types to demonstrate their functionality.

Uploaded by

yashwanth kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views22 pages

Vidya Murugendrappa Assistant Professor

The document discusses various selection and iteration statements in Java with examples: 1. It explains if, if-else-if, and switch statements with examples of using them to print different outputs based on conditions. 2. It describes while, do-while, and for loops for repeating blocks of code. The while loop checks the condition first, do-while always executes the body at least once, and for allows initialization, condition checking, and incrementing in one place. 3. Examples are provided to count from 10 to 1 using these different loop types to demonstrate their functionality.

Uploaded by

yashwanth kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Vidya Murugendrappa

Assistant Professor

Study Guide Questions on MODULE 4


1. Explain if statement of java with an example [5 marks]
General form of simple if statement:
If(condition)
{
Statements which will be executed if the condition is true
}
Here if the condition is true, the code which is written inside the curly brackets {} of the
if block will be executed.

Example:

public class SimpleIfStatementDemo1


{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 10
int test=10;

//Checking if "test" is greater than 5


if(test>5)
{
//This block will be executed only if "test" is greater than 5
System.out.println("Success");
}
//The if block ends.
System.out.println("Executed successfully");
}
}

Advanced Computer Programming UNIT 4 Page 1


Vidya Murugendrappa
Assistant Professor

2. Explain any selection statements of java with an example [10 marks]


a. A common programming construct that is based upon a sequence of nested ifs
is the if-else-if ladder. It looks like this:
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. The final else acts as a default condition; that is, if all
other conditional tests fail, then the then no action will take place.
Example:
Here is a program that uses an if-else-if ladder to determine which season a particular
month is in.
// Demonstrate if-else-if statements.
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";

Advanced Computer Programming UNIT 4 Page 2


Vidya Murugendrappa
Assistant Professor

else if(month == 9 || month == 10 || month == 11)


season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
2. Generalize switch statement of java with an example [10 marks]
a. The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression.
b. General form of a switch statement:

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.

Advanced Computer Programming UNIT 4 Page 3


Vidya Murugendrappa
Assistant Professor

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

 The “default” is an optional parameter. If the value we get by evaluating the


expression is not matching with any of the values in value-1, value-2…value-n, the
statements in the default section will be executed. Once the break statement is
executed, control goes outside the switch block and the statements after the switch
block will be executed.
c. Example:

public class SwitchStatementDemo1


{
public static void main(String args[])
{
int choice = 2;
switch (choice)
{
case 1:
System. out .println( "Bank Menu" );
break ;
case 2:
System. out .println( "Loan Menu" );
break ;
case 3:
System. out .println( "Credit Card Menu" );
break ;
default :
System. out .println( "No Match Found" );
break ;
}
}
}

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:

Advanced Computer Programming UNIT 4 Page 4


Vidya Murugendrappa
Assistant Professor

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:

Advanced Computer Programming UNIT 4 Page 5


Vidya Murugendrappa
Assistant Professor

// Demonstrate the do-while loop.


class Do While {
public static void main(String args[]) {
int n = 10;
do {
System.out.println ("tick " + n);
n--;
} while(n > 0);
}
}

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.3 FOR LOOP STATEMENT


a. General statement for statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces.
b. 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 understand that
the initialization expression is only executed once. Next, 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. Next, the 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.
Here is a version of the “tick” program that uses a for loop:

Advanced Computer Programming UNIT 4 Page 6


Vidya Murugendrappa
Assistant Professor

// Demonstrate the for loop.


class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}

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.

Advanced Computer Programming UNIT 4 Page 7


Vidya Murugendrappa
Assistant Professor

 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

Advanced Computer Programming UNIT 4 Page 8


Vidya Murugendrappa
Assistant Professor

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;

System.out.println("Before the return.");


if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
The output from this program is shown here:
Before the return.

5. Summarize general form of a class in java with an example [6 marks]


a. Class:
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.
b. A class in java can contain:
 data member
 method
 constructor
 block
 class and interface
c. Syntax to declare a class:
class <class_name>{
data member;
method;
}
d. Simple Example of Object and Class:
Example 1:

Advanced Computer Programming UNIT 4 Page 9


Vidya Murugendrappa
Assistant Professor

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

6. Discuss declaration of objects with and example [5 marks]


 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

Advanced Computer Programming UNIT 4 Page 10


Vidya Murugendrappa
Assistant Professor

Puppy myPuppy = new Puppy( "tommy" );


}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy

 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

7. Define constructor. Different types of Constructor. Explain how to initialize default


constructor, non-parameterized and parameterized constructor with an example[15
marks]

Advanced Computer Programming UNIT 4 Page 11


Vidya Murugendrappa
Assistant Professor

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

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();

Advanced Computer Programming UNIT 4 Page 12


Vidya Murugendrappa
Assistant Professor

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

Advanced Computer Programming UNIT 4 Page 13


Vidya Murugendrappa
Assistant Professor

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

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error


 Java final class:
 If you make any class as final, you cannot extend it.
 Example of final class:

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda();
honda.run();
}
}
Test it Now

Output: Compile Time Error

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:

 Visible to the package. the default. No modifiers are needed.

 Visible to the class only (private).

Advanced Computer Programming UNIT 4 Page 14


Vidya Murugendrappa
Assistant Professor

 Visible to the world (public).

 Visible to the package and all subclasses (protected).


 Default Access Modifier - No keyword:
 Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.
 A variable or method declared without any access control modifier is available to
any other class in the same package. The fields in an interface are implicitly public
static final and the methods in an interface are by default public.
 Example:

 Private Access Modifier - private:


 Methods, Variables and Constructors that are declared private can only be accessed
within the declared class itself.

 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:

public class Logger {


private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}
 Here, the format variable of the Logger class is private, so there's no way for other
classes to retrieve or set its value directly.

 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:

Advanced Computer Programming UNIT 4 Page 15


Vidya Murugendrappa
Assistant Professor

 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:

public static void main(String[] arguments) {


// ...
}
The main() method of an application has to be public. Otherwise, it could not be
called by a Java interpreter (such as java) to run the class.
 Protected Access Modifier - protected:
 Variables, methods and constructors which are declared protected in a superclass
can be accessed only by the subclasses in other package or any class within the
package of the protected members' class.
 The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in a interface cannot
be declared protected.

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

Advanced Computer Programming UNIT 4 Page 16


Vidya Murugendrappa
Assistant Professor

}
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

// Using finalize() to detect an object that hasn't been properly cleaned up


class Book
{
boolean checkedOut = false;

Book(boolean checkOut)

{
checkedOut = checkOut;
}
void checkIn() {

Advanced Computer Programming UNIT 4 Page 17


Vidya Murugendrappa
Assistant Professor

checkedOut = false;
}

public void finalize()

{
if (checkedOut)

System.out.println("Error: checked out");


}
}
public class TerminationCondition
{
public static void main(String[] args)
{
Book novel = new Book(true);

novel.checkIn();
// Proper cleanup:

new Book(true);
// Drop the reference, forget to clean up:

System.gc(); // Force garbage collection & finalization:


}
}

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:

Advanced Computer Programming UNIT 4 Page 18


Vidya Murugendrappa
Assistant Professor

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

13. Explain this and static keyword in java.


 This Keyword:
 In java, this is a reference variable that refers to the current object.
 Usage of java this keyword:
 This keyword can be used to refer current class instance variable.
 This() can be used to invoke current class constructor.
 This keyword can be used to invoke current class method (implicitly)
 This can be passed as an argument in the method call.
 This can be passed as argument in the constructor call.
 This keyword can also be used to return the current class instance.
 Example:

class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}

Advanced Computer Programming UNIT 4 Page 19


Vidya Murugendrappa
Assistant Professor

Student13(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
 Static Keyword in java:
 The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
 The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) Java static variable:

 If you declare any variable as static, it is known static variable.


 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students
etc.
 The static variable gets memory only once in class area at the time of class loading.
 Advantage of static variable:
 It makes your program memory efficient (i.e it saves memory).
 Example:

//Program of static variable

Advanced Computer Programming UNIT 4 Page 20


Vidya Murugendrappa
Assistant Professor

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}

Test it Now
Output:111 Karan ITS
222 Aryan ITS

14. Write a java programs to search month belongs to which season.

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

Advanced Computer Programming UNIT 4 Page 21


Vidya Murugendrappa
Assistant Professor

System.out.println("Month”+l is in the " + season + ".");


}
}
15. Write a java programs to display student id and name.

class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
222 Aryan

Advanced Computer Programming UNIT 4 Page 22

You might also like