[go: up one dir, main page]

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

Basic of Java and Fucntion Theory Class 11

Uploaded by

ayushgupta140310
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)
45 views22 pages

Basic of Java and Fucntion Theory Class 11

Uploaded by

ayushgupta140310
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

C ITY MONTESSORI SCHOOL

SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

INTRODUCING JAVA AND OOP CONCEPTS


Programming Paradigms: A programming paradigm is a fundamental style of programming regarding how solutions
to problems are to be formulated in a programming language. A program can be conceptually organized around its
code or around its data. Thus, there are two paradigms of programming :
1. Procedure oriented
2. Object oriented

Procedure-Oriented Programming: A program in a procedure oriented paradigm is a list of instructions. For e.g.
Pascal, Fortran, C, Basic.
Characteristics:-
i) Programs are divided into subprograms, subroutines, or functions, each function has a clearly defined purpose.
ii) Related functions are grouped into a larger entity called a module.
iii) Employs top-down approach in program design.

Drawbacks:–
i) Most of the functions share data and data moves more openly from function to function.
ii) Functions transform data from one form to another.

Object-Oriented Programming (OOP): OOP organizes a program around its data and a set of well defined interfaces
to that data. For e.g., VC++, Java, Visual Basic.
Characteristics:-
i) Emphasis is on data. i.e., data controls access to code.
ii) Programs are divided into objects.
iii) Functions (or methods) that operate on the data are combined into a single data structure.
iv) Data is hidden and is safe from accidental modification.
v) Objects communicate with each other through methods.

Object = Data + Methods


Basic Concepts of OOPS
Object: An object is a basic identifiable entity that may correspond to real-world ‘things’ such as student, employee,
bank account, inventory item etc. Every object has some distinct properties called attributes and behavior called
operations.
For e.g., an object Calculator can have the attributes: Result, Operand, and operations: Add, Subtract, Multiply and
Divide.

Class: A class defines the generalized structure and behavior (data and code) that will be shared by a set of objects.
Each object of a given class represents the structure and behavior as defined by the class (i.e. every object is an
instance of a class). Thus, a class is a logical construct; and object has a physical reality.
(19)
Encapsulation: It is a mechanism that binds data and code into a single unit. It keeps both data and code safe from
external interference and misuse. Moreover, data can be accessed by only those functions, which are wrapped inside
the class. This insulation of data from direct access by the program is called data hiding.

Abstraction: It refers to the act of representing essential features without including the irrelevant details. Encapsulated
data items use the concept of data abstraction to create new data types, that are suited to an application. For e.g.,
classes encapsulate all the essential properties of objects that are to be created.

Inheritance: It is the process by which objects of one class acquire the properties of another class. The idea is to
make use of an existing class without any further modifications, add additional features to it , thereby deriving a new
class from the existing one. The new class will have the combined features of both the classes.

Circle Cylinder

radius Extend height


circleArea( ) cylArea( )

Existing Class New Class

Polymorphism: It means the ability to take more than one form. For e.g. an operation may show different behavior in
different instances. The specific behavior depends on the data to be processed in the operation.

Shape
area( )

Circle Triangle
area(radius) area(base, height)

Message Communication: Objects communicate with each other by sending messages. A message for an object is
a request for execution of an operation, and therefore, will invoke a method.

Characteristics of Java:
1. Platform Independent.
2. Compiled and Interpreted.
3. Write Once Run Anywhere (WORA).
4. Object Oriented.
5. Portable and Light.

Java Runtime Environment (JRE) - It includes:


i. Java Development Kit (JDK)
ii. Java Application Programming Interface (API)

Java API:
Also known as Java Standard Library (JSL). It includes several classes and methods grouped into packages that
(20)
can be used in Java programs. Some commonly used packages are:
i. Language support package (java.lang)
ii. Input/Output package (java.io)
iii. Utilities package (java.util)

Java Virtual Machine (JVM) - It is an abstract machine which consists of bytecodes and exists as a .class file.
The bytecodes are always exactly the same for any platform. These bytecodes are translated into machine codes by
the Java interpreter of the host machine. JVM along with Java API form the Java platform.
Java Program Java Compiler Bytecode

Source code
Virtual Machine

Machine Code Java Interpreter

Real Machine
Java Virtual Machine
Structure of a Java Program:
SNo. Section Name Priority Example
1. Documentation Optional // …. , /* .… */, /**….*/
2. Package stmt. Optional package MyPack ;
3. Import stmt. Optional import java.util.Date ;
4. Interface Optional interface Area { …. }
5. Class definition class Prime {
Optional
…………. }
6. Main method class class First {
{ public static void main (String args[ ]) throws Exception
Essential
//main() method def. { …… }
}

Java Program Implementation: It includes:


i. program creation
ii. compilation
iii. execution Source Code . java

Java Compiler

Bytecode (Java VM) . class

Java Interpreter

Machine Code Output


Implementing a Java Program

Bytecode: The Java compiler converts the source code (the .java file) into an intermediate virtual machine code called
bytecode. The bytecode is machine independent and therefore can be run on any machine. It is then translated into host
machine code by the Java interpreter.
(21)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

JAVA FUNDAMENTALS
Data Types

 
Primitive or Intrinsic Reference or Derived
 
   
Numeric Non-Numeric Pre-Defined User-Defined
 char String Array
   boolean Vector Class
Integral Real Interface
byte float
short double
int
long
Primitive Data Types
Type of Data Keyword Size (in bits) Numerical Range Remarks

Boolean boolean 1 bit true or false


Character char 16 (2) 0 to 216 -1 Unicode
byte 8 (1) -27 to 27 -1
short 16 (2) -215 to 215 -1
Integral
int 32 (4) -231 to 231 -1
long 64 (8) -263 to 263 -1
float 32 (4) single precision values
3.4 x 10-38 to 3.4 x 1038
Fractional
double 64 (8) double precision values
1.7 x 10-308 to 1.7 x10308

Tokens

Token Description Examples Used as/in


Reserved words that convey a special float, int, class Data types
Keywords
meaning to the language. public, final, private Access modifiers

User–defined names that uniquely rollNo, name Variable names


Identifiers identify a variable ,class, array, method Prime, Quad Class names
etc. getData( ) Method name
‘A’, ‘\n’, ‘@’ Characters
Literals /
Fixed data values used in a program. 12.5f, 0.25F Float values
Constants
9999L A long value
{ } braces Stmt. block
Punctuators [ ] brackets Arr. size limit
Symbols used to define the shape of a
or ; semicolon Statement terminator. Expression,
Java program.
Separators
( ) parenthesis Function signature

+, – , * , / >, &&, ==, || Arithmetic operations


Operators Symbols that work on data items.
Comparisons

(22)
Literals or Constants
Literal Type Data type Format Examples
Integer byte, short, int, long Decimal –321, 999L, 0
(Whole numbers without Octal 037, 0435, 0
decimal point.) Hexadecimal 0xA, 0X9f, 0
Floating Point Fractional 1.0f, 0.1,–1.35
(Numbers having decimal double, float Exponential 1.1e+08, 314159–E05
point.) (Scientific)
Graphic ‘@’, ‘5’ ,‘z’,‘+’
Character
char Escape ‘\n’, ‘\t’, ‘\b’
(Unicode chrs. enclosed in ‘ ’)
sequences
String N/A “Hello\n”, “123F”
(sequence of one or more
characters. enclosed in “ ”) String, StringBuffer

Boolean boolean N/A true or false

Variable: It is a symbolic name that identifies a storage location where data value will be stored.
Declaration:
Syntax :- data_type variablename ;
Example : int p ; //declares an integer location p
float x,y ; // multiple declaration
Initialization:
Syntax :- variablename = value ;
Examples :
i) age = 10 ; // age is an integer variable
ii) long val = 25L ; // variable definition
iii) float avg = 0.36f ; // variable definition
iv) int i, j, k ; i = j = k = 1 ; // multiple initialization
v) int x = 5, y = 3, z ; // multiple definition

Dynamic Initialization: It refers to variable definition at point of first use.


class Demo {
public static void main (String args[ ]) {
int a = 5, b = 3 ;
System.out.println(“a=” +a + “b=” +b) ;
// c and d are dynamically initialized
double c = (a+b) / 2.0 ;
double d = Math.pow(c,2) ;
System.out.println(c + “ “+ d) ;
}
}
Symbolic Constant: It is a data value attached with a symbolic identifier, such that it cannot be changed during
program execution.
Syntax: final symbolic-identifier = value ;
where final is a keyword which prevents the contents of the variable from being modified.
For e.g. final double PI = 3.14159 ;

Expression: It is a meaningful combination of operands and operators, written according to the syntax of the language.
Operands may be variables, constants, method calls.

Operator: It is a symbol that performs a specific function on operands.

(23)
Operator Type Symbol Function Usage
Arithmetic +,–,, /, % For mathematical calculations. x+2, 42.5%5 , “Jdk”+“1.5”
Relational <, <=, >, >=, ==, != To compare two or more operands. a<4, x==10 , a!=b
Logical &&, ||, ! To join two or more comparisons. a==b || b==c
Increment ++ To add 1 to an operand. ++i prefix i++ postfix
Decrement -- To subtract 1 from an operand. --i prefix i-- postfix
Comma , For variable definitions s = 0, f = 1
Assignment = For initialization x = 123.4 ; b = –a ;
Compound Perform shortcuts in common a += 2.5 ; a %= 7 ;
+=, –=, =, /=, %=
Assignment programming operations. a /= 10 ;

. (Dot) To access class members. System.out.println( ) ;


Special new For object creation a = new int[5] ;
(type) Cast To convert a value to a specific type. x = (int) 2.4 ;

Types of Operators

Evaluation of an Expression - Operator Precedence and Associativity:


Precedence determines the order in which operators are applied in an expression. Associativity determines the
operating order of operators of same precedence.
E.g. 1: If t = 2, n = 3, then evaluate t += n++ + ++n
Solution:
t = t + (n++ + ++n)
= 2 + (3++ + ++n)
= 2 + (3 + ++4)
= 2 + (3 + 5)
t = 10
E.g. 2: If a = 10, then evaluate a += ++a + a++
Solution:
a = a + (++a + a++)
= 10 + (++10 + a++)
= 10 + (11 + 11++)
= 10 + (11 + 11)
a = 32
E.g. 3: If a = 5, b = 10, c = –6, then find x, where x = b – a >15 && c + a<0 || a>0
Solution:
x = 10 – 5 >15 && –6 + 5 < 0 || a > 0
= 5 >15 && –1< 0 || 5 >0
= F || T
x= T

Type Conversion: An arithmetic expression is of two types:-


i) Pure or Single Mode Expression: Operands are of same data type. For e.g., 15/10, 4.5/1.5
ii) Impure or Mixed Mode Expression: Operands are of different data type. For e.g., ‘A’+3, 15/1.5. Such
operands are converted before evaluation, to maintain compatibility between data types.
The process of converting one pre-defined type into another is called Type Conversion.

Implicit Type Conversion:


It is performed by the compiler according to Java’s type promotion rules. Hence, it is also called Automatic type
conversion.

(24)
char  byte  short  int  long  float  double
The automatic promotion of data type is known as Coercion. For e.g.
double x = (1/2 + 3.5)  2.0 ;
= (0 + 3.5)  2.0 [int / int = int]
= (0.0 + 3.5)  2.0 [int  double]
= 3.5  2.0
x = 7.0

Explicit Type Conversion:


It is forcefully performed by the user between two incompatible types, using a cast operator. Hence, it is also called
Type Casting.
Syntax: (cast-type) expression
For e.g. double x, y = 27.6 ;
x = (int) (y + 0.5) ; // 28.0
Type casting may result in loss of information such as:
i) truncation of fractional part (double/float  int)
ii) rounding of digits (double  float)
iii) dropping of excess higher order bits (long int)

Standard I/O in Java:


Java performs I/O through streams. The java.io package contains three pre-defined standard streams for managing
I/O operations:
i) System.in , for standard input.
ii) System.out , for standard output.
iii) System.err , to output error messages.

Standard Output: Output at the console is accomplished by two methods defined by standard output, System.out.
Syntax :
System.out.print( [“message”] [+variable] ) ;
System.out.println( [“message”] [+variable] ) ;

For e.g., System.out.println(sum) ;


System.out.print(“\nSum= “ +sum) ;

Standard Input using Scanner:


The Scanner class of java.util package can be used for input processing from a keyboard, a file or a String. The
following Java statement creates a Scanner object for keyboard input:
Scanner sc = new Scanner (System.in) ;
• System.in refers to standard input device (i.e. the keyboard) which is connected to the Scanner class.
• sc is a Scanner object which inputs primitive values or String using its methods.

The Scanner’s nextX( ) methods given below are used to read the value of the desired type from the input stream.

Method Use
next( ) Inputs a string.
nextInt( ) Inputs an integer.
nextLong( ) Inputs a long integer.
nextFloat( ) Inputs a float value.
nextDouble( ) Inputs a double value.
nextLine( ) Inputs a sentence.
nextBoolean( ) Inputs a Boolean value.

(25)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

CONTROL FLOW STRUCTURES


Statement Block: It is a group of zero or more statements between a pair of curly braces ({ }), that behave as a
logical unit. For e.g., class definitions, bodies of methods, loops, decisions etc.

Conditional Statements:-

The if-else statement:


Syntax: if (condition) // here condition is a test–expression of boolean type.

{
//….statement Block
}
[else {
//….statement Block
}
]
For e.g. // To test the validity of a triangle (usage of if–else)
……..
if(a+b > c && b+c > a && c+a > b)
System.out.println(“Valid sides”) ;
else System.out.println(“Invalid sides”) ;

The Conditional Operator (?:):


It is also known as ternary operator as it works on three operands. It can be used in place of if–else statement as its
alternative.
Syntax: expr1 ? expr2 : expr3 ;
where, expr1 is a condition of boolean type.
expr2 is evaluated if expr1 is true, otherwise expr3 is evaluated.
E.g. 1: x =700, y =300
x = x + (x + y<500 ? 500 : 150) ;
E.g. 2: System.out.println((x%2==0) ? x  x : x  x  x) ;
E.g. 3: max = (a>b && a>c) ? a : (b>c) ? b : c ;

Nested if:
if (y%4= =0) // outer if
if (y%100!=0) // inner if
It is equivalent to if (y%4= =0 && y%100!=0)

Dangling else Problem:-


It is an ambiguous situation that arises, when in a nested if statement, number of if’s is more than the number of else
clauses. For e.g.
x = 5, y = 4, z = 0
if (x<5) // outer if
if (y>4) z+=1 ; // inner if
else // dangling else
z+=2 ;
System.out.println(“z= “ +z) ;
(26)
Output: z = 0 (not 2 as expected, due dangling else)

Cause and solution: The dangling else, by default always refers to the nearest preceding if statement, that does not
have a matching else associated with it. The dangling else problem can be overridden by using a statement block.

The if – else – if ladder:


The if–else–if ladder is typically made up multiple conditional blocks.The optional else clause, if used acts as a default
statement, that gets executed when none of the conditions is true.

// Usage of if–else–if ladder (character classification)


import java.util. ;
class Test {
public static void main(String args [ ]) throws Exception {
char c ;
Scanner sc = new Scanner(System.in) ;
c = sc.next( ).charAt(0) ; // input a character
if(c >= ‘A’ && c <= ‘Z’)
System.out.println(“Uppercase letter”) ;
else if(c >= ‘a’ && c <= ‘z’)
System.out.println(“Lowercase letter”) ;
else if(c >= ‘0’ && c <= ‘9’)
System.out.println(“Digit”) ;
else if(c == ‘ ’ || c== ‘\t’)
System.out.println(“White space”) ;
else
System.out.println(“Special character”) ;
} // end of main
} // end of main class

The switch–case statement:


Syntax: switch (expression)
{
case value1:
Statement sequence1 ;
break ;
case value2:
Statement sequence2 ; break ;
................
case valueN:
Statement sequenceN ; break ;
[default :
//….statement Block
]
}
i) The value of the expression and the case values (called case labels) must be constants of integer type (byte,
short, int or char).
ii) The break statement is optional. It is needed to end the switch block, once a statement sequence executes.
iii) In absence of a break statement, the case statements fall through. i.e. all cases below the matching case
execute sequentially, until a break or the end of switch is reached.
iv) The default clause is optional and may be used anywhere in the switch. It corresponds to the else block in an
if–else–if ladder, when used at the last.

(27)
// E.g.: Temperature conversion as per user’s choice (usage of switch–case statement)
import java.util. ;
class Convert {
public static void main(String args[ ]) throws Exception {
double temp, ans = 0.0;
int ch;
Scanner sc = new Scanner(System.in) ;
//…….display menu options
System.out.println(“1. Celsius to Fahrenheit”) ;
System.out.println(“2. Fahrenheit to Celsius”) ;
System.out.print(“\nEnter your choice – 1/2”) ;
ch = sc.nextInt( ) ; // user’s choice
System.out.println(“\nEnter temperature”) ;
temp = sc.nextDouble( ) ;
switch(ch)
{
case 1:
ans = temp*1.8 + 32 ;
break;
case 2:
ans = (temp-32) / 1.8 ;
break;
default:
System.out.println(“Invalid Choice”) ;
System.exit(0) ; // exits from the program
} // end of switch
System.out.println(“Ans= “ +ans) ;
} // end of main
} // end of class

Looping Statements:-
Elements of a Loop:
i) Initialization (simple assignment expression like i = 0, j = i)
ii) Termination (test expression like i < 5, j < i)
iii) Updation (compound assignment expression like ++i, i /= 2)
iv) Loop body (Java statements)

The for loop:


initialization termination updation
  
For e.g for (i = 0 ; i<10 ; i++)
System.out.print(“ “+i) ; // loop body

Output: 0 1 2 3 4 5 6 7 8 9

Variations in for loop:

1. Definition of control variable inside loop:


for (int i = 0 ; i <10 ; i++) System.out.print(“ “+i) ;

2. Multiple variable assignments inside loop:


for (i = 1, j = 20, s = 0 ; i<=10 && j<10 ; i++, --j) s+=i ;

(28)
3. Parts of for loop are optional:
i) int i = 0 ; // initialization
for ( ; i<10 ; ) {
System.out.print(“ “+i) ;
i++ ; // updation
}
ii) int i = 0 ; boolean finish = false ;
for ( ; !finish ; ) {
System.out.print(“ “+i) ;
i++ ;
if(i > 9) finish = true ;
}
iii) for (i = 0 ; ++i<10 ; ) System.out.print(“ “+i) ;

4. Time–Delay (or Empty) loop: a loop with missing body.


for (int i = 10000 ; i>0 ; i—) ; // null statement
5. Infinite loop: a loop with missing termination or update expression
for (; ;) {
//… loop body
}

The while loop:


For e.g., int i = 0; // initialization
while (i<10) // test–expression
{
System.out.print(“ “+i) ;
i++ ; // updation
}
Output: 0 1 2 3 4 5 6 7 8 9
Variations in while loop:
1. int i = 100, j = 200 ;
while (++i < —j) ; // null statement – Empty loop
System.out.println(“Midpoint: “ +i) ; // 150

2. int i = 0 ;
while (++i <= 9) System.out.print(“ “+i) ;

3. while (true) { // infinite loop


//……
}

The do while loop:


For e.g., int i = 0 ; // initialization
do {
System.out.print(“ “+i) ;
i++ ; // updation
} while (i<10) ; // test–expression
Output: 0 1 2 3 4 5 6 7 8 9

Nested Loop (a loop within a loop):


i) Loop control variables of each loop should be different.
ii) The inner loop executes faster then the outer loop. Hence the inner loop terminates before the outer loop.
iii) The loops should be properly indented, so as to avoid confusion regarding their bodies.
(29)
class Nested {
public static void main(String args[ ]) throws Exception {
int i , j ;
for (i = 1 ; i<=4 ; i++) // outer loop
{ // start of outer for loop
for (j = i ; j>0 ; j--) // inner loop
{ // start of inner for loop
System.out.print( j ) ;
} // end of inner for loop
System.out.println( ) ;
} // end of outer for loop
}
}
Comparison of Loops:
i) In entry–controlled loops (for, while), control conditions are tested before the start of loop execution.
ii) In an exit–controlled loop (do–while), control condition is tested at the end of the loop, as a result the loop
body executes unconditionally for the first time.
iii) The for loop is usually used when the number of iterations are fixed in advance.
iv) The while loop is used when the number of iterations are unpredictable, before its execution.
v) The do–while loop is used when the number of iterations are unknown, but still the loop should iterate at least
once.

Jump Statements:-
The break statement:
It causes an exit from a switch block or loop, and transfers the control to the statement following the terminated
control structure. For e.g.
for (int m = 50 ; ;)
{
if (m<10) break ;
m = m-10 ;
}
System.out.println(“m= “ +m) ;

Output: m = 0
When used inside a nested loop, the break statement terminates the loop in which it appears.

The continue statement:


It causes the loop to continue with the next iteration, after skipping some statements in between. For e.g.
for (int i =1 ; i<=20 ; i++)
{
if (i % 5 == 0) continue ;
System.out.print (i +” “) ;
}
Output: 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19

(30)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

CLASSES IN JAVA I(METHODS)


Class Basics:
i) A class defines a user–defined data type that is used to produce objects. Hence, it is considered as an object
factory.
ii) A class is a blueprint (or template) for an object. Hence, it reserves no space in memory.
iii) The framework of a class is based on logically related elements of different data types. Hence, class is referred
to as composite data type.

Class Structure: A class may contain 3 kinds of members:


1. Data fields or variables which may be
Instance variables
Class variables
2. Operations or methods which may be
Instance methods
Class methods
3. Constructors

Class Definition Format:


class <classname> {
[variable declarations ;] Data members
[classname([ parameter–list ]) Constructor
{
//…..constructor definition
}]
[type methodname([ parameter–list ]) { Method
//…..method definition(s)
}
} where, classname identifies an ADT..

Variable or Data Declaration Syntax:


[static] type var1,[var2,var3,….varN] ;
For e.g.
class abc {
int num, sum ; // instance variable
static int count = 0 ; // class variable
.......
}
Instance variable Class variable

Declared without the static keyword. Declared with static keyword.

Created with each class instance. Created only once, when the class is first referred to.

All class instances have an individual copy. All class instances share a single copy.

Method or Function: Methods define the set of operations to be performed on objects.


Need of a Method:-
i) It reduces complexity by breaking the program into smaller units.
ii) It enables reusability of code.
(31)
iii) It checks repetition of code.

Parts of a Method:- A function consists of:


i) Definition
ii) Declaration
iii) Calling
// Structure of a function-oriented program
class abc {
void sqr(int x) Function declaration
{
System.out.println(x  x) ; Function definition
}
public static void main(String args[ ])
{
abc ob = new abc( ) ; // object creation
ob.sqr(5) ; Function calling (by object)
……………
}
}
Method Definition:
General form(Syntax):
modifier type func-name parameter
   
static float add(float a, float b) // a static method
{
return (a+b);
}
void abs(int a) // a non-static or instance method
{
System.out.println(a<0 ? -a : a) ;
}
Method Declaration: It is the first line of function definition.
Function Declaration = Return type + Function signature (= method name + parameters)

Objects:
i) An object is a concrete abstract representation of real–world entity.
ii) The state of the object is the data that it contains in its instance variables while the behavior of an
object is specified in its methods.
iii) Objects differ from each other by their state as the instance variables can take different values for each object.
object constructor
 
Creation Syntax: classname <classvar> = new classname( ) ;

reference declaration memory allocation


The new operator instantiates a class (i.e. allocates memory) and returns the reference to the newly created object.
For e.g. Box b = new Box( ) ;
The object creation process can also be written individually as:
Box b ; // declares a null reference
b = new Box( ) ; // creates and assigns an object reference

Method Calling Syntax:


i) object . methodname([args-list]) ; // instance method call
(32)
ii) class . methodname([args-list]) ; // class method call
iii) methodname([args-list]) ; // nested method call

// Accessing class methods


import java.util. ;
class Sphere { // class definition
int radius ; // instance variable
double area ; // instance variable
void input( ) throws Exception {
Scanner sc = new Scanner(System.in) ;
System.out.print(“Enter radius “) ;
radius =sc.nextInt( ); // instance variable access
}
void calcArea( ) { // instance method definition
double rsqr ;
rsqr = Math.pow(radius, 2) ; // class method call
area = 4  3.14  rsqr ;
}
void display( ) {
System.out.print(“Radius =” +radius) ;
System.out.print(“Area =” +area) ;
}
public static void main(String args[ ]) throws Exception
{
Sphere ob = new Sphere( ) ; // ob is class instance
ob.input( ) ; // instance method call
ob.calcArea( ) ; // instance method call
ob.display( ) ; // instance method access
} // end of main
} // end of main method class

Impure Method
They are methods that bring about a change in the state of an object or a parameter. Such methods usually do not return
values and hence, they are of void type. For e.g., procedural methods, mutator methods.

Pure Methods
They are methods that do not change state of an object or a parameter. Such methods always return values (using a
return statement), either of a simple or reference type. For e.g., computational methods, boolean methods, accessor
methods.
The return statement in a pure method has two uses:
i) It causes an immediate exit from a method and the control passes back to the calling function.
ii) It returns a value to the calling function.
// Pure and Impure methods
class Method {
void change (int x, int y) { // impure method
x=x+y;
y=x-y;
x=x-y;
}
int square (int a) { // pure method
return (a  a) ;
}
} // end of class
(33)
Argument Passing in Methods:
i) Pass (Call) by Value:- In pass–by–value, the value of an actual argument is copied into the formal parameter of the
method. Hence, changes made to the formal parameter have no effect on the arguments used to call it.
ii) Pass (Call) by Reference:- In pass–by–reference, a reference to the actual argument is passed to the formal
parameter.Hence, any changes made to the formal parameter will effect the arguments used to call it.
iii) Simple types are passed by value, while composite types are passed by reference.

Scope Rules of Variables: The scope of a variable determines where in a program, the variable is usable or accessible.
i) General Scope Rule:– A variable declared inside a statement block is accessible only in that block and any block
nested inside it.
ii) Lifetime:– A variable loses its value, once it goes out of scope. Hence, the lifetime of a variable is confined to its
scope.
Variable Type Scope Defined Visibility Lifetime

Instance variable Block Inside a class. Accessible to all method Created when object is
blocks inside the class. instantiated and destro-
yed when object goes
out of scope.
Local block variable Block Inside a statement block. Accessible only in the Created when program
statement block in which control enters the block
declared. and destroyed when it
leaves the block.
Local variable Local Inside a method. Accessible only in the Exists when a method is
method in which called and destroyed
declared. when the method termi–
nates.
Class variable Global Inside a class as static. Accessible to all objects Created before a class is
of the class. instantiated.

Note:- A local variable has a higher precedence over instance variable. Hence, a local variable hides the instance
variable, when both have the same name.

Constructors: A constructor is a special method that initializes an object’s internal state, immediately after its creation.
Syntax: class <classname> {
//…instance variable declarations
classname([ parameter–list ])
{
//…constructor body
}
//…..
}
Characteristics:-
i) It is called automatically called when the object is created.
ii) It has the same name as the class in which it resides.
iii) It has no return type, not even void, since the implicit return type of a constructor is the class type
itself.
Default Constructor - A default (or non–parameterized) constructor performs default initialization for instance variables
of the class. For e.g.
class Account {
int anum ; String aname ;
Account( ) { // explicit default constructor
System.out.println(“Creating Account”) ;
anum = 0 ; // default numeric value
aname = “” ; // default string value – null reference
(34)
}
//……..
}
class Demo {
public static void main(String args[ ]) throws Exception {
Account a = new Account( ) ; // object created, constructor called
//……..
}
}
Parameterized Constructor: It performs initialization of objects, using user–defined values. For e.g.
class Clock {
int hrs, min, sec ;
Clock(int h, int m, int s ) { // parameterized constructor
System.out.println(“Validating Time”) ;
hrs = h>=0 && h<24 ? h : 0 ; // validating hrs
min = m>=0 && m<60 ? m : 0 ; // validating min
sec = s>=0 && s<60 ? s : 0 ; // validating sec
}
……..
}
class Demo {
public static void main(String args[ ]) throws Exception {
Clock t = new Clock(10,20,15) ; // parameterized constructor calling
//……..
}
Constructor Overloading: Defining more than one constructor in a class, which differ in their signatures is called
constructor overloading. For e.g.
class Box {
private int width, len, depth ;
Box( ) { // constructor 1 (0 - arg)
System.out.println(“Uninitialized Box”) ;
width = len = depth = 0 ;
}
Box(int l) { // constructor 2 (1- arg)
System.out.println(“Cubed Box”) ;
width = len = depth = l ;
}
Box(int w, int l, int d) { // constructor 3 (3 - args)
System.out.println(“Cuboid Box”) ;
width = w ; len = l ; depth = d ;
}
int vol( ) {
return (width  len  depth) ;
}
public static void main(String args[ ]) throws Exception
{
Box x = new Box(10,2,15) ; // uses constructor 3
Box y = new Box( ) ; // uses constructor 1
Box z = new Box(6) ; // uses constructor 2
System.out.println(“\nVol of Box X= “ +x.vol( )) ;
System.out.println(“\nVol of Box Y= “ +y.vol( )) ;
System.out.println(“\nVol of Box Z= “ +z.vol( )) ;
}}// end of class
(35)
Nested Method Calling:-
// To find the lcm of 2 nos. (nested method call)
import java.util. ;
class Lcm { // class definition
int a, b, lcm ; // instance variable
Lcm(int x, int y) { // parameterized constructor
a=x;
b=y;
}
int calcHcf( ) { // finds hcf
int h, i, c ;
c=a<b?a:b;
for(i = c ; i >= 1 ; i—)
if(a % i == 0 && b % i == 0) { h = i ; break ; }
return h ;
}
void calcLcm( ) { // finds lcm
int h = calcHcf( ) ; // nested method call
lcm = (a  b) / h ;
}
void display( ) {
System.out.print(“Lcm =” +lcm) ;
}
public static void main(String args[ ]) throws Exception {
Lcm ob = new Lcm(3,5) ; // ob is class instance
ob.calcLcm( ) ;
ob.display( ) ; // instance method call
} // end of main
} // end of main method class
The this variable:
i) It holds an implicit reference of the object that invoked a method (i.e. the current object).
ii) It is explicitly used inside the method to access members of the current object.
iii) It is automatically activated whenever a method of a class is called.
iv) The this variable can be used to resolve name space collisions that might occur between instance variable and
local variable of same name.
class Rectangle {
double width,height ;
Rectangle(double width, double height) {
this.width = width ;
this.height = height ;
}
//……..
}
class Demo {
int x = 10 ;
void display( ) {
int x = this.x++ ;
System.out.println(x + “ “ + this.x) ;
}
}

(36)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)

METHODS
Methods define the set of operations to be performed on objects. They are statement blocks, which usually:
i) perform complex abstract actions
ii) change the state of an object
iii) determine the state of an object
Methods may belong to:
i) an instance of a class – Instance or Non–static method.
ii) a class in a package – Class or Static method.

Method Definition:
General form(Syntax):
modifier type func-name parameter
   
static float add(float a, float b) // a static method
{
return (a+b);
}
void abs(int a) // a non-static or instance method
{
System.out.println(a<0 ? -a : a) ;
}
Method Calling or Invocation:
A method can be called by simply using:
i) the method–name with an object. E.g. an instance method call inside the main method.
ii) the method–name with a class name. E.g. a static method call outside its class like Math.sqrt( ).
In addition to this, parameters (if any) may be passed to the called function.

// To print Armstrong numbers between a and b


import java.util. ;
class Arm {
int process(int m) { // called instance method
int s = 0, d ;
for(int i = m ; i > 0 ; i /=10) {
d = i%10 ;
s += (int) Math.pow(d, 3) ; // class method call
}
return s ;
}
public static void main(String args[ ]) throws Exception // calling method
{
Scanner sc = new Scanner (System.in) ;
int a, b, sum ;
Arm ob = new Arm( ) ; // object creation
System.out.println(“Enter lower and upper limits”);
a = sc.nextInt( ) ;
b = sc.nextInt( ) ;
for(int i = a ; i <= b ; i++)
(37)
{
sum = ob.process( i ) ; // object calling instance method
if(sum == i) System.out.println( i ) ;
}
} // end of main
} // end of class

Method Return Types:


The return type of a method depends on whether:
i) the method causes side effects – An impure method.
ii) the method returns values, but has no side effects – A pure method.

Impure Method
They are methods that bring about a change in the state of an object or a parameter. Such methods usually do not return
values and hence, they are of void type. For e.g., procedural methods, mutator methods.

Pure Methods
They are methods that do not change state of an object or a parameter. Such methods always return values (using a
return statement), either of a simple or reference type. For e.g., computational methods, boolean methods, accessor
methods.
The return statement in a pure method has two uses:
i) It causes an immediate exit from a method and the control passes back to the calling function.
ii) It returns a value to the calling function.

Method Parameters:
A parameter is a variable that contains an argument or a value to be used in a method. It may be of 2 types:
Implicit or First parameter : always refers to a class instance which invokes a method.
Explicit or Second parameter : defines a variable which is used to transfer data to a method. It may appear in :
a function call to send the data – called an actual parameter.
a function definition to receive the data –called a formal parameter.
object . prime(n)
 
Implicit parameter Explicit Parameter
Impure methods change the state of a formal parameter by altering its value. This change is sometimes referred as side–
effect of an impure method.
// Pure and Impure methods
class Method {
void change (int x, int y) { // impure method
x=x+y;
y=x-y;
x=x-y;
}
int square (int a) { // pure method
return (a  a) ;
}
} // end of class

Argument Passing in Methods:


An argument may be of:
i) a simple type (char, int, float, double etc.) or
ii) a composite type (objects, arrays)
An argument may be passed to a method:
i) By Value – Pass (Call) by Value
(38)
ii) By Reference – Pass (Call) by Reference
Simple types are passed by value, while composite types are passed by reference.

// Passing arguments by value or reference


class Fun {
// passing primitive types as arguments
void swap(int x, int y) { // pass by value
int tx = x, ty = y ;
x =ty ; y = tx ;
System.out.println(“swap: x= “+x + “, y= “ +y) ;
}
// passing a composite type as argument
void exchange(int b[ ]) { // pass by reference
int t1 = b[0], t2 = b[1] ;
b[0] = t2 ; b[1] = t1 ;
}
public static void main(String args[ ]) throws Exception {
int x = 3, y = 2 ; // primitive type
int a[ ] = { 5, 3 } ; // composite type
Fun ob = new Fun( ); // object creation
System.out.println(“\nCall by Value”);
System.out.println(“main: x= “+x + “, y= “+y) ;
ob.swap(x,y) ; // call by value
System.out.println(“main: x= “+x + “, y= “+y) ;
System.out.println(“\nCall by Reference”) ;
System.out.print (“Before call: a[0]= “+a[0]) ;
System.out.println(“, a[1]= “+a[1]) ;
ob.exchange(a) ; // call by reference
System.out.print(“After call: a[0]= “+a[0]) ;
System.out.println(“, a[1]= “+a[1]) ;
} // end of main
} // end of class

i) In pass–by–value, the value of an actual argument is copied into the formal parameter of the method. Hence,
changes made to the formal parameter have no effect on the arguments used to call it.
ii) In pass–by–reference, a reference to the actual argument is passed to the formal parameter. Hence, any
changes made to the formal parameter will effect the arguments used to call it.

Method Overloading:
When two or more methods in a class share the same name, but their signatures (parameter declarations) are different,
the methods are said to be overloaded, and the process is referred to as method overloading.

// To find area of square or rectangle using a overloaded method


import java.util. ;
class AreaOvl {
float area(float a) { // area of square
return (a  a) ;
}
float area(float a, float b) { // area of rectangle
return (a  b) ;
}
public static void main(String args[ ]) throws Exception {
float a, b ;
(39)
int choice ;
Scanner sc = new Scanner (System.in) ;
AreaOvl ob = new AreaOvl( ) ; // object creation
System.out.println(“1. Area of Square”) ;
System.out.println(“2. Area of Rectangle”) ;
System.out.println(“\nEnter choice “) ;
ch = sc.nextInt( ) ;
a = b = 0.0f ;
switch(ch)
{
case 1:
a = sc.nextFloat( ) ;
System.out.println(“\nArea= “ +ob.area(a)) ;
break ;
case 2:
a = sc.nextFloat( ) ;
b = sc.nextFloat( ) ;
System.out.println(“\nArea= “ +ob.area(a,b));
break ;
} // end of switch
} // end of main
} // end of class

(40)

You might also like