BSC Final All Units Notes PDF
BSC Final All Units Notes PDF
BSC Final All Units Notes PDF
short: short is signed 16 b it type. It has range from -215 to 215-1. The short variables are
declared by use of short keyword.
eg: short s;
int: The most commonly used integer type is int. It is a signed 32 bit type that a range from
-231 to 231-1. In addition to other uses, variables of type int are commonly employed to
control loop and to index arrays. ‘int’ type is most versatile & efficient type. int variables are
declared by use of ‘int’ keyword.
eg: int a;
long: long is a signed 64 bit type and is useful for those occasions where an int type is not
large enough to hold the desired values. The range of long is quite large. It has range from
-263 to 263-1. long variables are declared by use of ‘long’ keyword
eg: long a;
Floating point types:
Floating point numbers are used when evaluating expressions that require fractional
precision. There are two kinds of floating point types, float and double. Which represent
single and double precision numbers respectively.
Type Size Range
float 4 bytes 1.4e-045 to 3.4e+038
short 8 bytes 4.9e-324 to 1.8e+308
float: the type float specifies a single precision value that uses 32 bits of storage. Single
precision is faster on same processors and takes half as much space as double precision. float
variables are declared by use of ‘float’ keyword.
eg: float a=1.234;
double: double precision, as denoted by the double keyword, uses 64 bits to store a value. All
transcendental math functions such as sin(), cos() and sqrt() return double values. double
variables are declared by use of ‘double’ keyword.
eg: double d;
char: In java, the datatype used to store characters is char. Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the
characters found in all human languages. Thus in java char is a 16bit type. The range of char
is 0 to 65536. There are no negative chars. char variables are declared by use of char
keyword.
eg: char c;
boolean: Java has a simple type called boolean, for logical values. It can have only one of
two possible values, true or false. This is the type returned by all relational operators such as
a<b. Boolean is also the type required by conditional expressions that govern the control
statements such as ‘if’ and ‘for’. boolean variables are declared by use of ‘boolean’ keyword.
eg: boolean b; b=false;
A virtual machine code is not machine specific. The code generated by the java interpreter
by acting as an intermediary between the virtual machine and real machine.
4. Implementing a java program:
Implementation of java application program involves a series of steps. They include
● Creating the program
● Compiling the program
● Running the program
Remember that, before we begin creating the program, JDK must be properly installed on our
system.
Creating the program:
We can create a program using any text editor
class Sample
{
public static void main(String arg[])
{
System.out.println(“Hi friend”);
}
}
We have to save this program with a name like prog.java
A java Application have any no of classes, but only one main class. Main class is nothing but
class which contains main() method
Now, the interpreter looks for the main method in the program and begins execution from
there. When executed our program displays the following
o/p: Hi friend
Documentation section:
This section comprises of a set of comment lines giving the name of program, the author &
other details, which the programmer would like to refer at later stage. It is suggested one.
Package statement:
The first statement allowed in java is a ‘package’ statement.
This statement declares a package name and informs the compiler that the classes defined
here belong to this package.
Eg: package student;
It is optional section.
Import statement:
This is similar to the #include statement in C
Eg: import java.io.*;
It is optional section.
Interface statement:
An interface is like a class but includes a group of method declarations. It is also optional
section and is used only when we wish to implement the multiple inheritance feature in
jprogram.
Class Definitions:
A java program may contain multiple class definitions. Classes are the primary & essential
elements of a java program.
Main Method Class:
Since every java stand alone program requires a main method as its starting point, this class is
the essential part of a java program.The main method creates objects of various classes and
establishes communications between them. On reaching the end of main, the program
terminates and the control passes back to the operating system.
6. COMMAND LINE ARGUMENTS:
Sometimes we will need to supply data into a java program when it runs. This type of data
will be supplied in the form of command line arguments. The command line arguments will
immediately follow the program name on the command line. These command line arguments
will be collected into an array of string which is supplied as a parameter to main methods.
Later these command line arguments must be processed and then accessed. The
following program takes command line argument and prints them.
Eg: class Display
{
public static void main(String args[])
{
for(i=0;i<args.length();i++)
System.out.println(args[i]);
}
}
c:\> javac file.java
c:\> java Display hi this is ur friend
o/p-> hi
this
is
ur
friend
7. VARIABLES:
A variable is an identifier that denotes a storage location used to store a data value. All
variables have a scope, w hich defines their visibility and a lifetime.
Declaring variable:
All variables must be declared before they can be used. The basic form of a variable
declaration is , type identifier[=value][, identifier [=value]… ];
Eg: int value;
float avg;
in the above example, ‘value’ is an integer type variable , where as ‘avg’ is float type
variable.
To declare more than one variable of the specified type, use a comma-separated list.
int a,b,c; // declares three integer variables a, b, and c
int d=3,e,f=5; // declares 3 integer variables initializing d and f
Unlike in C, variable can be declared any where in the program, where ever they are needed.
Dynamic Initialization:
Although the preceding examples have used only constants as initializers, java allows
variables to be initialized dynamically, using any expression valid at the time the variable is
declared.
For example,
Class DynInit
{
Public static void main(String arg[])
{
double a=3.0, b=4.0;
double c=Math.sqrt(a*a+b*b); // c is dynamically
initialized
System.out.println(“Hypotenuse is ”+c);
}
}
Here, three local variables a, b, c are declared. The two a and b are initialized by constants.
However c is initialized dynamically.
8. Classification of variables:
Java variables are actually classified into three kinds:
● Instance variables
● Class variables
● Local variables
Instance variables are created when the objects are instantiated and therefore they are
associated with the objects.They take different values for each object.
Class variables are global to a class and belong to the entire set of objects that class creates.
Only one memory location is created for each class variable.
● Instance and class variables are declared inside a class.
Local variables are declared and used inside methods and program blocks(defined between
opening brace { and a closing brace} ). These variables are visible to the program only from
the beginning of its program block to the end of the program block.
9. Scope and lifetime of variables:
Scope of variables: Scope is defined as an area of the program where the variable is
accessible. As a general rule, variables declared insid a scope are not visible to code that is
defined outside that scope.
Scopes can be nested. For example, each time you create a block of code, you are creating a
new, nested scope. When this occurs, the outer scope encloses the inner scope.This means
that objects declared in the outer scope will be visible to code within the inner scope.
However the reverse is not true. Objects declared with in the inner scope will not be visible
outside it.
// program to demostarte block scope
class scope
{
public static void main(String ar[])
{
Int x; // known to all code with in main
x=10;
if(x==10)
{
Int y =20; // known only to this block
System.out.println(“x and y: ”+x+” ”+y);
x=y*2;
}
y = 100; // Error! y not known here
System.out.println(“x is ”+x); // x is still known here
}
}
As the comments indicate, the variable x is declared at the start of main()’s scope and is
accessible to all subsequent code within main(). y is only visible to the code in if block .
Lifetime of variables:
Varaibles are created when their scope is entered, and destroyed when their scope is
left. This means that a variable will not hold its value once it has gone out of scope.
Therefore, variables declared within a method will not hold their values between calls to that
method. Also a variable declared within a block will lose its values when the block is left.
Thus, the lifetime of a variable is confined to its scope.
class Lifetime
{
public static void main(String ar[])
{
int x;
for(x=0; x<3; x++)
{
int y=-1; // y is initialized each time block
is entered
System.out.println(“y is : ”+y); // this
always prints -1
Y=100;
System.out.println(“y is now : ”+y);
}
}
}
The output of above program is :
y is : -1
y is now: 100
y is : -1
y is now: 100
y is : -1
y is now: 100
10. Arrays
An array is a collection of homogeneous data items that share a common name. Arrays of
anytype can be created and may have one or more dimensions. A specific element in an array
is accessed by its index.
One-Dimensional Arrays:
general form of a one-dimensional array declaration is
type var-name[];
eg: int marks[];
and we must use new operator to allocate memory. So the general form of new as it
applies to one-dimensional arrays appears as follows.
type var-name[]=new type[size];
eg: int marks[] = new int[20];
}
}
11. Operators
Java supports a rich set of operators. Operators are used in programs to manipulate data and
variables. Java operators can be classified into a number of related categories as below:
1. Arithmetic operators
2. Increment & Decrement operators
3. Relational operators
4. Bitwise operators
5. Logical operators
6. Assignment Operator
7. Conditional Operator
1)Arithmetic operators:
These are used in mathematical expressions in the same way that they are used in
algebra. The following are the list of arithmetic operators:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division (Remainder)
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
3)Relational operators:
The relational operators determine the relationship that one operand has to the other.
The outcome of these operators is a boolean value. The relational operational operators are
most frequently used in the expressions that control the if statement and the various loop
statements. The following are the list of Relational operators:
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
As stated, the result produced by a relational operator is a Boolean value. For example,
int a=4;
int b=1;
boolean c=a>b;
● in this case, the result of a<b(which is true) is stored in c
if(a>b)
{
}
● in this case, a>b results true, so if statement will be executed
Bitwise operators:
Java defines several bitwise operators which can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their operands. The
following are the list of Bitwise operators:
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise XOR
~ bitwise unary NOT
<< shift left
>> shift right
>>> shift right with zero fill
Logical operators:
Logical operators are also called as Boolean Logical operators. They operate on
boolean operands. All of the binary logical operators combine two boolean values to form a
resultant boolean value.
Operator Meaning
&& logical AND
|| logical OR
^ logical XOR
! logical NOT
The logical operators && and || are used when we want to form compound conditions by
combining two or more relations.
for example,
if( a>b && x ==10) { }
A B A&&B A||B A^B !A
true true true true false false
true false false true true false
false true false true true true
false false false false false true
Relational expression:
If we use Relational operators in an expression, that is treated as a Relational expression: Eg:
a>b;
Logical expression:
If we use Boolean logical operators in an expression, that is treated as a logical expression:
Eg: a&&b;
Conditional expression:
If we use arithmetic operators in an expression, that is treated as an Conditional expression.
Eg: a>b? a: b;
… like this, we have some other expressions.
b. do-while statement:
‘do-while’ statement is very much similar to while statement with little difference. In
while statement, if the condition is initially false then the body of loop will not be
executed at all. Where as in do-while statement, body of the loop will be executed at
least once since the condition of do-while is at the bottom of the loop.
Syntax:
do
{
// body of the loop
} while(condition);
Each iteration of do-while executes the body of loop first and evaluates the
condition later. If condition is true, the loop repeats. Otherwise, the loop terminates.
c. for statement:
‘for’ statement also repeats the execution of statements while its condition is true.
Syntax:
for(initialization; condition; iteration)
{
// body of the loop
}
where initialization portion of the loop sets the value of the variable that acts
as a counter. This portion is executed first when the loop starts. And it is executed
only once. when the control goes to condition, condition is evaluated. If condition is
true, the body of loop is executes. Otherwise the loop terminates.Next iteration
portion is executed. This helps to increment or decrement the control variable.
The loop then iterates evaluating condition, then executing the body and then
executing the iteration portion each time it iterates.
2) Jump Statements:
Jump statements allows the control to jump to a particular position. There are 3 types
of jump statements.
a. break statement:
in java, there are 3 uses of break statement.
i. It helps to terminate a statement sequence in switch statement.
ii. It can be used to exit or terminate the loop
iii. It can be used as another form of goto
Eg:
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
if(i==10)
break; // terminates loop if i is 10
System.out.println(“i :”+i);
}
}
}
b. continue statement:
The continue statement starts the next iteration of the immediately enclosing iteration
statements(while, do-while or for). When the control goes to continue statement, then
it skips the remaining statements and starts the next iteration of enclosing structure.
Eg:
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
System.out.println(“i :”+i);
if(i%2==0)
continue;
System.out.println(“ “);
}
}
}
c. return statement:
This is used to return from a method. When the control reaches to return statement, it
causes the program control to transfer back to the caller of the method.
Eg:
class A
{
public static void main(String arg[])
{
boolean t=true;
if(t)
return;
System.out.println(“Hi”); // This won’t execute
}
}
In this example, return statement returns to the java run time system, since the caller
of main() is runtime system.
}
}
Here,
● class is a keyword used to define class
● class name is the identifier that specifies the name of the class
● type specifies the datatype of the variable
● instance_variable1, . . . are the variable defined in the class
● method name is the method defined in the class that can operate on the variables
in the class
Example:
class sample
{
int x, y;
setXY()
{
x=10; y=20;
}
}
The variables defined in the class are called member variables/data members
The functions defined in the class are called member functions/member methods.
Both data members and member methods together called members of class.
}
}
class Demo
{
public static void main(String ar[])
{
Sample s;
s=new String();
s.setXY();
s.printXY();
}
}
19. Constructors
A constructor is a special kind of method that has the same name as that of class in
which it is defined. It is used to automaticallyl initialize an object when the object is created.
Constructor gets executed automatically at the time of creating the object. A constructor
doesn’t have any return type.
Example:
// program to demonstrate constructor
class Student
{
int number;
String name;
Student() // default constructor
{
number=569;
name=”satyam”;
}
Student(int no, String s) // parameterized constructor
{
number=no;
name=s;
}
void showStudent()
{
System.out.println(“number =”+number);
System.out.println(“name =”+name);
}
}
class Demo
{
public static void main(String ar[])
{
Student s1=new Student();
Student s2=new Student(72,”raju”);
s1.showStudent();
s1.showStudent();
}
}
output:number= 569
name= satyam
number= 72
name= raju
Static Blocks:
Just like static variables and static methods we can also create a static block . this static block
is used to initialize the static variables.
Example program:
class UseStatic
{
static int a=3;
static int b;
static void meth(int x)
{
System.out.println(“x=” + x);
System.out.println(“a=” + a);
System.out.println(“b=” + b);
}
static
{
System.out.println(“static block initialized”);
}
output:
static block initialized
x = 69
a=3
b = 12
s.setStudent(69,81,”ramu”);
s.showStudent();
}
}
output:
number=1
marks=89
name=rama
number=69
marks=81
name=ramu
27. Overloading Constructors
Just like member methods constructors can also be overloaded. the following example
demonstrates this,
class Student
{
int no;
String name;
Student()
{
no=70;
name=”ram”;
}
Student(int n, String s)
{
no=n;
name=s;
}
void show()
{
System.out.println(“Number=”+no);
System.out.println(“Name=”+name);
}
}
class Display
{
public static void main(String ar[])
{
Student s1= new Student();
Student s2= new Student(69,”satya”);
s1.show();
s2.show();
}
}
output:
number=70
name=ram
number=69
name=satya
}
}
output:
a and b before call: 10 20
a and b after call: 10 20
29. Recursion
Java supports recursion. It is the process of defining something interms of itself. It is the
attribute that allows a method to call itself. The method that calls itself is said to be recursive
method.
The classic example of recursion is the computation of the factorial of a number.
class Factorial
{
int fact(int n)
{
if(n==1) return 1;
return (fact(n-1)*n);
}
}
class Recursion
{
public static void main(String ar[])
{
Factorial f=new Factorial();
System.out.println(“Factorial of 5 is”+ f.fact(5));
}
}
output above program:
Factorial of 5 is 120
class Display
{
public static void main(String ar[])
{
Outer out=new Outer();
Out.outerMethod();
}
}
output:
In Outerclass Method
In Innerclass Method
outer class variable: 10
Method Task
s2=s1.toLowerCase() converts the String s1 to all lowecase
s2=s1.toUpperCase() converts the String s1 to all Uppercase
s2=s1.replace(‘x’,’y’); Replace all appearances of x with y
s2=s1.trim(); Remove white spaces at the beginning and end of String
s1
s1.equals(s2); Returns ‘true’ if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns ‘true’ if s1=s2, ignoring the case of
characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns –ve if s1<s2, positive if s1>s2, and zero if s1 is
equal s2
s1.concat(s2) Concatenates s1 and s2
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’
in string s1
s1.indexOf(‘x’,n) Gives the position of ‘x’ that occurs after nth position in
the- string s1
Method Task
s1.setCharAt(n,’x’) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n,s2) Inserts the string s2 at the position n of the string s1
s1.setLength(n) sets the length of the string s1 to n. if
n<s1.length() s1 is
truncated .if n>s1.length() zeros are added to s1
INHERITANCE
35. Inheritance:
Inheritance is one of the corner stones of Object oriented programming. Because it
allows hierarchical classifications. In terminology of java, a class that is inherited is called a
super class. The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of super class. It inherits all of the instance variables and methods defined
by the super class and adds its own, unique elements.
36. Hierarchical abstractions
A powerful way to manage abstraction is through the use of hierarchical classification. This
allows to break the complex systems into manageable pieces.
for example, a car is a single object for outside but the car consists of several
subsystems such as steering, breaks, sound system, seat belts etc. Again the sound system
consists of radio, DVD player etc.
Here we manage the complexity of a car system through the use of hierarchical
classification. Here everything we view in this world is an object. The topmost hierarchy for
every object is material object.
Base class:
suppose in the above example, car is the base class. and the sub classes are steering, breaks,
engine etc
The behaviour of the child class is always an extension of the properties of the associated
with the parent class.
37. Subclass:
Consider the relationship associated with the parent class and subclass
● Instances of a sub class must possess all the data areas associated with the parent
class.
● Instances of a sub-class must implement through inheritance at least some or all
functionalities defined for the parent class.
● Thus an instance of a child class can mime the behaviour of the parent class and
should be indistinguishable from the instance of parent class if substituted in similar
situation.
This creates a problem because we use so many forms of inheritance. To solve this, we use
principle of substitutability .
38. Substitutability :
Def: “The principle of substitutability” says that if we have two classes ‘A’ and ‘B’ such that
class B is sub-class of A class, it should be possible to substitute instances of class B for
instance of class A in any situation with no observable effect.
39. Subtype: The term subtype often refers to a subclass relationship in which the
principle of substitutability is maintained.
statically typed languages (C++) place much more emphasis on principle of substitutability
than dynamically typed languages (Small Talk)
The reason for this is the statically typed languages tend to characterize objects by their class
and dynamically typed languages tend to characterize by behaviour.
That is the subtype us determined in statically typed languages by their class and
dynamically typed languages by their behaviour.
40. Forms of inheritance:
Inheritance is used in variety of ways. The following list represents general abstract
categories and is not intended to be exhaustive.
● Single Inheritance:
In a class hierarchy when a child has one and only one parent and parent has
one only child, that inheritance is said to be single inheritance.
eg:
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println(“rollno= ”+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println(“marks= ”+marks);
}
}
class Display
{
public static void main(String ar[])
{
Marks ob=new Marks();
ob.getNo(44);
ob.putNo();
ob.getMarks(66);
ob.putMarks();
}
}
● Multi-level Inheritance
In a class hierarchy, when a class is derived from already derived class then that
inheritance is said to be multi-level inheritance.
eg:
class Student
{
int rollno;
void putNo()
{
System.out.println(“rollno= ”+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println(“marks= ”+marks);
}
}
class Display
{
public static void main(String ar[])
{
Sports ob=new Sports();
ob.getNo(44);
ob.putNo();
ob.getMarks(55);
ob.putMarks();
ob.getScore(85);
ob.putScore();
}
}
● Hierarchical inheritance:
In a class hierarchy, when a parent class has two or more than two child classes
then, the inheritance is said to be hierarchical inheritance.
e.g:
class Student
{
int rollno;
void putNo()
{
System.out.println(“rollno= ”+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println(“marks= ”+marks);
}
}
class Display
{
public static void main(String ar[])
{
Marks s1=new Marks();
Sports s2=new Sports();
s1.getNo(44);
s1.putNo();
s1.getMarks(45);
s1.putMarks();
s2.getNo(44);
s2.putNo();
s2.getScore(95);
s2.putScore();
}
}
44. Polymorphism:
It is a mechanism of having multiple forms. In other words polymorphism is a
mechanism of defining an interface to represent a general class actions.
class Display
{
public static void main(String ar[])
{
B ob=new B();
ob.callMe(); // B’s callMe() will be executed
// i.e, A’s callMe() overridden by B’s callMe()
}
}
Abstract Keyword:
1. To declare abstract methods
2. To declare abstract classes
1. Abstract Method:
It is a method in which we have only method declaration but it will not have
definition or body. Abstract methods aare declared with abstract keyword and
terminated by semicolon (;)
Syntax: abstract return_type MethodName(parameter_list);
● In a class hierarchy when a superclass containing an abstract method. all the
subclasses of that superclass must override the base class method.
● If the child fails to override the superclass abstract method, the child class
must also be abstract.
● Hence abstract method follows the process of method overriding.
2. Abstract Classes:
A class which consists atleast one abstract method is called abstract class. The class
definition must be preceded by abstract keyword.
Syntax:
abstract class className
{
-----
-----
abstract returntype MethodName(parameter_list)
{
-------
-------
}
-------
-------
// it can include concrete methods also
}
eg:
abstract class Shape
{
abstract void callMe();
}
class DemoAbstract
{
public static void main(String ar[])
{
sub s=new sub();
s.callMe();
}
}
1. final datamembers:
when a data member is declared as final, its value can’t be changed through out the
program. Hence final variables can be treated as ‘java constants’ Hence when a
datamember is declared as final its value must be assigned immediately.
eg: final double pie=3.14;
2. final methods:
when a method is declared as final its value cant be overridden at all
syntax: final returntype MethodName(ParameterList)
{
-------
-------
}
When a base class method is declared as final no subclass of that superclass will be
allowed to override the base class final method
eg:
final void show()
{
------
------
}
3. final class:
when a class is declared as a final it cant be inherited at all. Hence we cant have
subclasses for final classes.
class B
{
int x;
B(int p, int q)
{
super.x=p; // superclass variable is initialized
x=q; // subclass variable is initialized
}
void display()
{
System.out.println(“super class variable=”+super.x);
System.out.println(“sub class variable=”+ x);
}
class DemoSuper
{
public static void main(String ar[])
{
B ob=new B(10,20);
ob.display();
}
}
}
class DemoSuper
{
public static void main(String ar[])
{
B ob=new B(10,20,30);
ob.display();
}
}
49. Member access rules
As java is an object-oriented programming language, data is given more importance
regarding its access. Data is to be protected against unauthorized access. In order to protect
data in a well built way, data is organized into three categories.
a. Public data
b. Private data
c. Protected data
public, private & protected are called access specifiers. The following table illustrates
the member access rules
● The members declared as public can be accessed any where, any class and any
package.
● The members declared as private can be accessed only by the methods of same class
where the private members are declared.
● The members declared as protected cannot be accessed in non-subclasses of different
packages in rest of the cases they can be accessed. If you want any member to be
accessed in the subclasses of other packages they can be declared as protected. These
members are being protected from the access facility of non-subclasses of other
packages.
● The members declared by nothing, like of no modifier is being placed before a
member of a class then, these members can be access only up to package. This occurs
by default. Different packages are not allowed to access these no modifier members.
Same class
Same Package Yes Yes Yes No
No-sub Classes
Different Package Yes Yes No No
Sub Classes
Different Package Yes No No No
Non-Subclasses
packuse.java
import siet.packEg;
class Display
{
public static void main(String ar[])
54. Interface:
An interface is a special case of abstract class, which contains all the abstract methods
(methods without their implementation). An interface specifies what a class must do, but not
how to do.
Using the keyword interface, we can fully abstract a class interface from its
implementation. Interfaces are syntactically similar to classes, but they lack instance variable,
and their methods are declared without anybody. Once it is defined, any number of classes
can implement an interface. Also, once class can implement any number of interfaces.
55. Initializing interface:
An interface is defined much like a class. This is the general form of an interface:
access interface interface_name
{
type final_varname1=value;
type final_varname2=value;
....
returntype method-name1(parameter_list);
returntype method-name2(parameter_list);
....
}
here , access is either public or not used. When no access specifier is included, then defult
access results, and the interface is only available to other members of the class package in
which it is declared. when it is declared as public, the interface can be used by any other
code. interface_name can be any valid identifier.
Methods which are declared have no bodies. they end with a semicolon after the parameter
list. they are explicitly abstract methods.
variables are implicitly final and static, meaning they cannot be changed by the implementing
class. They must be initialized with a constant value. All the methods and variable are
implicitly public if the interface, itself is declared as public.
Eg:
interface
{
int pcode=999; // final variable
String pname=”HardDisk”; // final variable
void show(); // abstract method
}
class DemoMultiple
{
public static void main(String ar[])
{
Professor p=new Professor();
p.showCitizen();
p.showEmploy();
p.showProfessor();
}
}
The processing of text often consists of parsing a formatted input string. Parsing is the
division of text into a set of discrete parts, or tokens, which in a certain sequence can convey
a semantic meaning. The StringTokenizer class provides the first step in this parsing process.
We can enumerate the individual tokens contained in it using StringTokenizer .
To use StringTokenizer, you specify an input string and a string that contains delimiters.
Delimiters are characters that separate tokens. Each character in the delimiters string is
considered a valid delimiter for example, ", ; :" sets the delimiters to a comma, semicolon,
and colon. The default set of delimiters consists of the whitespace characters: space, tab,
newline etc
Method Description
62. Exception: An Exception is defined as “an abnormal error condition that arises
during our program execution”
When a Exception occurs in a program, the java interpreter creates an exception object and
throws it out as java exceptions, which are implemented as objects of exception class. This
class is defined in java.lang package
An Exception object contains datamembers that will store the exact information about
the runtime error (Exception) that has occurred.
1. try
2. catch
3. finally
4. throw
5. throws
try block:
The statements that produces exception are identified in the program and the statements are
placed in try block
Syntax:
try
{
//Statements that causes Exception
}
catch block
The catch block is used to process the exception raised. The catch block is placed
immediately after the try block.
Syntax:
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
}
finally block:
finally creates a block of code that will be executed after a try/catch block has completed. The
finally block will execute whether or not an exception is thrown. If an exception is thrown,
the finally block will execute even if no catch statement matches the exception.
Syntax:
finally
{
// statements that executed before try/catch
}
throw:
It is possible to create a program that throws an exception explicitly, using the “throw ”
statement.
Syntax: throw throwable_instance;
Here throwable_instance must be an object type of Throwable class or subclass of
Throwable. There are two ways to obtain a Throwable objects
1. using parameter into a catch clause
2. Crating one with the new operator
throws:
If a method is capable of causing an exception that it doen’t handle, it must specify the
behaviour to the callers of the method can guard themselves against that ex ce ptin. This can
be don’t by throws statement in the methods declarations.
A throws lists the types of exceptions that a method might throw.
Syntax: return_ type method_name(parameter-list)throws exception-list
{
//method body
}
Here, exception-list is a comma-separated list of the exception that a method can
throw.
import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
Class Test
{
public static void main(String ar[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter marks”);
try
{
int marks=Integer.parseInt(br.readLine());
if(marks>100)
{
throw new MyException(“Greater than 100”);
}
System.out.println(“Marks=”+marks);
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println(“completed”);
}
}
}
output-1:
Enter marks
99
Marks=99
completed
output-2:
Enter marks
101
Greater than 100
completed
if(a==2)
{
int c[]={3};
c[20]=40;
}
}// end of inner try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index exceeds”);
}
}//end of outer try
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception”);
}
}
}
67. Thread is a sequence of instsructions that is executed to define a unique flow of
control. It is the smallest unit of code.
Creating Threads:
Threads are implemented in the form of objects that contain a method called run(). The run()
method is the heart and soul of any thread.
public void run()
{
…………….
…………….(statements for implementing thread)
…………….
}
the run() method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method called
start().
A new thread can be created in two ways.
1. By extending Thread class: Define a class that extends Thread class and override its
run() method with the code required by the thread.
2. By implementing Runnable interface: Define a class that implements Runnable
interface. The Runnable interface has only one method, run(), that is to be defined in
the method with the code to be executed by the thread.
output-1:
From Thread A : i 1
From Thread A : i 2
From Thread B : j 1
From Thread B : j 2
From Thread A : i 3
From Thread A : i 4
From Thread B : j 3
From Thread A : i 5
From Thread B : i 4
From Thread B : i 5
output-2:
From Thread A : i 1
From Thread B : j 1
From Thread B : j 2
From Thread B : j 3
From Thread A : i 2
From Thread B : j 4
From Thread B : j 5
From Thread A : i 3
From Thread A : i 4
From Thread A : i 5
Example:
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“Thread A: i= ”+i);
}
}
}
class RunnableTest
{
public static void main(String ar[])
{
A ob=new A();// A’s object ‘ob’
Thread t=new Thread(ob);
t.start();
}
}
output:
Thread A: i= 1
Thread A: i= 2
Thread A: i= 3
Thread A: i= 4
Thread A: i= 5
69. Lifecycle of a Thread
During the lifetime of a thread, there are many states it can enter. They include:
1. NewBorn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
A thread is always in one of these five states. It can move from one state to another via a
variety of ways as shown in below figure.
NewBorn State:
When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At t his state, we can do only one of the following
things with it:
● Schedule it for running using start() method
● Kill it using stop() method
Runnable State:
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. If we want a thread to relinquish control to another thread to
equal priority before its turn comes, we can do so by using the yield()
Running State:
Running means that the processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread.
Blocked State:
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running s tate. This happens when the thread is suspended, sleping, or
waiting in order to satisfy certain requirements. A blocked thread is considered “not
runnable” but not dead and therefore fully qualified to run again.
Dead State:
Every thread has a lifecycle. A running thread ends its life when it has completed executing
its run() method. It is natural death. However, we can kill it by sending the stop message to it
at any state thus causing a premature death to it. It is done by stop() method.
Synchronizing Threads:
Synchronization of threads ensures that if two or more threads need to access a shared
resource then that resource is used by only one thread at a time. You can synchronize your
code using the synchronized keyword. You can invoke only one synchronized method for an
object at any given time.
Synchronization is based on the concept of monitor. A monitor, also known as a semaphore,
is an object that is used as a mutually exclusive lock. All objects and classes are associated
with a monitor and only one thread can won a monitor at a given time.
The monitor controls the way in which synchronized methods access an object or class.
When a thread acquires a lock, it is said to have entered the monitor. The monitor ensures
that only one thread has access to the resources at any given time. To enter an object’s
monitor, you need to call a synchronized method.
When a thread is with in a synchronized method, all the other threads that try to call it
on the same instance have to wait. During the execution of a synchronized method, the object
is locked so that no other synchronized method can be invoked. The monitor is automatically
released when the method completes its execution. The monitor can also be released when
the synchronized method executes the wait() method. When a thread calls the wait() method,
it temporarily releases the locks that it holds.
example: See the example which I was given (u can find it in observation or in record or in
notes)
73. ThreadGroup
ThreadGroup creates a group of threads. It defines these two constructors
ThreadGroup(String groupname);
ThreadGroup(ThreadGroup parentob,String groupname);
For both forms, group name specifies the name of the thread group. Thread groups offer a
convenient way to manage groups of threads as a unit.
For example, imagine a program in which one set of threads is used for printing a document,
another set is used to display the document on the screen, and another set saves the document
to a disk file. If printing is aborted, you will want an easy way to stop all threads related to
printing.
Networking
Networks sockets are used for networking the systems. A Network socket is like an electrical
socket at which various plugs around the network has a standard way of delivering their
payload. For transmission the data, the sockets are used some protocols.
79. Protocol is a standard set of rules, which is used to transfer the data from one system
to another. Protocols are classified into two types as
Connection oriented protocols: Eg: TCP/IP Protocols
Connection-less Protocols Eg: UDP Protocols
Internet Protocol(IP) is a low-level routing protocol that breaks data into small packets and
sends them to an address across the network. It is not guarantee to deliver the packets to
destination.
Transmission Control Protocol(TCP) is a higher level protocol that manages to robustly
string together these packets, sorting and retransmitting them as necessary to reliably tranmit
the data.
User Datagram Protocol(UDP) used directly to support fast, connectionless, unreliable
transfer of packets.
Addresses:
When there are tens of millions of computers that are connected in a single network, an
addressing scheme can be used to select an application that is running on any one of those
multiple computers. The computers connected with in an internet have addresses called IP
addresses. This address has the form
Num1.Num2.Num3.Num4
There are four numbers separated with dots and each number can have any value between 0
and 255
Another way of designating a particular computer is through domain name address. The
domain names are similar to that of IP addresses as they are written as a sequence of items
that are separated by periods(dots).Domain names point to a particular machine through
multiple levels. The levels on the right are more general and as they are read to the left, they
become more specific.
Example. www.jntu.edu.in
Port: A Location where the clients and servers can exchange information is called a port.
Ports can be designated using integer numbers. The numbers that are less than 1024 are
reserved for predefined services such as file transfer, email etc. So, a user defined port can
have an integer value that is greater than 1024.
class client
{
public static void main(String arg[])throws Exception
{
System.out.println("Client Activated");
System.out.println("Client1 Activated");