Basic of Java and Fucntion Theory Class 11
Basic of Java and Fucntion Theory Class 11
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.
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
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 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
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 Compiler
Java Interpreter
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
Tokens
(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
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
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.
(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 ;
Types of Operators
(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
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] ) ;
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)
Conditional Statements:-
{
//….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”) ;
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)
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.
(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)
Output: 0 1 2 3 4 5 6 7 8 9
(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) ;
2. int i = 0 ;
while (++i <= 9) System.out.print(“ “+i) ;
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.
(30)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)
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.
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( ) ;
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.
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
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.
(40)