You are on page 1of 21

Unit-2 KHK

Decision Making and Branching


Explain all about if statements?
if statements:
The “if” statement is a powerful decision making statement and is used
to control the flow of execution of statements. It is basically a two – way Test
Cond
decision statement and is used in conjunction with a boolean expression. ition

The “if” statement may be implemented in different forms


1. Simple if
2. if … else statement
3. Nested if … else statement
4. else if ladder

Simple if statement:
An “if” statement consists of a Boolean expression followed by one or more
statements.
Syn:
The syntax of an if statement is:
if(Expression)
{
//Statements will execute
//if the Boolean expression is true
}

If the expression evaluates to true then


the block of code inside the if statement
will be executed. If not the first set of code after the end of the if statement (after the
closing curly brace) will be executed.

Vasavi Degree College (C) www.anuupdates.org 1


Unit-2 KHK

if-else Statement:
The if-else statement is an extension of the simple if statement. The general form is

if(condition){
True block
}
else{
Alternate block
}

If the test condition (condition) is true then the true block is immediately following the if
statement is executed; otherwise the alternate block is executed. In either case , either true
block or alternate block will be executed not both. In both the cases the control is transferred
to Statement-x

Nested if- else Statement:


if a statement executes after no of conditions then we can choose nested if – else
blocks. In this a condition is executes after a condition execution When you nest ifs,
the main thing to remember is that an else statement always refers to the nearest if
statement.

Vasavi Degree College (C) www.anuupdates.org 2


Unit-2 KHK

else - - if Ladder
A common programming construct that is based upon a sequence conditions is the else-if
ladder.
Syn:
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 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 optional. If there is no final else and all other conditions are false, then no action will
take place.
Example:
import java.util.*;
class biggest{
public static void main(String args[]){
int n1,n2,n3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter three numbers: ");
n1= sc.nextInt();
n2= sc.nextInt();
n3=sc.nextInt();
if(n1 > n2){
if(n1 > n3)
System.out.println(n1 +" is big ");
else
System.out.println(n3 +" is big ");

Vasavi Degree College (C) www.anuupdates.org 3


Unit-2 KHK

}
else{
if(n2 > n3)
System.out.println(n2 +" is big ");
else
System.out.println(n3 +" is big ");
}
}
}

Explain switch statement?


Switch:
The switch statement is Java’s multi way branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression.
Syn:

switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

Vasavi Degree College (C) www.anuupdates.org 4


Unit-2 KHK

The switch statement works like this: The value of the expression is compared with
each of the “ case “ values. If a match is found, the statements following that case are
executed. If none of the case values are not matched, then the optional default statement is
executed. The break statement is used inside the switch to terminate a statement sequence.
Example:
class ColorDemo{
public static void main(String args[])throws Exception{
char color ;
System.out.print("Enter a charecter : ");
color=(char)System.in.read();
switch (color){
case 'r':
System.out.println ("red"); break;
case 'g':
System.out.println ("green"); break;
case 'b':
System.out.println ("blue"); break;
case 'y':
System.out.println ("yellow"); break;
case 'w':
System.out.println ("white"); break;
default:
System.out.println ("No Color Selected");
}
}
}

Explain Conditional Operator?


Conditional Operator (? : ):
It is a ternary operator, useful for making two way decisions. This operator is a combination
of ? and : and takes three operands. The general form of this operator is

exp1 ? exp2: exp3;

Vasavi Degree College (C) www.anuupdates.org 5


Unit-2 KHK

The exp1 is evaluated first. If the result is true, exp2 is evaluated and returned as the value of
the conditional expression. Otherwise exp3 is evaluated and its value is returned. When the
conditional operator is used, the code becomes simpler, efficient. However the readability is
poor.
Example:
import java .util.*;
class cond_ex{
public static void main(String args[]){
int x, y,big;
Scanner sc = new Scanner (System.in);
System.out.println("Enter two nos :");
x=sc.nextInt();
y=sc.nextInt();
big=(x>y) ? x: y;
System.out.println("Biggest no : "+big);
}
}

Write a short note on while loop?


The while loop is Java’s most fundamental looping statement. It repeats a statement or block
while its controlling expression is true. Here is its
general form:
Syn:
while(condition)
{
// body of loop
}

It is an entry control loop, i.e. the condition is checked at the time of entry point of the
loop body. First it evaluates the loop condition, if it is true then the loop body will
executes. After executing the loop body the control again transfers to the condition.
This process will continue until the condition will become false. Once the condition is
false then the control transfers to out of loop.

Vasavi Degree College (C) www.anuupdates.org 6


Unit-2 KHK

Example:
import java .util.*;
class series{
public static void main(String args[]){
int n,i=1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a no :");
n=sc.nextInt();
while(i<=n){
System.out.print(i+" ");
i++;
}
}
}

Explain for loop with an example?


it is an entry controlled loop and counter controlled loop. The general syntax is as
follows.
for (initialization ; condition ; updation)
{
// Loop Body
}

The for loop operates as follows:


 When the loop first starts, the initialization portion of the loop is executed.
 Next, condition is evaluated. If this condition is true, then the body of the loop is
executed. If it is false, the loop terminates.
 Next, the updation portion of the loop is executed.
 This process repeats until the controlling expression is false.
Features:
 In for loop more than one variable can be initialized at a time in for statement,
separated by comma.
for ( i=0, j=10, k=1; i<=20 ; i++)

Vasavi Degree College (C) www.anuupdates.org 7


Unit-2 KHK

 Like initialization the increment part may also have more than one expression and
separated by comma.
for(n=1, m=20 ; n<=m ; n=n+1, m=m-2)
 One or more sections can be omitted from the for statement. However, the semicolons
separating the sections must remain.
for( ; m<=10 ; )

Initialization

False Cond True Loop Body Increment

Example:

import java.util.*;
class prime {
public static void main(String args[ ]) {
int n,i,c;
String str;
Scanner sc= new Scanner (System.in);
System.out.println("Enter a number ");
n= sc.nextInt();
for(i=1,c=0 ; i<=n ; i++) {
if(n%i==0)
c++;
}
str = (c = = 2) ? "prime no " : "Not a prime no ";
System.out.println (str) ;
}
}

Vasavi Degree College (C) www.anuupdates.org 8


Unit-2 KHK

Explain do-while loop?


It is exit controlled loop i.e. the loop condition is evaluated after the loop body
execution. In this the loop body will execute minimum one time. If the condition is true , the
program continues to evaluate the body of the loop once again. This process continues as
long as the condition is true. When the condition is false, the loop will be terminated, and the
control goes to the statement that appears immediately after the while statement.

Loop Body do
{
// Loop Body;
F T }while(Cond);
Cond

Exaple:
import java.util.*;
class digit_sum{
public static void main(String args[ ]){
int n,sum=0,r;
Scanner sc = new Scanner(System.in);
System.out.print ("Enter a number : ");
n=sc.nextInt( );
int t=n;
do{
r=t%10;
sum=sum+r;
t=t/10;
} while( t > 0) ;
System.out.println("The digital sum of "+n +" is "+sum);
}
}

Vasavi Degree College (C) www.anuupdates.org 9


Unit-2 KHK

Differences between while and do - while loops


While:
 While loop is an entry controlled loop.
 It is generally used for implementing common looping situations.
 It executes if the condition is true.
do .. while :
 It is an exit controlled loop.
 It is typically used for implementing menu-based programs where the menu required
to be printed at least once.
 The loop will execute minimum one time.

Explain about jump statements?


Java supports three jump statements: break, continue and return. These statements
transfer control to another part of the program.
break:
1. break can be used inside a loop to come out of it.
2. break can be used inside the switch block to come out of the switch block.
3. break can be used in nested blocks to go to the end of a block. Nested blocks
represent a block written within another block.
Syn:
break;
break label; //here label represents the name of the block.

Example:
import java.util.*;
class break_ex{
public static void main(String args[ ]){
int n,i,c;
String str;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
n=sc.nextInt();

Vasavi Degree College (C) www.anuupdates.org 10


Unit-2 KHK

for(c=0, i=1; i<=n ; i++){


if(n % i= =0)
c++;
if(c= =2)
break;
}
str = (i= =n) ? "Prime number " : "Not a Prime number ";
System.out.println(str);
}
}
continue:
The continue, as name implies, causes the loop to be continued with the next iteration
after skipping any statement in between. When continue is executed, subsequent
statements inside the loop are not executed.
Syn:
continue;
Example:
class continue_ex{
public static void main(String args[ ]){
int i=0;
while(++i <=10){
if(i= =5 || i= =6)
continue;
System.out.print(i+" ");
}
}
}
return:
1. return statement is useful to terminate a method and come back to the calling method.
2. return statement in main method terminates the application.
3. return statement can be used to return some value from a method to a calling method.
Syn: return;
(or)
return value; // value may be of any type

Vasavi Degree College (C) www.anuupdates.org 11


Unit-2 KHK

OBJECT ORIENTED PROGRAMMING


What is a class?
Class:
A class is a user defined data type with a template that serves to define its properties.
Class groups the logically related data items and functions that work on them. A class
is declared by use of the class keyword. The general form of a class definition is:

class classname
{
type instance-variables;
type methodname1(parameter-list) {
// body of method
}
}
Variables defined within a class are called instance variables because each instance
of the class (that is, each object of the class) contains its own copy of these variables.
Example:
class rectangle
{
int length;
int width;
void getdata(int x, int y) { }
int area( ) { }
}

What are objects? How they created from a class?


Creating an object is known as instantiating. Creating objects of a class is a two-step process.
 First, you must declare a variable of the class type.
Rectangle r1; // declare reference to object
 Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.
r1= new Rectangle ( ); // allocate a rectangle object

Vasavi Degree College (C) www.anuupdates.org 12


Unit-2 KHK

 The new operator dynamically allocates memory for an object and returns a reference
to it.

Explain how to access class members with an example?


Every class type object will contain its own copy of the instance variables. To access
these variables, you will use the dot (.) operator. The dot operator links the name of
the object with the name of an instance variable.
r1 . length=10
Example:
class rectangle{
int length, width;
void getdata(int x, int y){
length=x;
width=y;
}
int area( ){
int a;
a=length*width;
return(a);
}}
class shape {
public static void main ( String args[ ] ){
rectangle r = new rectangle( );
r.getdata(10,5);
System.out.println("area of the rectangle is "+r.area( ));
}}

Vasavi Degree College (C) www.anuupdates.org 13


Unit-2 KHK

Explain method overloading?


 In java it is possible to create methods that have the same name, but different
parameters lists and different definitions. This is called method overloading
 Overloaded methods must differ in the type and/or number of their parameters.
 When an overloaded method is called, Java looks for a match between the arguments
used to call the method and the method’s parameters. However, this match need not
always be exact.
 When you overload a method, each version of that method can perform any activity
you desire. There is no rule stating that overloaded methods must relate to one
another.
Example:
class rectangle {
int length, width;
void read( ){
length=10;
width=5;
}
void read(int x){
length=width=x;
}
void read(int x, int y){
length=x;
width=y;
}
int area( ) {
return(length*width);
}
}
class overload_demo{
public static void main( String args[ ] ){
rectangle r1 = new rectangle();
rectangle r2= new rectangle();
r1.read(15,5);

Vasavi Degree College (C) www.anuupdates.org 14


Unit-2 KHK

r2.read( );
System.out.println("Area of first recangle : "+r1.area());
System.out.println("Area of second recangle : "+r2.area());
}}

What is a constructor and explain its properties with an example?


Constructor:
 Constructor is a member method used to construct the object. It has the same name as
the class in which it resides and is syntactically similar to a method. Once defined, the
constructor is automatically called immediately after the object is created, before the
new operator completes.
Properties:
 Constructors can’t return any value not even void also. The implicit return type of a
class’ constructor is the class type itself.
 The constructor must be public.
 If you won’t create your constructor the JVM creates a constructor and is called
default constructor. Once you define your own constructor, the default constructor is
no longer used.
 Apart from the object creation we can use the constructor method to initialize the
object.
 Like other methods the constructor method also parameterized and overloaded.

Example:
class rectangle{
int length, width;
public rectangle( ){ //constructor method
length=10;
width=5;
}
int area( ){
return(length*width);
}}
class constructor_demo{
public static void main ( String args[ ] ){
rectangle r1 = new rectangle( );

Vasavi Degree College (C) www.anuupdates.org 15


Unit-2 KHK

rectangle r2= new rectangle( );


System.out.println("Area of first recangle : "+r1.area());
System.out.println("Area of second recangle : "+r2.area());
}}

What is a constructor explain its types with examples?


Constructor:
 Constructor is a member method used to construct the object. It has the same name as
the class in which it resides and is syntactically similar to a method. Once defined, the
constructor is automatically called immediately after the object is created, before the
new operator completes.
 We can define the following types of constructors
 Default constructor
 Parameterized constructor
 Overloading of constructors
 Cloning of constructors.

Default constructor:
When we create a constructor with out any parameters then it is known as default
constructor. We can instantiate the object normally.
Parameterized constructor:
 We can define a constructor which takes parameters as the normal method can.
 When we are using a parameterized constructor to construct the object we need to
supply the required no , type of parameters at the time of instantiation, the constructor
is implicitly invoked by passing certain no of parameters.
Example:
class rectangle {
int length, width;
public rectangle (int x, int y){ // parameterized constructor
length=x;
width=y;
}

Vasavi Degree College (C) www.anuupdates.org 16


Unit-2 KHK

int area( ){
return(length*width);
}}
class constructor_para {
public static void main ( String args[ ] ) {
rectangle r1 = new rectangle(10,5);
rectangle r2= new rectangle(20,10);
System.out.println("Area of first recangle : "+r1.area());
System.out.println("Area of second recangle : "+r2.area());
}}

Overloading of constructors
We can also define more than one constructor in a class so that we can customize the
way object creation. At the time instantiation we can invoke the required constructor.
Example:
class rectangle {
int length, width;
public rectangle( ){ //default constructor
length=0;
width=0;
}
//constructor with two parameters
public rectangle(int x, int y) {
length=x;
width=y;
}
//constructor with one parameter
public rectangle ( int x ){
length=width=x;
}
int area( ) {
return (length*width);
}
}

Vasavi Degree College (C) www.anuupdates.org 17


Unit-2 KHK

class constructor_over {

public static void main ( String args[ ] ) {


rectangle r1 = new rectangle(10,5);
rectangle r2= new rectangle(20);
System.out.println("Area of first recangle : "+r1.area());
System.out.println("Area of second recangle : "+r2.area());
}}
Constructor taking Objects as Parameters
Frequently we want to construct a new object so that it is initially the same as some
existing object. To do this, we must define a constructor that takes an object of its
class as a parameter. To define this type constructors the class must overload the
constructor methods. This process of constructing an object using another object is
called object cloning.

Example:
class rectangle {
int length, width;
public rectangle ( int x, int y) {
length=x;
width=y;
}
public rectangle(int x) {
length=width=x;
}
public rectangle (rectangle t) {
length=t.length;
width=t.width;
}
int area ( ) {
return(length*width);
}
}

Vasavi Degree College (C) www.anuupdates.org 18


Unit-2 KHK

class clone {
public static void main ( String args[ ] ) {
rectangle r1 = new rectangle(10,5);
rectangle r2= new rectangle(r1);
System.out.println("Area of first recangle : "+r1.area());
System.out.println("Area of Third recangle : "+r2.area());
}}

Explain about static members of the class?


These are the members which resides in the class memory area and can be accessed
by all objects globally. We do this by declaring a member as static.
 When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
static int count;
static void max ( int x , int y);
 You can declare both methods and variables to be static.
 When a class is instantiated only one copy of static data members are created in the
class memory.
 We can initialize the static variables by using static block, which gets executed
exactly once, when the class is first loaded.
 A static method can be called before its instantiation using the following general
form:

classname . method( )

 Methods declared as static have several restrictions:


 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
Example:
class StaticDemo {
static int a = 10;
static int b ;
static{
b=a*2;
Vasavi Degree College (C) www.anuupdates.org 19
Unit-2 KHK

}
static void callme() {
System.out.println("a = " + a);
}}
class stat2 {
public static void main ( String args[ ] ) {
StaticDemo.callme( );
System.out.println ("b = " + StaticDemo.b);
}}

What is access specifier ? Explain deferent Access Specifiers supported by java?:


 An access specifier is a key word that represents how to access a member of a class.
There are four access specifiers in java.
 only one accessibility modifier can be specified for a member
public Members
Public accessibility is the least restrictive of all the accessibility modifiers. A public
member is accessible from anywhere, both in the package containing its class and in
other packages where this class is visible. This is true for both instance and static
members.
protected Members
A protected member is accessible in all classes in the same package, and by all
subclasses of its class in any package where this class is visible. It is more restrictive
than public member accessibility.
Default Accessibility for Members
When no member accessibility modifier is specified, the member is only accessible by
other classes in its own class’s package. Even if its class is visible in another (possibly
nested) package, the member is not accessible elsewhere. Default member
accessibility is more restrictive than protected member accessibility.
private Members
This is the most restrictive of all the accessibility modifiers. Private members are not
accessible from any other classes. This also applies to subclasses, whether they are in
the same package or not. Since they are not accessible by their simple name in a
subclass, they are also not inherited by the subclass.

Vasavi Degree College (C) www.anuupdates.org 20


Unit-2 KHK

Specification Members
Public Accessible everywhere
Protected Accessible by any class in the same package as its class, and
accessible only by subclasses of its class in other packages.

default (no modifier) Only accessible by classes, including subclasses, in the same
package as its class (package accessibility).

Private Only accessible in its own class and not anywhere else

Vasavi Degree College (C) www.anuupdates.org 21

You might also like