You are on page 1of 11

JAVA UNIT-2 JAVA UNIT-2

Decision Making and Branching if-else Statement:


The if-else statement is an extension of the simple if statement. The general form is
Explain all about if statements?
if(condition){

if statements: True block


}
The “if” statement is a powerful decision making statement and is used
else{
to control the flow of execution of statements. It is basically a two – way Test Alternate block
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 If the test condition (condition) is true then the true block is immediately following the if
2. if … else statement statement is executed; otherwise the alternate block is executed. In either case , either true
3. Nested if … else statement block or alternate block will be executed not both. In both the cases the control is transferred
4. else if ladder to Statement-x
Nested if- else Statement:
if a statement executes after no of conditions then we can choose nested if – else
Simple if statement: blocks. In this a condition is executes after a condition execution When you nest ifs,
An “if” statement consists of a Boolean expression followed by one or more the main thing to remember is that an else statement always refers to the nearest if
statements. statement.
Syntax:
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.

1 2
JAVA UNIT-2 JAVA UNIT-2

else - - if Ladder }

A common programming construct that is based upon a sequence conditions is the else-if else{

ladder. if(n2 > n3)


Syn: System.out.println(n2 +" is big ");
if(condition) else
statement; System.out.println(n3 +" is big ");
else if(condition) }
statement; }
else if(condition) }
statement;
Explain switch statement?
...
else
Switch:
statement; The switch statement is Java’s multi way branch statement. It provides an easy way to

The if statements are executed from the top down. As soon as one of the conditions is true, dispatch execution to different parts of your code based on the value of an expression.
the statement associated with that if is executed, and the rest of the ladder is bypassed. If Syn:

none of the conditions is true, then the final else statement will be executed. The final else switch (expression)

acts as optional. If there is no final else and all other conditions are false, then no action will {

take place. case value1:

Example: // statement sequence


import java.util.*; break;
class biggest{ case value2:

public static void main(String args[]){ // statement sequence

int n1,n2,n3; break;


Scanner sc = new Scanner(System.in); ...

System.out.println("Enter three numbers: "); case valueN:

n1= sc.nextInt(); // statement sequence

n2= sc.nextInt(); break;

n3=sc.nextInt(); default:

if(n1 > n2){ // default statement sequence

if(n1 > n3) }

System.out.println(n1 +" is big ");


else
System.out.println(n3 +" is big ");

3 4
JAVA UNIT-2 JAVA UNIT-2

The switch statement works like this: The value of the expression is compared with The exp1 is evaluated first. If the result is true, exp2 is evaluated and returned as the value of
each of the “ case “ values. If a match is found, the statements following that case are the conditional expression. Otherwise exp3 is evaluated and its value is returned. When the
executed. If none of the case values are not matched, then the optional default statement is conditional operator is used, the code becomes simpler, efficient. However the readability is
executed. The break statement is used inside the switch to terminate a statement sequence. poor.
Example: Example:
class ColorDemo{ import java .util.*;
public static void main(String args[])throws Exception{ class cond_ex{
char color ; public static void main(String args[]){
System.out.print("Enter a charecter : "); int x, y,big;
color=(char)System.in.read(); Scanner sc = new Scanner (System.in);
switch (color){ System.out.println("Enter two nos :");
case 'r': x=sc.nextInt();
System.out.println ("red"); break; y=sc.nextInt();
case 'g': big=(x>y) ? x: y;
System.out.println ("green"); break; System.out.println("Biggest no : "+big);
case 'b': }
System.out.println ("blue"); break; }
case 'y': Write a short note on while loop?
System.out.println ("yellow"); break;
The while loop is Java’s most fundamental looping statement. It repeats a statement or block
case 'w':
while its controlling expression is true. Here is its
System.out.println ("white"); break;
general form:
default:
Syn:
System.out.println ("No Color Selected");
while(condition)
}
{
}
// body of loop
}
}
Explain Conditional Operator?
Conditional Operator (? : ):
It is a ternary operator, useful for making two way decisions. This operator is a combination It is an entry control loop, i.e. the condition is checked at the time of entry point of the
of ? and : and takes three operands. The general form of this operator is 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.
exp1 ? exp2: exp3; This process will continue until the condition will become false. Once the condition is
false then the control transfers to out of loop.

5 6
JAVA UNIT-2 JAVA UNIT-2

Example:  Like initialization the increment part may also have more than one expression and
import java .util.*; separated by comma.
class series{ for(n=1, m=20 ; n<=m ; n=n+1, m=m-2)
public static void main(String args[]){  One or more sections can be omitted from the for statement. However, the semicolons
int n,i=1; separating the sections must remain.
Scanner sc = new Scanner(System.in); for( ; m<=10 ; )
System.out.print("Enter a no :");
n=sc.nextInt(); Initialization
while(i<=n){
System.out.print(i+" ");
i++;
} False Cond True Loop Body Increment
}
}

Explain for loop with an example?


it is an entry controlled loop and counter controlled loop. The general syntax is as
follows.
Example:
for (initialization ; condition ; updation)
import java.util.*;
{
class prime {
// Loop Body
public static void main(String args[ ]) {
}
int n,i,c;
The for loop operates as follows:
String str;
 When the loop first starts, the initialization portion of the loop is executed.
Scanner sc= new Scanner (System.in);
 Next, condition is evaluated. If this condition is true, then the body of the loop is
System.out.println("Enter a number ");
executed. If it is false, the loop terminates.
n= sc.nextInt();
 Next, the updation portion of the loop is executed.
for(i=1,c=0 ; i<=n ; i++) {
 This process repeats until the controlling expression is false.
if(n%i==0)
Features:
c++;
 In for loop more than one variable can be initialized at a time in for statement,
}
separated by comma.
str = (c = = 2) ? "prime no " : "Not a prime no ";
for ( i=0, j=10, k=1; i<=20 ; i++)
System.out.println (str) ;
}
}

7 8
JAVA UNIT-2 JAVA UNIT-2

Explain do-while loop? Differences between while and do - while loops


It is exit controlled loop i.e. the loop condition is evaluated after the loop body While:

execution. In this the loop body will execute minimum one time. If the condition is true , the  While loop is an entry controlled loop.

program continues to evaluate the body of the loop once again. This process continues as  It is generally used for implementing common looping situations.

long as the condition is true. When the condition is false, the loop will be terminated, and the  It executes if the condition is true.

control goes to the statement that appears immediately after the while statement. do .. while :
 It is an exit controlled loop.
 It is typically used for implementing menu-based programs where the menu required
Loop Body do
to be printed at least once.
{
 The loop will execute minimum one time.
// Loop Body;

F T }while(Cond); Explain about jump statements?


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

Exaple: 2. break can be used inside the switch block to come out of the switch block.

import java.util.*; 3. break can be used in nested blocks to go to the end of a block. Nested blocks

class digit_sum{ represent a block written within another block.

public static void main(String args[ ]){ Syn:

int n,sum=0,r; break;


Scanner sc = new Scanner(System.in); break label; //here label represents the name of the block.
System.out.print ("Enter a number : ");
n=sc.nextInt( );
Example:
int t=n;
import java.util.*;
do{
class break_ex{
r=t%10;
public static void main(String args[ ]){
sum=sum+r;
int n,i,c;
t=t/10;
String str;
} while( t > 0) ;
Scanner sc = new Scanner(System.in);
System.out.println("The digital sum of "+n +" is "+sum);
System.out.print("Enter a number : ");
}
n=sc.nextInt();
}

9 10
JAVA UNIT-2 JAVA UNIT-2

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


OBJECT ORIENTED PROGRAMMING
if(n % i= =0)
c++; What is a class?
if(c= =2) Class:
break; 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
str = (i= =n) ? "Prime number " : "Not a Prime number "; is declared by use of the class keyword. The general form of a class definition is:
System.out.println(str); class classname
} {
} type instance-variables;
continue: type methodname1(parameter-list) {
The continue, as name implies, causes the loop to be continued with the next iteration // body of method
after skipping any statement in between. When continue is executed, subsequent }
statements inside the loop are not executed. }
Syn: Variables defined within a class are called instance variables because each instance
Example: continue: of the class (that is, each object of the class) contains its own copy of these variables.
class continue_ex{ Example:
public static void main(String args[ ]){ class rectangle
int i=0; {
while(++i <=10){ int length;
if(i= =5 || i= =6) int width;
continue; void getdata(int x, int y) { }
System.out.print(i+" "); 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.
return:
 First, you must declare a variable of the class type.
1. return statement is useful to terminate a method and come back to the calling method.
Rectangle r1; // declare reference to object
2. return statement in main method terminates the application.
 Second, you must acquire an actual, physical copy of the object and assign it to that
3. return statement can be used to return some value from a method to a calling method.
variable. You can do this using the new operator.
Syn: return;
r1= new Rectangle ( ); // allocate a rectangle object
(or)
return value; // value may be of any type

11 12
JAVA UNIT-2 JAVA UNIT-2

 The new operator dynamically allocates memory for an object and returns a reference Explain method overloading?
to it.
 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
Explain how to access class members with an example? you desire. There is no rule stating that overloaded methods must relate to one
Every class type object will contain its own copy of the instance variables. To access another.
these variables, you will use the dot (.) operator. The dot operator links the name of Example:
the object with the name of an instance variable. class rectangle {
r1 . length=10 int length, width;
Example: void read( ){
class rectangle{ length=10;
int length, width; width=5;
void getdata(int x, int y){ }
length=x; void read(int x){
width=y; length=width=x;
} }
int area( ){ void read(int x, int y){
int a; length=x;
a=length*width; width=y;
return(a); }
}} int area( ) {
class shape { return(length*width);
public static void main ( String args[ ] ){ }
rectangle r = new rectangle( ); }
r.getdata(10,5); class overload_demo{
System.out.println("area of the rectangle is "+r.area( )); public static void main( String args[ ] ){
}} rectangle r1 = new rectangle();
rectangle r2= new rectangle();
r1.read(15,5);

13 14
JAVA UNIT-2 JAVA UNIT-2

r2.read( ); rectangle r2= new rectangle( );


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

What is a constructor and explain its properties with an example? What is a constructor explain its types with examples?
Constructor: Constructor:
 Constructor is a member method used to construct the object. It has the same name as  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 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 constructor is automatically called immediately after the object is created, before the
new operator completes. new operator completes.
Properties:  We can define the following types of constructors
 Constructors can’t return any value not even void also. The implicit return type of a  Default constructor
class’ constructor is the class type itself.  Parameterized constructor
 The constructor must be public.  Overloading of constructors
 If you won’t create your constructor the JVM creates a constructor and is called  Cloning of constructors.
default constructor. Once you define your own constructor, the default constructor is
no longer used.
Default constructor:
 Apart from the object creation we can use the constructor method to initialize the
When we create a constructor with out any parameters then it is known as default
object.
constructor. We can instantiate the object normally.
 Like other methods the constructor method also parameterized and overloaded.
Parameterized constructor:
Example:  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
class rectangle{
int length, width; supply the required no , type of parameters at the time of instantiation, the constructor
is implicitly invoked by passing certain no of parameters.
public rectangle( ){ //constructor method
Example:
length=10;
class rectangle {
width=5;
} int length, width;
public rectangle (int x, int y){ // parameterized constructor
int area( ){
length=x;
return(length*width);
width=y;
}}
class constructor_demo{ }

public static void main ( String args[ ] ){


rectangle r1 = new rectangle( );

15 16
JAVA UNIT-2 JAVA UNIT-2

int area( ){ class constructor_over {


return(length*width); public static void main ( String args[ ] ) {
}} rectangle r1 = new rectangle(10,5);
class constructor_para { rectangle r2= new rectangle(20);
public static void main ( String args[ ] ) { System.out.println("Area of first recangle : "+r1.area());
rectangle r1 = new rectangle(10,5); System.out.println("Area of second recangle : "+r2.area());
rectangle r2= new rectangle(20,10); }}
System.out.println("Area of first recangle : "+r1.area()); Constructor taking Objects as Parameters
System.out.println("Area of second recangle : "+r2.area()); 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
Overloading of constructors class as a parameter. To define this type constructors the class must overload the
We can also define more than one constructor in a class so that we can customize the constructor methods. This process of constructing an object using another object is
way object creation. At the time instantiation we can invoke the required constructor. called object cloning.
Example:
class rectangle { Example:
int length, width; class rectangle {
public rectangle( ){ //default constructor int length, width;
length=0; public rectangle ( int x, int y) {
width=0; length=x;
} width=y;
//constructor with two parameters }
public rectangle(int x, int y) { public rectangle(int x) {
length=x; length=width=x;
width=y; }
} public rectangle (rectangle t) {
//constructor with one parameter length=t.length;
public rectangle ( int x ){ width=t.width;
length=width=x; }
} int area ( ) {
int area( ) { return(length*width);
return (length*width); }
} }
}

17 18
JAVA UNIT-2 JAVA UNIT-2

class clone { }
public static void main ( String args[ ] ) { static void callme() {
rectangle r1 = new rectangle(10,5); System.out.println("a = " + a);
rectangle r2= new rectangle(r1); }}
System.out.println("Area of first recangle : "+r1.area()); class stat2 {
System.out.println("Area of Third recangle : "+r2.area()); public static void main ( String args[ ] ) {
}} StaticDemo.callme( );
Explain about static members of the class? System.out.println ("b = " + StaticDemo.b);

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. What is access specifier ? Explain deferent Access Specifiers supported by java?:
 When a member is declared static, it can be accessed before any objects of its class  An access specifier is a key word that represents how to access a member of a class.

are created, and without reference to any object. There are four access specifiers in java.

static int count;  only one accessibility modifier can be specified for a member

static void max ( int x , int y); public Members


 You can declare both methods and variables to be static. Public accessibility is the least restrictive of all the accessibility modifiers. A public

 When a class is instantiated only one copy of static data members are created in the member is accessible from anywhere, both in the package containing its class and in

class memory. other packages where this class is visible. This is true for both instance and static

 We can initialize the static variables by using static block, which gets executed members.

exactly once, when the class is first loaded. protected Members


 A static method can be called before its instantiation using the following general A protected member is accessible in all classes in the same package, and by all
form: subclasses of its class in any package where this class is visible. It is more restrictive
than public member accessibility.
classname . method( )
Default Accessibility for Members
 Methods declared as static have several restrictions:
When no member accessibility modifier is specified, the member is only accessible by
 They can only call other static methods.
other classes in its own class’s package. Even if its class is visible in another (possibly
 They must only access static data.
nested) package, the member is not accessible elsewhere. Default member
 They cannot refer to this or super in any way.
accessibility is more restrictive than protected member accessibility.
Example:
private Members
This is the most restrictive of all the accessibility modifiers. Private members are not
class StaticDemo {
accessible from any other classes. This also applies to subclasses, whether they are in
static int a = 10;
the same package or not. Since they are not accessible by their simple name in a
static int b ;
subclass, they are also not inherited by the subclass.
static{
b=a*2;

19 20
JAVA UNIT-2

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

21

You might also like