CJ Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Core

JAVA
MODULE-2: Control Flow Statements,Iterations and Classes

Vidyalankar School of Compiled by: Beena Kapadia


Information Technology
Wadala (E), Mumbai [email protected]
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “CORE JAVA” comprises all
elementary learning tools for a better understating of the relevant concepts. This e-
book is comprehensively compiled as per the predefined eight parameters and
guidelines.

Signature Date: 19-11-2019


Ms. Beena Kapadia
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit II Control Flow Statements,Iterations and Classes

Contents :
Control Flow Statements: The If…Else If…Else Statement, The Switch…Case Statement

Iterations: The While Loop, The Do … While Loop, The For Loop, The Foreach Loop, Labeled
Statements, The Break And Continue Statements, The Return Statement

Classes: Types of Classes, Scope Rules, Access Modifier, Instantiating Objects From A Class,
Initializing The Class Object And Its Attributes, Class Methods, Accessing A Method, Method Returning
A Value, Method's Arguments, Method Overloading, Variable Arguments [Varargs], Constructors, this
Instance, super Instance, Characteristics Of Members Of A Class, constants, this instance, static fields of
a class, static methods of a class, garbage collection.

Recommended Books :
Core Java 8 for Beginners, Vaishali Shah, Sharnam Shah, 1st Edition
Java: The Complete Reference , Herbert Schildt ,9th Edition
Murach’s beginning Java with Net Beans, Joel Murach , Michael Urban, 1st Edition
Core Java, Volume I: Fundamentals, Hortsman, 9th Edition
Core Java, Volume II: Advanced Features, Gary Cornell and Hortsman, 8th Edition
Core Java: An Integrated Approach , R. Nageswara Rao , 1st Edition

Prerequisites/linkages
Unit II Pre- Sem. I Sem. II Sem. III Sem. V Sem. VI
requisites
Control Flow -- IP WP, Python Enterprise Project
Statements,Iterati OOPS Java,
ons and Classes AWP
Control Flow Statements

 If
The general form :
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block). The condition is any expression that returns a boolean value.
The else clause is optional.
The if works like this: If the condition is true, then statement1 is executed.
Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed.

For example, consider the following:


int a, b;
// ...
if(a < b) a = 0;
else b = 0;

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are
they both set to zero.

 Nested ifs
A nested if is an if statement that is the target of another if or else.
Example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)

 The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. The General Form:
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 last
else statement is performed. If there is no final else and all other conditions are false, then no
action will take place.
// 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";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
OUTPUT:
April is in the Spring.

 switch
The general form of a switch statement:
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 (that is, 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. When a
break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
OUTPUT:
i is zero. i is one. i is two. i is three. i is greater than 3. i is greater
than 3.

Iterations

 while
The general form:
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.

// Demonstrate the while loop


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

OUTPUT:
tick 10 tick 9 tick 8 tick 7 tick 6
tick 5 tick 4 tick 3 tick 2 tick 1
 do-while
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.

// Demonstrate the do-while loop.


class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
OUTPUT:
tick 10 tick 9 tick 8 tick 7 tick 6
tick 5 tick 4 tick 3 tick 2 tick 1

 For
The general form:
for(initialization; condition; iteration) {
// body
}
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 controlvariable, which acts as a counter that controls the
loop.
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:
// 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);
}
}
 Empty For Loop
The Syntax:
for(;;){
// body
}
Omitting the test is equivalent to a perpetually true test. So the above condition creates loop
that repeats Forever.

 Foreach Loop
The for each loop allows iterating over arrays and other collections in sequential
fashion from start to finish.

Syntax:
for(data_type variable : array | collection){}

//Demonstrate foreach loop


class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
for(int i:arr){
System.out.println(i);
}

}
}
Output:
12
13
14
44

Source:- https://www.youtube.com/watch?v=8eVyuSq3GCQ
 Jump Statements
Java supports three jump statements: break, continue, and return.
Using break
When the break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop. When
the loops are nested, the break would only exit from the loop containing it. That is, the break
will exit only a single loop.

while(……..) do
{ {
…………………… ……………………
…………………… ……………………
if(condition) if(condition)
break; break;
…………………… ……………………
…………………… ……………………
} } while(……..);
…………………… ……………………
for(…………) for(…………)
{ {
…………………… ……………………
…………………… for(…………)
if(condition) {
break; if(condition)
…………………… break;
…………………… ……………………
} ……………………
………………… }
……………………
}

Skiping a part of a loop


Unlike the break which causes the loop to be terminated, the continue statement is
used to continue the loop with the next iteration after skipping any statements in between.

while(……. do for(……..)
.) { {
{ …………… ……………
………… … …
…… …………… ……………
………… … …
…… if(condition) if(condition)
if(condition contin contin
) ue; ue;
continue; …………… ……………
………… … …
…… …………… ……………
………… … …
…… }while(……..); }
}

 LABELLED LOOPS
In java , we can give a label to a block of statements. A label is any valid java
variable name. to give a label to a loop, place it before the loop with a colon at the
end. Example:
Loop1: for(……..)
{
………………
}
A block of statement can be labeled as

Block1: {
………………

Block2: {
………………
}
}
To jump outside a nested loops or to continue a loop that is outside the current one, then we
may have to use the labelled break and labelled continue statements.

//Demonstrate labelled continue and break statement


class continuebreak
{
public static void main(String args[]) {
Loop1: for(int i=1;i<100;i++)
{
System.out.println(" ");
if(i>=10) break;
for (int j=1;j<100;j++)
{
System.out.print(" * ");
if(j==i)
continue Loop1;
}
}
System.out.println("Termination by BREAK");
}
}

OUTPUT:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
Termination by BREAK
 Return Statement
The return statement is used to explicitly return from a method. It causes the program
control to transfer back to the caller of the method. Thus the return statement
immediately terminates the method in which it is executed.

//Demonstrate return statement


class ReturnEx{
public static void main(String args[]) {
boolean t= true;
System.out.println(“Before the return.”);
if(t)
return;
System.out.println(“This will not be executed.”);
}
}

Output:
Before the return.

In the above code the final println() statement will not be executed. As soon as the return
statement is executed, the control passes back to the caller.

Classes ,Objects and Methods


 DEFINING A CLASS
A class is user defined data type with a template that serves to define its properties.
The basic form of a class definition is:
class classname [extends superclassname]
{
[field declaration];
[methods declaration];
}

Everything inside a square bracket is optional. This means the following would be a valid
class definition:
class empty
{
}
Because the body is empty, this class does not contain any properties and therefore cannot do
anything . but we can compile it and even create its objects.
Classname and superclassname are any valid java identifiers. The keyword extends indicates
that the properties of the superclassname class are extended to the classname class.

 FIELDS DECLARATION
Data is encapsulated in a class by placing data fields inside the body of the class
definition. These variables are called instance variables because they are created
whenever an object of the class is instantiated. They are also known as member
variables.
Example:
class Rectangle
{
int length;
int width;
}
The class Rectangle contains two integer type instance variables. It is allowed to
declare them in one line as int length, width;

 METHOD DECLARATION
Methods are declared inside the body of the class but immediately after the declaration of
instance variables. The general form of a method declaration is

type methodname (parameter-list)


{
Method-body;
}
Method declaration have four basic parts:
 The name of the method(methodname)
 The type of the value the method returns(type)
 A list of parameters(parameter-list)
 The body of the method
Example 1:
class Rectangle
{
int length;
int width;
void getdata(int x, int y) //method declaration
{
length=x;
width=y;
}
}
Example 2:
class Rectangle
{
int length,width; //combined declaration

void getdata(int x, int y) //method declaration


{
length=x;
width=y;}
int rectarea() // declaration of another method
{
int area=length*width;
return (area);
}
}

Instance variables and methods in classes are accessible by all the methods in the class but a method
cannot access the variables declared in other methods. Example:
class Access
{
int x;
void method1()
{
int y;
x=10; //legal
y=x; //legal
}
void method2()
{
int z;
x=5; //legal
z=10 //legal
y=1; //illegal
}

 CREATING OBJECTS
 Objects in java are created using the new operator. The new operator creates an
object of the specified class and returns a reference to that object. Example:
Rectangle rect1; //declare the object
Rect1=new Rectangle(); //instantiate the object
 The first statement declares a variable to hold the object reference and the second one
actually assigns the object reference to the variable. The variable rect1 is now an
object of the Rectangle class.
Action Statement Result
Declare Rectangle rect1; Null rect1
Instantiate rect1=new Rectangle(); Creates rect1, reference to rectangle object
 Both statements can be combined
Rectangle rect1=new Rectangle();
 The method rectangle() is the default constructor of the class. We can create any
number objects of Rectangle. Example:
Rectangle rect1=new rectangle();
Rectangle rect2=new rectangle();
.
.
.
Rectangle rectN=new rectangle();
 Each object has its own copy of the instance variables of its class. This means that
any changes to the variables of one object have no effect on the variables of another.
 It is also possible to create two or more references to the same object
Example:
Rectangle R1=new Rectangle();
Rectangle R2=R1;

Both R1 and R2 refer to the same object.

 ACCESSING CLASS MEMBERS


To access instance variables and methods outside the class we must use concerned
object and the dot operator.
Objectname.variablename=value;
Objectname.methodname(parameter-list);
Example:
The instance variables and methods of a class Rectangle can be accessed and assigned
values as follows:
rect1.length=15; //accessing instance variables
rect1.width=20; //accessing instance variables
rect1.getdata(20,30); //calling the method

int area1=rect1.length*rect1.width //accessing instance variables


int area=rect1.rectArea(); //calling the method which returns
integer value

//Demonstrate Application of classes and objects


class Rectangle
{ int length,width; //Declaration of Variables
void getData(int x ,int y) //Definition of Method
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return area;
} }

class Mainrect
{ public static void main(String a[])
{
int area1,area2;
Rectangle rect1=new Rectangle();
rect1.getData(20,40);
area1=rect1.rectArea();

Rectangle rect2=new Rectangle();


rect2.getData(15,12);
area2=rect2.rectArea();

System.out.println("Area1="+area1);
System.out.println("Area2="+area2);
} }

OUTPUT:
Area1=800
Area2=180

Source:- https://www.youtube.com/watch?v=yJAuuDAF4Yo
 Types of classes
1. Public Class
a. The public modifier specifies that other objects outside the current
package can use the class.
b. By default the classes are public in same package.and private if a class
is accessed from another package.
Syntax:
Public class<class name>{//body of class}
Eg:
Public class Employee{//body of class}
Here employee class can be accessed by any class either in the same package or in some
other package.

2. Private Class
a. The private modifier specifies that other objects outside the current
package cannot use the class.
b. Private class has to be defined within another class.

Syntax:
private class<class name>{//body of class}
Eg:
Public class employee{
Private class Manager{//body of class}
}
Here Manager class is defined within the class Employee. So the class Manager can be
accessed within the employee but not outside the class.

3. Final Class
a. The final modifier specifies a class that can have no subclasses.
b. Since final classes cannot be sub classes, additional variables and
methods cannot be added and methods cannot be overridden.

Syntax:
final class<class name>{//body of class}
Eg:
final class Employee{//body of class}
Here employee class is declared as final so it cannot be used to create any other class i.e
employee class cannot be sub classed.

4. Abstract Class
a. An abstract modifier specifies a class that has at least one abstract
method in it.
b. An abstract method is one that has no implementation. An abstract
class cannot be instantiated.
c. The purpose of having abstract class is to declare methods, yet leave
them unimplemented. The subclasses of an abstract class are required
to provide implementation for the abstract methods.

Syntax:
abstract class<class name>{//here there is no signature}
Eg:
abstract class MyGraphics{
public abstract void draw();
}
Here a class called MyGraphics, which has a method draw(). Depending on their shape,
different objects will require different draw() methods(). For eg:- a circle class will have a
different draw() method from a square.

 Scope Rules
 In early programming languages such as COBOL, all variables were considered
global variables.
 A global variable is a variable that can be accessed from any part of the program. So
global variables must have unique names. Also single variable can be used for
different puposes in different parts of the program. But change in one part of the code
can adversely affect a completely different part of the program.
 The solution to the problem of global variables is to use local variables, which have a
limited
life span and relate to only a single part of the code. One can make use of two
variables with identical names as long as they are in different parts of the program.
 The rules that dictate which parts of the program can see which variables are called
scope rules

 Access Modifier
1. Public Access
a. The Public access specifies that the variables of a class can be freely accessed
from outside the class of the current package.
b. By default the scope of a variable is public in same package.and private if the
variable is accessed from another package.
Syntax:
public <data type><variable name>=[value]
public <data type><method name>();

2. Private Access
a. To completely hide a method or variable from being used by any other class, the
private modifier is used.
b. The only place these variables or methods can be seen is from within their own
class.
Syntax:
private <data type><variable name>=[value]
private <data type><method name>();
c. A private instance variable for example, can be used by methods in its own class
but not by methods of any class. In the same way private methods can be called
by other methods in their own class but by no others.

3. Protected Access
a. Protected variables or methods can be freely accessed either in a subclass or any
other class in the same package.

Syntax:
protected<data type><variable name>=[value]
protected <data type><method name>();
 CONSTRUCTORS
 Constructor is special type of a method that enables an object to initialize itself
when it is created.
 Constructors have the same name as the class itself.
 They do not specify return type, not even void. This is because they return the
instance of the class itself.

//Demonstrate Application of constructors


class Rectangle
{
int length,width; //Declaration of Variables
Rectangle() //Defining default Constructor
{
length=20;
width=40;
}
Rectangle(int x,int y) //Defining Parameterized Constructor
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return area;
}
}
class Mainrect {
public static void main(String a[])
{ int area1,area2;
Rectangle rect1=new Rectangle(); //Calling default constructor
area1=rect1.rectArea();
Rectangle rect2=new Rectangle(25,15); //Calling parameterized constructor
area2=rect2.rectArea();
System.out.println("Area1="+area1);
System.out.println("Area2="+area2);
}}
OUTPUT:
Area1=800
Area2=375

 METHOD OVERLOADING
 The process of creating method with the same name but different parameter list
and different definitions is called Method Overloading.
 Method overloading is used when objects are required to perform similar tasks using
different input parameters.
 When we call a method in an object, java matches up the method name first and then
the number and type of parameters to decide which one of the difinitions to execute.
This process is known as polymorphism.

//Demonstrate Method Overloading of Area() method

class MethdOver
{
int Area(int side)
{
int area=side*side;
return area;
}
int Area(int length,int width)
{
int area=length*width;
return area;
}
}

class MainOverloading
{
public static void main(String a[])
{
int area1,area2;
MethdOver m1=new MethdOver();
area1=m1.Area(20);
area2=m1.Area(15,30);
System.out.println("Area of Square="+area1);
System.out.println("Area of Rectangle="+area2);
}
}

OUTPUT:
Area of Square=400
Area of Rectangle=450

//Demonstrate Constructor Overloading

class Room
{
float length,breadth;
Room(float x,float y) //constructor 1
{
length=x;
breadth=y;
}

Room(float x) //constructor 2
{
length=breadth=x;
}
float Area()
{
float area=length*breadth;
return area;
}
}

class MainRoom
{
public static void main(String a[])
{
float area1,area2;
Room r1=new Room(20.5f,23.4f);
Room r2=new Room(40.6f);
area1 = r1.Area();
area2=r2.Area();
System.out.println("Area of Square Room="+area1);
System.out.println("Area of Rectangular Room ="+area2);
}
}

OUTPUT:
Area of Square Room=479.69998
Area of Rectangular Room =1648.3599

 NESTING OF METHODS
A method can be called by using only its name by another method od the same class.
This is known as nesting of methods.
Program below illustrate the nesting of methods inside a class. The class Nesting
defines one constructor and two methods, namely largest() and display(). The
method display() calls the method largest() to determine the largest of the two
numbers and then displays the result.

class Nesting
{
int m,n;
Nesting(int x , int y)
{
m=x;
n=y;
}

int largest()
{
if(m>=n)
return m;
else
return n;
}
void display()
{
int large=largest(); //calling a method
System.out.println("Largest value="+large);
}
}

class NestingTest
{
public static void main(String[] a)
{
Nesting nest=new Nesting(23.45);
nest.display();
}
}

OUTPUT:
Largest value=45

Variable Arguments [Varargs]


Variable Arguments also known as Varargs is a feature that allows declaring a method that
can accept a variable number of parameters for a given argument. Vararg must be the last argument
in the formal argument list.
Syntax:
return_type method_name(data_type… variableName)
{
//body of method
}

//program to demonstrate the use of Variable Arguments


public class A{
public static void show(String… records){
for(String r : records)
System.out.println(“Hello ”+r+”.”);
}
public static void main(String args[]){
show(“Shruti”,”Sakshi”);
}
}
Output:
Hello Shruti.
Hello Sakshi.

The this Keyword


“this” keyword can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked.
You can use this anywhere a reference to an object of the current class type is permitted.
// A redundant use of this.
Class Box
{
double width,height,depth;
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
} }
Inside Box( ), this will always refer to the invoking object.
when a local variable has the same name as an instance variable, the local variable hides the
instance variable. This is why width, height, and depth were not used as the names of the
parameters to the Box( ) constructor inside the Box class. If they had been, then width would have
referred to the formal parameter, hiding the instance variable width.
We can use same name for instance variable and local variables using this keyword
Because this lets you refer directly to the object, you can use it to resolve any name space collisions
that might occur between instance variables and local variables.
For example, here is another version of Box( ), which uses width, height, and depth for parameter
names and then uses this to access the instance variables by the same name:

// Use this to resolve name-space collisions.


class box
{
double width,height,depth;
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
} }

Java static keywod


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

Understanding problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so instance
data member is good.Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.

Example of static variable


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

Output:
111 Karan ITS
222 Aryan ITS
2. Java static method

If you apply static keyword with any method, it is known as static method.

a. A static method belongs to the class rather than object of a class.


b. A static method can be invoked without the need for creating an instance of a class.
c. static method can access static data member and can change the value of it.

Example of static method

//Program of changing the common property of all objects(static field).

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

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

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

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output: 111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Restrictions for static method


There are two main restrictions for the static method. They are:
 The static method can not use non static data member or call non-static method
directly.
 this and super cannot be used in static context.

Source:- https://www.youtube.com/watch?v=3gYr83ni388

 Garbage Collection
 In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
 Java takes a different approach; it handles deallocation of objects automatically using
garbage collection.
 It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed. There is
no explicit need to destroy objects as in C++.
 Garbage collection only occurs sporadically (if at all) during the execution of your
program. It will not occur simply because one or more objects exist that are no longer
used.
The finalize( ) Method
 Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed.
 To handle such situations, Java provides a mechanism called finalization. By using
finalization, you can
define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector.
 The Java run time calls the method finalize() whenever it is about to recycle an object of that
class.
Inside the finalize( ) method, you will specify those actions that must be performed before
an object is destroyed.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside
its class.

gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes. Garbage collection is performed by a daemon thread
called Garbage Collector(GC). This thread calls the finalize() method before object is garbage
collected.

//program to demonstrate the use of finalize() and gc() method


Public class Grb
{
Public void finalize()
{
System.out.println(“Destroyed”);
}
Public static void main(String args[])
{
Grb G1=new Grb();
G1=null;
System.gc();
}
}

Output:
Destroyed
Source:- https://www.youtube.com/watch?v=b2DFCthQsp8

Question Bank
1. Describe the syntax of if-else statement in java with program.
2. Describe the synatx of for loop in java with program.
3. Write a program to demonstrate the use of the Switch Case Statement.
4. Write a short note on Labelled Statements.
5. Write a program to demonstrate use of for each loop.
6. Explain while and do..while loop in detail.
7. Explain the structure of class in java.
8. What are the types of classes in java?
9. Write short note on Access Modifier.
10. Write a program to demonstrate use of Method Overloading.
11. Explain in details constructors in java.
12. What is Constructor Overloading?
13. What are the characteristics of Members of a class?
14. Explain static fields of a class.
15. Write a short note on Garbage Collection in java.

Multiple Choice Questions


1. In java, ............ can only test for equality, where as .......... can evaluate any type of the Boolean
expression.
a. switch, if
b. if, switch
c. If, break
d. continue, if

2. Determine the output


public class Test{
public static void main(String args[]){
int i;
for(i = 1; i < 6; i++){
if(i > 3) continue ;
}
System.out.println(i);
}
}
a. 5
b. 4
c. 3
d. 6

3. Which of the following for loops will be an infinite loop?


a. for(;;)
b. for(i=0;i<1;i--)
c. for(i=0;;i++)
d. all of the above

4. Which of the following is not a valid flow control statement?


a. Break;
b. Continue outer;
c. Return;
d. Exit();

5. public class Test{


public static void main(String [] args){
int x = 0;
. // insert code here
do{ } while(x++ < y);
System.out.println(x);
}
}
Which option, inserted at line 4, produces the output 12?
a. int y=x;
b. int y=10;
c. int y=11;
d. int y=12;

6. classes are useful because they


a. permit data to be hidden from other classes
b. can closely model objects in the real world
c. brings together all aspects of an entity in one place
d. all of the above.

7. Which of the following is the correct statement to create an object of Data class?
a. Data d=new object();
b. Data d=new Data();
c. Data d()=new Data();
d. D. Data d()=new Data();

8. What will be the return type of a method that not returns any value?
a. Void
b. Int
c. Double
d. None of the above

9. Which of the modifier can't be used for constructors?


a. Public
b. Private
c. Static
d. Protected

10. Which of the following statements are incorrect?


a. default constructor is called at the time of object declaration
b. Constructor can be parameterized
c. finalize() method is called when a object goes out of scope and is no longer needed
d. finalize() method must be declared protected

11. The variables declared in a class for the use of all methods of the class are called
a. Reference variable
b. Objects
c. Instance variable
d. None of these

12. Which of the following statements regarding static methods are correct?
I. Static methods are difficult to maintain, because you can not change their implementation.
II. Static methods can be called using an object reference to an object of the class in which
this method is defined.
III. Static methods are always public, because they are defined at class-level.
IV. Static methods do not have direct access to non-static methods which are defined inside
the same class.

a. I and II
b. II and IV
c. III and IV
d. I and III

13. public class Test { }


What is the prototype of the default constructor?
a. Public Test(void)
b. Test()
c. Test(void)
d. public Test()

14. class MyClass{


int i;
int j;

public MyClass(int i, int j){


this.i = i;
this.j = j;
}

public void call(){


System.out.print("One");
}
}

public class Test{


public static void main(String args[]){
MyClass m = new MyClass(); //line 1
m.call(); //line 2
}
}
a. one
b. compilation fails due to error on line 1
c. compilation fails due to error on line 2
d. compilation succeed but no output.

15. Overloaded methods ____


a. are a group of methods with the same name
b. have the same number and type of arguments
c. make life simpler for programmer
d. may fail unexpectedly due to stress.

You might also like