Bca Final Java Notes
Bca Final Java Notes
Bca Final Java Notes
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.
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.
Java Virtual Machine:
Generally all language compilers translate source code into machine code for a specific
computer. In java, architectural neutral is achieved because compiler produces an
intermediate code called Byte code, for a machine is called JVM
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.
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.
Sumati Baral Page 3
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.
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(int 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
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
Local Variables
Local variables are declared in methods, constructors, or blocks.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.
int age = 0;
age = age + 7;
test.pupAge();
}}
Example
Following example uses age without initializing it, so it would give an error at the time of
compilation.
int age;
age = age + 7;
test.pupAge();
1 error
Instance Variables
Instance variables are declared in a class, but outside a method, constructor
or any block.
When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
Example
import java.io.*;
salary = empSal;
name : Ransika
salary :1000.0
Class/static Variables
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and
static. Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
Static variables are created when the program starts and destroyed when
the program stops.
Default values are same as instance variables. For numbers, the default
value is 0; for Booleans, it is false; and for object references, it is null.
Values can be assigned during the declaration or within the constructor.
Additionally, values can be assigned in special static initializer blocks.
When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and
final, the naming syntax is the same as instance and local variables.
Example
import java.io.*;
salary = 1000;
Note: If the variables are accessed from an outside class, the constant should be
accessed as Employee.DEPARTMENT
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];
}
}
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
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
Sumati Baral Page 11
>> 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:
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.
Control Statements
A Control statement is a statement that controls the flow of execution of the program. Java’s
program control statements are divided into 3 categories
● Selection Statements
● Iteration Statements
● Jump Statements
1)Selection Statements:
Selection statement controls the flow of the program depending on the result of the
conditional expression or the state of a variable. There are two selection statements : if and
switch
a. if statement:
‘if’ is a selection statement that is used to choose two choices in a program.
Syntax:
if(condition)
statement1;
else
statement2;
‘condition’ is any expression that returns a Boolean value (i.e., true/false).
Statement is a single or multiple statements.
If the condition is true then the control goes to the statement1 and it is
executed. Otherwise, the statement2 is executed.
b. Nested if statement:
It means an if statement under another if statement.
Syntax:
if(condition)
{
if(condition)
statement;
}
c. if-else-if ladder:
if-else-if statement is a sequence of if-else statements.
Syntax:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
statement3;
.
.
else statement2;
In if-else-if ladder if a condition is not met then the control flows from top to
bottom until the last if statement.
switch statement:
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:
Sumati Baral Page 14
‘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(“ “);
}
}
}
}
}
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
Sumati Baral Page 17
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.
Concept of Objects
Objects are instances of a class. Objects are created and th is process is called
“Instantiation”. In java objects are created through the use of new operator. The new operator
creates an object and allocates memory to that object. Since objects are created at runtime,
they are called runtime entities.
In java object creation is a two step process.
Step1: create a reference variable of the class
Eg: Sample s;
When this declaration is made a reference variable is created in memory and
initialized with null.
Step2: create the object using the new operator and assign the address of the object to
the reference variable created in step1.
Eg: Sample s=new Sample();
The step2 creates the object physically and stores the address of the object in the
reference variable.
Accessing members of an object:
Once an object of a class is created we can access the members of the class through the use of
object name and ‘.‘ (dot) operator.
Syntax: objectname. member;
Example:
class sample
{
int x, y;
setXY()
{
x=10; y=20;
}
printXY()
{
System.out.print(“=”+x);
System.out.print(“=”+y);
}
}
class Demo
{
public static void main(String ar[])
{
Sample s;
s=new String();
s.setXY();
s.printXY();
Sumati Baral Page 18
}
}
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 variables:
When a datamember of a class, is declared static only one copy of it is created in
memory and is used by all the objects of the class. Hence static variables are essentially
global variables.
When a modification is performed on a static variable the change will be reflected in
all objects of the class for which the static variable is a member.
2. Static Methods:
● A static method can call other static methods only
● A static method can access static variables only
● Static methods cant have access to this/ super keyword.
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;
Sumati Baral Page 20
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
Access Control:
Java’s access specifiers are public, private and protected. Java also defines a default
access level. protected applies only when inheritance is involved.
When a member of a class is specified as public, then that member can be accessed by
anyother code.
When a member of class is specified as private, then that member can only be accessed by
other members of its class, but not anyother class members.
Garbage Collection
Objects are dynamically allocated using the ‘new’ operator and their memory must be
released after reallocation. In C++, they are manually released by the use of delete operator.
Java deallocates memory automatically and it is called “Garbage Collection”. When no
references to an object exist the object is assumed to be no longer needed and the memory
occupied by the object can be reclaimed and t his is how “garbage collection” is done.
Finalize() Method :
In some situations an object will lead to perform some action when it is destroyed. Suppose
for example an object is holding some non-java resource such as file-handling. We must
have to free the resources after the object is destroyed.
To handle these situations java provides finalization using finalize() method
Syntax: protected void finalize()
{
// finalization code here
}
protected prevents to access finalize method by code defined outside the class.
void is used because it doesn’t return anything.
Overloading methods
In java, it is possible for a class, to contain two or more methods with the same name as long
as the method signatures are different. That is the method should have different number of
parameters or different type of parameters when this is the case the methods are said to be
overloaded and the mechanism is called method overloading.
s.setStudent(69,81,”ramu”);
s.showStudent();
}
}
output:
number=1
marks=89
name=rama
number=69
marks=81
name=ramu
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;
Parameter passing
There are two ways that a computer language can pass an argument to a subroutine
(method).
1. call by value
2. call by reference
In the first way, the change made to the parameter of the subroutine have no effect on
the argument.
In the second way, the changes made to the parameter will effect the argument used to
call the subroutine.
In java when you pass a primitive type it is pass by value. when you pass an
object(reference) to a method, it is done through pass by reference
Example:
// call by value
class Test
{
void meth(int i , int j)
{
i+=2;
j*=2;
}
}
class CallByValue
{
public static void main(String arg[])
{
Test ob= new Test();
}
}
output:
a and b before call: 10 20
a and b after call: 10 20
Recursion
Java supports recursion. It is the process of defining something in terms 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
String Handling
A String is a sequence of characters. In java , Strings are class objects and implemented
using two classes, namely, String and StringBuffer. A java string is an instantiated object of
the String class.A java String is not a character array and is not NULL terminated. Strings
may be declared and created as follows:
String stringname= new String(“string”);
String name=new String(“kanth”); is same as
String name=”kanth”;
like arrays, it is possible to get the length of string using the length method of the String class.
int len = name.length();
Java string can be concatenated using the + operator.
eg: String firstname = ”sri”;
String lastname = ”kanth”;
String name = firstname+lastname;
( or )
Sumati Baral Page 25
String name = ”sri”+”kanth”;
String Arrays:
we can also create an use arrays that contain strings. The statement,
String names[]=new String[3];
will create an names array of size 3 to hold three string constants.
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
StringBuffer Class :
StringBuffer is a peer class of String. While String creates string of fixed length,
StringBuffer creates strings of flexible length that can be modified in terms of both length
and content. We can insert characters and substrings in the middle of a string, or append
another string to the end.
Below, there are some of methods that are frequently used in string manipulations.
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
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.
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 .
3. Forms of inheritance:
Sumati Baral Page 27
Inheritance is used in variety of ways. The following list represents general abstract
categories and is not intended to be exhaustive.
Benefits of Inheritance:
various benefits of inheritance are
● S/w Reusability:
Many programmers spend much of their time in rewriting code they have
written many times before. So with inheritance code once written can be
reused.
● code sharing
Code sharing occurs at two levels. At first level many users or projects can use
the same class. In the second level sharing occurs when two or more classes
developed by a single programmer as part of a project which is being inherited
from a single parent class. Here also code is written once and reused. This is
possible through inheritance.
● Consistency of inheritance:
When two or more classes inherit from the same superclass we are assured
that the behaviour they inherit will be the same in all cases. Thus we can
guarantee that interfaces to similar objects are in fact similar.
● 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 Display
{
public static void main(String ar[])
{
Marks ob=new Marks();
ob.getNo(44);
ob.putNo();
Sumati Baral Page 31
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.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;
class Display
{
public static void main(String ar[])
{
Marks s1=new Marks();
Sports s2=new Sports();
s1.getNo(44);
s2.getNo(44);
s2.putNo();
s2.getScore(95);
s2.putScore();
}
}
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.
Method Overriding:
In a class hierarchy when a method of a subclass has the same name and type
signature has that of a method in its superclass, then the method in the subclass is said to be
override the method in the superclass. When this is the case the mechanism called “method
overriding” and such methods are called overridden methods.
When overridden method is using base class object the base class version is executed
and if it is called by subclass, the subclass version is executed.
eg:
class A
{
void callMe()
{
System.out.println(“I am version of superclass A”);
}
}
class B extends A
{
void callMe()
{
System.out.println(“I am version of subclass B”);
}
}
class Display
{
public static void main(String ar[])
{
B ob=new B();
ob.callMe(); // B’s callMe() will be executed
Sumati Baral Page 36
// 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();
}
}
final keyword: final keyword is used for the following purposes
1. To define final datamembers
2. To define final methods
3. To define final classes
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()
{
------
------
}
final class:
super keyword:
● It is used for referring the immediate superclass of the sub class
● super keyword is used to access super class data members from its subclass.
eg:
class A
{
int x;
}
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();
}
}
super uses:
1)super keyword is used to access superclass methods from its subclass
eg: above example
}
class DemoSuper
{
public static void main(String ar[])
{
B ob=new B(10,20,30);
ob.display();
}
}
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
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
PACKAGES & INTERFACES
Package:
A package is a collection of classes and interfaces which provides a high level of
access protection and names space management.
Defining & Creating package:
step1: simply include a package command has the first statement in java source file. Any
class you declare with in that file will belong to the specified package.
syntax: package packagename;
Eg: package mypack;
step 2: next define the class that is to be put in the package and declare it as public
step 3: now st ore the classname.java file in the directory having name same as package
name.
step 4: file is to be compiled, which creates .class file in the directory
java also supports the package hierarchy , which allows to group related classes into a
package and then group related packages into a larger package. We can achieve this by
specifying multiple names in a pcakge statement, separated by dot .
i.e., package firstpackage.secondpackage;
Sumati Baral Page 41
Accessing package:
A java system package can be accessed either using a fully qualified classname or using
import statement. We generally use import statement.
syntax: import pack1[.pack2][.pack3].classname;
or
import pack1. [.pack2][.pack3].*;
here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on.
In this way we can have several packages in a package hierarchy. We should specify explicit
class name finally. Multiple import statements are valid. * indicates that the compiler should
search this entire package hierarchy when it encounters a class name.
Understanding CLASSPATH:
the package hierarchy is controlled by CLASSPATH. Until now we have been storing
all of our classes in the same unnamed default package. This works because the default
current working directory(.) is usually in the class path environmental variable defined for the
java runtime system by default. But there are so many unknown problems when packages are
involved.
How does the java runtime system know where to look for packages that we create?
The answer has twoparts. First, by default, the java runtime system uses the current working
directory as its starting point. Thus if our packages in in the current directory, or a
subdirectory of the current directory , it will be found. Second, you can specify a directory
path by setting the CLASSPATH environmental variable.
eg: create a class called ‘packtest’ in package ‘test’. create a directory called ‘test’ and
put packtest.java inside the directory. Now we compile the program and the resultant .class
file will be stored in the current working directory. Then execute the program as ;
java test.packtest
Importing packages:
java includes import statement to bring certain classes or entire package into visibility. In a
java source file import statement occurs immediately following the package statement and
before any class definitions.
syntax: import pkg1[.pkg2].(classname / *) ;
here pkg1 is the name of the top level package. pkg2 is the name of the subordinate
package separated by (.)
finally classname/ * indicates whether the java compiler should import the entire
package or a part of it.
eg: import java.util.Date;
here java is main package, util is subordinate package Date is the class belongs to util
package
Example program(user defined package):
packEg.java
package siet;
public class packEg
{
public void display()
{
System.out.println(“WELCOME TO SWARNANDHRA INSTITUE”);
}
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.
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
Implementing interfaces:
Once an interface has been defined, one or more lases can implement that interface. To
implement an interface, include the implementes clause in a class definition, and then create
the methods defined by the interface. The general form of a class that includes the
implements clause looks like this:
access class classname [extends superclass] [implements interface [,interface…]]
{
// class body
}
Eg:
interface product
{
int pcode=999;
String pname=”HardDisk”;
abstract void showProduct();
}
class ProductDesc implements Product
{
public void showProduct()
{
System.out.println(“Pcode=”+pcode);
System.out.println(“PName=”+pname);
}
}
class DemoInterface
{
public static void main(String ar[])
{
ProductDesc ob=new ProductDesc();
ob.showProduct();
}
}
Note:
At the time of overriding, the interface methods must be declared as public.
●
Interfaces are introduced to implement multiple inheritance indirectly in java
●
Variables in interface:
Sumati Baral Page 44
Interfaces can also be used to declare a set of constants that can be used in different classes.
The constant values will be available to any class that implements the interface. The values
can be used in any method, as part of any variable declaration, or anywhere where we can use
a final value.
Example:
interface A
{
int m=10, n=50;
}
class B implements A
{
void display()
{
System.out.println(“m=”+m+” , n=”+n);
}
}
Extending interfaces
Like classes, interfaces can also be extended. That is , an interface can be subinterfaced from
other interfaces. The new subinterface will inherit all the members of the superinterface in the
manner similar to subclasses. This is achieved using the keyword extends as shown below
interface name2 extends name1
{
body of name2;
}
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
void display();
}
class display implements Item
{
public void display()
{
System.out.println(code+”:”+name);
}
}
Applying interfaces
Implementing Multiple Inheritance:
Sumati Baral Page 45
A class can extend only class but it can implement multiple interfaces. This is one of
the ways to ruse multiple inheritance in java. The class must override all the methods of all
the interfaces.
eg:
interface citizen
{
String name=”Rama”;
abstract void show();
}
interface Employ
{
int eno=65, salary=20000;
abstract void showEmploy();
}
class DemoMultiple
{
public static void main(String ar[])
{
Professor p=new Professor();
p.showCitizen();
p.showEmploy();
p.showProfessor();
}
}
Differences between classes and interfaces
Both classes and interfaces contain methods and variables but with major difference. An
interface defines only abstract methods and final fields i.e., they don’t specify any code for
StringTokenizer Class :
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
The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, Boolean delimAsToken)
In all versions, str is the string that will be tokenized. In the first version, the default
delimiters are used. In the second and third versions, delimiters is a string that specifies the
delimiters. Delimiters are not returned as tokens by the first two forms. Once you have
created a StringTokenizer object, the nextToken( ) method is used to extract consecutive
tokens. The hasMoreTokens( ) method returns true while there are more tokens to be
extracted. Since StringTokenizer implements Enumeration , the hasMoreElements( ) and
nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( )
and nextToken( ) , respectively. The StringTokenizer methods are shown in below.
Method Description
int countTokens( ) Using the current set of delimiters, the method
determines the number of tokens left to be parsed and
returns the result.
boolean hasMoreElements( ) Returns true if one or more tokens remain in the string
and returns false if there are none.
boolean hasMoreTokens( ) Returns true if one or more tokens remain in the string
and returns false if there are none.
Object nextElement( ) Returns the next token as an Object.
String nextToken( ) Returns the next token as a String.
String nextToken(String delimiters) Returns the next token as a String and sets the delimiters
‘Exception’ Class:
This class is used for exceptional conditions that user programs should catch. This is
also the class that you will subclass to create your own custom exception types. There is an
important subclass of Exception, called Runtime Exception. Exceptions of this type are
automatically defined for the programs that you write and include things such as division by
zero and invalid array indexing.
‘Error’ Class:
Which defines exceptions that are not expected to be caught under normal circumstances by
your program. Exceptions of type Error are used by the java run-time environment, itself.
Stack overflow is an example of such an error.
Uncaught Exceptions:
This small program includes an expression that intentionally causes divide-by-zero error.
class Ex
{
public static void main(String ar[])
{
int a=0;
int b=10/a;
}
}
Any exception that is not caught by your program will ultimately be processed by the
default handler. The default handler displays a string describing the exception, prints a stack
trace from the point at which the exception occurred, and terminates the program.
-----Here is the output generated when this example is executed------
javja.lang.ArithemeticException:/by zero
Java uses 5 keywords in order to handle the exceptions
1. try
2. catch
3. finally
4. throw
5. throws
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
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
Nested Try
A try block is placed inside the block of another try block is termed as Nested try block
statements. If any error statement is in outer try block , it goes to the corresponding outer
catch block. If any error statement is in inner try block first go to the inner catch block. If it is
not the corresponding exception next goes to the outer catch, which is also not corresponding
exception then terminated.
Example:
class NestedTry
{
public static void main(String ar[])
{
try
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”);
}
}
}
Multiple Catch Statements:
Multiple catch statements handle the situation where more than one exception could be raised
by a single piece of code. In such situations specify two or more catch blocks, each specify
different type of exception.
Example:
class MultiCatch
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=42/a;
int c[]={3};
c[20]=40;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
}
output-1:
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
Lifecycle of a Thread
During the lifetime of a thread, there are many states it can enter. They include:
1. NewBorn State
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.
Sumati Baral Page 54
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)
The Synchronized Statement:
Synchronization among threads is achieved by using synchronized statements. The
synchronized statements is used where the synchronization methods are not used in a class
and you do not have access to the source code. You can synchronize the access to an object of
this class by placing the calls to the methods defined by it inside a synchronized block .
syntax:
synchronized(obj)
{
// statements;
}
Inter-thread communication
Java supports inter-thread communication using wait(), notify(), notifyAll() methods. These
methods are implemented as final methods in Object. So all classes have them. all three
methods can be called only from within a synchronized context.
● wait() tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify()
● notify() wakes up the first thread that called wait() on the same object.
● notifyAll() wakes up all the threads that called wait() on the same object. The highest
priority thread will run first.
Daemon Threads:
A daemon thread is a thread that runs in the background of a program and provides services
to other threads. The daemon threads are background service provides for other threads. For
example, Garbage collector, clock handler, and screen updater are the daemon threads. By
default no thread that you create is a daemon thread. The setDaemon() method is used to
convert a thread to a daemon thread.
Eg:
Thread1.setDaemon(true);
setDaemon() method is used to determine if a thread is a daemon thread.
Boolean b=Thread1.isDaemon();
‘b’ contains true if Thread1 is daemon, otherwise stores false.
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.
Thread Priorities:
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower priority
Networking
4. Basics of network programming
5. Network: More than one computer systems are connected to sent and receive the
information with each other is considered as a Network. due to the networking there is
a communication between the systems. So, that they are shared data as well as
resources.
6. Internet: An interconnection of networks is considered as a internet or intranet(Local
Area Network). It is the name for vast of worldwide systems, which consists of
different types of networks or different servers. The computers that are connected to
the Internet is considered as a Host.
7. Socket Overview:
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.
8. 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
Sumati Baral Page 56
Num1.Num2.Num3.Num4
There are four numbers separated with dots and each number can have any value between 0
and 255
For example: 192.27.168.35
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");