b.sc(m)-V Sem Java Notes
b.sc(m)-V Sem Java Notes
UNIT-I
Introduction:
JAVA - Java is a pure Object Oriented Programming Language.
OOPs Concepts:
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Data Abstraction & Encapsulation
6. Message communication
7. Dynamic binding
Objects & Classes:
Objects:
Objects are the basic runtime entities in object oriented system. They may
represent a place, person or any item that the program may handle.
- An entity that has state and behavior is known as an object
E.g. chair, bike, marker, pen, table, car etc.
An object has three characteristics:
• State: represents data (value) of an object.
• Behavior: represents the behavior (functionality) of an object
• Identity: Object identity is typically implemented via a unique ID.
Class:
Collection of Objects of same type is known as class
ex: mango, apple and orange are the members of the class fruit
Data Abstraction:
Hiding the implementation details of a particular object is known as Data
abstraction
Data Encapsulation:
Combining all the functions together is known as Data Encapsulation.
- The wrapping of data and methods into a single unit is called encapsulation
which is one of the important features of class. The data is not accessible to the
outside world and only those methods which are wrapped in the class can access it
which is known as data hiding.
Polymorphism:
Means the ability to take more than one form.
Inheritance:
It is the process by which the objects of one class acquire the properties of objects
of another class.
- Extending the parent class properties to child class is the concept of Inheritance.
-It provides the idea of reusability which means that we can additional features to
an existing class without modifying it which is possible by deriving a new class
from the existing one where the new class will have the combined features of both
the classes.
Dynamic binding:
Means that the code associated with given procedure call is not known until the
time of the call at runtime. It is associated with polymorphism and inheritance.
Message Communication
Objects communicate with each other by sending and receiving information as
people.
It involves specifying the name of the object, method name and information to be
sent.
example:
employee.salary(ename);
Depending on the above principles, they support,
- object based programming language
What is Java:
->Java is a pure object oriented programming language.
->Java is a programming language and a platform independent.
->Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs is
known as a platform. Since Java has its own runtime environment (JRE) and API,
it is called platform.
JAVA features:
- Compiled and Interpreted
- Platform independent & portable
- Object Oriented
- Robust & secure
- distributed
- Familiar, simple & small
- Multithreaded & interactive
- High performance
- Dynamic & Extensible
Object oriented:
Java is a true OOPL where all program code and data reside within objects &
classes.
Distributed:
It is a distributed language for creating applications on networks which has the
ability to share both data & programs.
High performance:
Incorporation of multithreading enhances the overall execution speed of java
program.
2) Web Application: An application that runs on the server side and creates
dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc.
technologies are used for creating web applications in java.
ex:as irctc.co.in, gmail.com,snapdeal.com,amazon.in,bookmyshow.com
JVM:
JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides runtime environment in which java byte code can
be executed.
Java virtual machine:
Java is a 2 stage system which supports both compiler & interpreter based.
At first stage, java compiler translates source code into intermediate code known as
byte code(virtual code) for a machine that does not exist. This machine is called
JVM and exists only inside computer memory. It is a simulated computer within
the computer and does all major functions of real computer.
At second stage, byte code is converted to machine code.
Process of compilation:
Java Compiler
Java Program code Virtual machine
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer ->right click->properties ->
change settings->advanced tab -> environment variables -> new tab of user
variable -> write “path” in variable name -> write path of bin folder (C:\jdk1.3\bin
ie paste by using ctrl+v)in variable value -> ok -> ok -> ok
- set the same path with system variable also
Notepad − On Windows machine, you can use any simple text editor
like Notepad , TextPad.
Netbeans − A Java IDE that is open-source and free which can be downloaded
from https://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded from https://www.eclipse.org/.
Example
class FirstJavaProgram
{
public static void main(String []args)
{
declaration of class
//syntax
imort packagename.classname;
class classname
{
public static void main(String args[])
{
function body;
}
}
First Java Program
Let us look at a simple code that will print the "Welcome to Java Programming"
Example:
class FirstJavaProgram
{
public static void main(String []args)
{
System.out.println("Welcome to Java Programming");
}
}
class declaration
class FirstJavaProgram declares a class which is Objet Oriented construct. As
java is true Object Oriented language, so everything must be placed inside a class.
main line
public static void main(String args[]) defines a method named main() similar
to main() of c & C++. Every java program must include main() method which is
the starting point for the interpreter to begin the execution of program.
A java application. can have number of classes but only one of them must include
main method to initiate the execution.
public - it is an access specifier that declares the main method as unprotected and
therefore making it accessible to all other classes.
static - it declares main method as one that belongs to the entire class and not a
part of any objects of the class.
Note: Static is used to access the methods without invoking on object using dot
operator.
Why do we use static in "public static void main (String args[]) in Java?
void - it states that the main method does not return any value(returns nothing)
-It is the only the executable statement which is similar to printf() or cout<<
Types
- primitive data types/intrinsic
- non primitive/derived data types
primitive data types (8 types)
char boolean byte short int long float double
These 8 primitive types can be put into 4 categories.
1. Integer type
this group includes byte,short,int,long
byte - it is 8 bit integer data type. Value ranges from -128 to 127. Default value is
zero 0.
ex: byte b=10;
short - it is 16 bit integer data type. Value ranges from -32768 to 32767. default
value is 0.
ex:
short p=11;
int - it is 32 bit integer data type. Value ranges from -2147483648 to 2147483647.
default value is 0.
ex:
int x=10;
long- it is 64 bit integer data type. value ranges from -9.223372036854775808 to
9223372036854775807. Default value is 0.
ex:
long l=100023;
2. floating type
this group includes float, double
float - it is 32 bit float data type. Default value is 0.02F
ex:float f=10.2f;
double - it is 64 bit float data type
default value is 0.0d.
ex:
double db=11.23d;
3. character type
this group represent char which represents symbols in a character set like letters
and numbers.
char - it is 16 bit unsigned Unicode character. Range is from 0 to 65535.
ex:char c='a';
4. boolean
this group represents boolean which is a special type for representing true/false
values.
ex:
boolean ms=true;
Basic Syntax
About Java programs, it is important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello
would have different meaning in Java.
ASCII(American Standard Code for Information Interchange)
- Characters
A to Z - 65 to 90 difference (+- 32)
a to z - 97 to 122
0 to 9 - 48 to 56
Class Names − For all class names the first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class
name.
When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match, your program will not compile).
Example: Assume 'FirstJavaProgram' is the class name. Then the file should be
saved as 'FirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
In Java, there are several points to remember about identifiers. They are as follows
1.All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
ex: stud_name
2.After the first character, identifiers can have any combination of characters.
ex: stud_name1
3. A key word cannot be used as an identifier.
4.Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers. There are two categories of modifiers −
1.Access Modifiers − default, public , protected, private
2. Non-access Modifiers − final, abstract, static
Note: Static is used to access the methods without invoking object
Variable is a data name that holds a value which changes during program
execution.
declaration of variables:
datatype variable1,variable2,...;
ex:
byte x;
int a,b,c;
- Instance variables are created when the objects are instantiated and therefore
associated with the objects
- class variables are global to a class and belong to the entire set of objects that
class creates.
-Local variables - variables declared and used inside methods are called local
variables. They are so called because they are not available for outside method
definition.
- These are visible to the program only from beginning till end of programming
block
Comments in Java
are non executable statements which are used for user identification.
Java supports single-line(//) and multi-line(/* ==== */) comments very similar to
C and C++.
Note : characters available inside any comment are ignored by Java compiler.
type casting - process of converting from one form(dat type) to other form
1- implicit type casting/type conversion
2- explicit type casting/casting a value
1- implicit type casting/type conversion -
process of converting from low range data types to high range data type values.
uses:
- it is possible to assign one type of values to another data type without caste
where java compiler does this conversion automatically and so it is also called as
automatic conversion.
byte short,int,long,float,double
char int,long,float,double
short int,long,float,double
int long,float,double
long float,double
float double
syntax:
datatype <variablename>=(datatype)<variablename>
ex:
int i=135;
byte b=(byte)i;
- casting high range values to low range value leads to loss of data
- casting float->int causes truncation of decimal part
ex:23.5 ->23
- casting double->float causes rounding off digits
ex:1.23456789234
1.234568
-> casting long-int causes dropping the excess high order bits
uses of casting
1) x=(int)7.5 converted into integer by truncating fractional part
X=7
2) y=(int) 21.3/(int)4.5 both numerator and dinominator are converted into int
and result is 5
3) int n=2;
int sum=3;
b=(double)sum/n; performs floating point mode division
4) y=(int)a+b performs additions and caste the result to int
5)p=cos((double)x) firstly caste the value "x" to double and it is
passed to cos() function as parameter
//Scanner12.java
//reading values from key board
import java.util.Scanner;
class Scanner12
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter ur rollnumber");
int rollno=sc.nextInt();
System.out.println("enter ur name");
String name=sc.next();
System.out.println("enter ur fee");
double fee=sc.nextDouble();
System.out.println("roll number ="+rollno);
System.out.println("name ="+name);
System.out.println("fee ="+fee);
sc.close();
}
}
for(int i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("factorial value is"+f);
}
}
if construct
- simple if
- if else construct
- if else if ladder
- nested if
simple if
if (condition)
statement(s);
// program to demonstrate Simple if
//Simpleif.java
import java.lang.*;
class Simpleif
{
public static void main(String args[])
{
int age=12;
if ( age>=18)
System.out.println("candidate is major");
if ( age<18)
System.out.println("candidate is minor");
}
}
if else construct:
if (condition)
statement(s);
else
statement(s);
* wap to calculate grade basing on total and print marks memo consisting of
rno,name and any 3 subject marks
nested if - if within a if
if(condition)
{
if(condition)
statement(s);
else
statement(s);
}
else
{
if(condition)
statement(s);
else
statement(s);
}
switch construct
is a multi way construct which is used as an alternate to if else if construct.
syntax:
switch(expression)
{
case value 1:
statements;
break;
case value 2:
statements;
break;
case value 3:
statements;
break;
=====
====
case value N:
statements;
break;
default:
statements;
break;
}
Q: program to accept day number and print appropriate day of the week
//SwitchChoice.java
import java.util.Scanner;
class SwitchChoice
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter day number from 1 to 7");
int dayno=sc.nextInt();
switch(dayno)
{
case 1:
System.out.println("it is monday");
break;
case 2:
System.out.println("it is tuesday");
break;
case 3:
System.out.println("it is wednesday");
break;
case 4:
System.out.println("it is thursday");
break;
case 5:
System.out.println("it is friday");
break;
case 6:
System.out.println("it is saturday");
break;
case 7:
System.out.println("it is sunday");
break;
default:
System.out.println("invalid choice ");
}
}
}
iterative statements or looping constructs
loop
execution of statements repeated number of times as long as condition is true or
until condition becomes false is known as loop.
ex: entry contol loop and exit control loop
while loop:
initialization statement(s);
while(condition)
{
body of loop;
}
statement-x;
//example to demonstrate while loop
//While.java
class While
{
public static void main(String args[])
{
int i=1; //initialisation
while(i<=10)
{
System.out.println(i);
i=i+1;
}
}
}
//reverse of a number
import java.util.Scanner;
class ReverseNum
{
public static void main(String args[])
{
int m,mod,rem,rev=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter any number");
int n=sc.nextInt();
m=n;
while(m>0)
{
rem=m%10;
rev=rev*10+rem;
m=m/10;
}
System.out.println("Reverse of "+n+" is :"+rev);
}
}
for loop:
for(initialization;condition;increment section)
{
body of loop;
}
statement(s);
do loop:
initialization statement(s);
do
{
body of loop;
}while(condition);
statement-x;
Arrays:
- It is collection of contiguous elements of similar data type(homogenous
collection of elements). Array is container object that hold values of homogenous
types. It is also known as static data structure because size of an array must be
specified at the time of its declaration.
- An array can be either non-primitive or reference type.
- In java, array is an example of derived data type.
- If an array contains "n" elements, the index of array starts from 0 and end
with n-1.
-Each individual element is called subscript of the array.
ex:
int a[]={10,20,30,40,50}; // initialization of array
a[0] is subscript and 0 is the index value
array declaration:
datatype [] identifier;
or
datatype identifier[];
ex:
int []arr;
char []b;
short []cc;
long []dd;
int [][] bb; // two dimensional array
int a[10];
int [10]arr;
note : array can be of any type;
types of arrays:
- one dimensional arrays
- two dimensional arrays
initialization of an array:
new operator is used to initialize an array
ex:
int [] aa=new int[10];
or
int aa[]={22,33,44,55,66};
Accessing an array element:
array index starts from 0. So, to access nth element of an array,
syntax is :
arrayname[n-1];
ex:
to access 5 th element of array
int []aa={11,22,33,44,55};
System.out.println("element in 5th position is"+aa[4]);
o/p
55
//initialisation of 1D array
class ArrayInit
{
public static void main(String args[])
{
int a[]={1,2,3,4,5};
for(int i=0;i<5;i++)
{
System.out.println("elements of array are :"+a[i]);
}
}
}
class Rectangle
{
int length,breadth; // instance variables
}
length and breadth are instance variables and are also known as member variables
which are only declared and therefore no storage space has been created in the
memory.
=>adding methods(functions)
Methods are declared inside the body of class but immediately after declaration of
instance variables.
syntax:
returntype methodname[(parameterlist)]
{
method-body;
return variable/expression;
}
creating objects:
Creating objects is known as instantiating an object (instantiation)
Objects in java are created using new operator which creates an object of the
specified class and returns reference to that object.
syntax:
classname object(s);
note:
- first statement declares a variable to hold the object reference
- second statement assigns the object reference to the variable
creation of object references
objectname.methodname(parameterlist);
here, objectname is the name of the object and variablename is the name of the
instance variable inside the object.
Ex:
Rectangle rect1=new Rectangle();
rect1.length=15; //giving values to members
rect1.breadth=12;
rect1.getdata(); //without argument
rect1.getdata(15,10); //with argument
//Example
//application of classes and objects
//Rectangle1.java
class Rectangle
{
int length,breadth; // declaration of instance variables
void getdata(int x,int y) //method definition
{
length=x;
breadth=y;
}
int rectarea() //definition of other method
{
int area=length*breadth;
return(area);
}
}
class Rectangle1 //class with main method
{
public static void main(String args[ ])
{
int area1,area2;
Rectangle rect1=new Rectangle(); //creating objects
Rectangle rect2=new Rectangle();
rect1.length=15; //giving values
rect1.breadth=10;
area1=rect1.length*rect1.breadth;
System.out.println("Area1="+area1);
rect2.getdata(12,5);
area2=rect2.rectarea();
System.out.println("Area2="+area);
}
}
// Example1
class Student
{
int id;//data member (or instance variable)
String name;//data member(or instance variable)
}
class Student1
{
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
s1.id=1001;
s1.name=”vaagdevi”;
System.out.println(s1.id);
System.out.println(s1.name);
}
}
------------------------------------------------------------------------------------
//Example2
class Student
{
int a;
String b;
void insertRecord(int x, String n) // Method with arguments
{
a=x;
b=n;
}
void displayInformation() //method without argument
{
System.out.println("Id= "+a);
System.out.println(“name=”+b);
}
}
Class Student2
{
public static void main(String args[])
{
Student s1=new Student();
s1.insertRecord(1001,"vaagdevi");
s1.displayInformation();
}
}
------------------------------------------------------------------
//Example3
class Student
{
int id;
String name;
void insertRecord() // Method with no argument
{
id=1001;
name="vaagdevi";
}
void displayInformation() //method
{
System.out.println("Id= "+id);
System.out.println("Name= "+name);
}
}
class Student3
{
public static void main(String args[])
{
Student s1=new Student();
s1.insertRecord();
s1.displayInformation();
}
}
--------------------------------------------
Anonymous object:
=>Anonymous simply means nameless.
=>An object that have no reference is known as anonymous object.
=>If you have to use an object only once, anonymous object is a good approach.
//Calculation.java
//demonstration of anonymous object
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
System.out.println("factorial value is "+fact);
}
}
class Anonymoustest
{
public static void main(String args[])
{
new Calculation().fact(5); //calling method with anonymous object
}
}
Output:Factorial is 120
Constructors in Java
Constructor in java is a special type of method that is used to initialize the object
when it is created. Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as
constructor.
//parameterized constructor
//RectangleArea1.java
class Rectangle
{
int length,breadth; // declaration of instance variables
Rectangle(int x,int y) //defining parameterized constructor
{
length=x;
breadth=y;
}
int rectarea() //definition of other method
{
int area=length*breadth;
return(area);
}
}
class RectangleArea1
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(15,10); //calling constructor with arguments
int area1=rect1.rectarea();
System.out.println("Area1="+area1);
}
}
--------------------------------------------------------------
Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to
another object just like copy constructor in C++.
//Example to demonstrate copy constructor
//CopyConStudent.java
class CopyConStudent
{
int id;
String name; //string object
CopyConStudent(int i,String n) // parameterised Constructor
{
id = i;
name = n;
}
CopyConStudent(CopyConStudent s) // Copy Constructor
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
}
Class Copycontest
{
public static void main(String args[])
{
CopyConStudent s1 = new CopyConStudent(10,"chinnu");
CopyConStudent s2 = new CopyConStudent(s1); //calling method with object
as argument
System.out.println("Object S1 =");
s1.display();
System.out.println("Object S2 =");
s2.display();
}
}
Copying values without using copy constructor:
We can copy the values of one object into another by assigning the objects values
to another object. In this case, there is no need to create the constructor.
//copy constructor
//CopyCons.java
class Student6
{
int id;
String name;
Student6(int i,String n) // parameterized Constructor definition
{
id = i;
name = n;
}
Student6(Student6 s) // Copy Constructor
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
}
class CopyCons
{
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan"); //parameterized constructor
Student6 s2 = new Student6(s1); // copy constructor
s1.display();
s2.display();
}
}
Types
- compile time polymorphism
- operator overloading (not supported in java but supported in C++)
- method overloading
- runtime polymorphim
- Polymorphism : when a method is called, java matches up the method name and
then the number & type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.
If a class have multiple methods by same name but different parameters and
performing different set of activities, it is known as Method Overloading.
Advantage of method overloading:
Method overloading increases the readability of the program
Static Members
-The members that are declared static are called static members. Since these
members are associated with the class itself rather than individual objects, the
static variables and methods are also known as class variables and class methods.
- Static variables are used when we want to have a common variable name to all
instances of a class.
- Like static variables, static methods can be called without using the objects.
•The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
•The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Java static property is shared to all objects.
For example, the Math class of java library defines many static methods to perform
math operations that can be used in any program.
float x=Math.sqrt(25.0);
Inheritance:Extending a class
Inheritance is the concept of extending the features of existing class to a
newly derived class. The Class which is giving properties to a new class is called
as parent class or base class or super class. The class which is inheriting the
properties of parent class is called as child class or sub or derived class.
-The new class will have the combined features of both old and new class.
-Inheritance allows subclasses to inherit all the variables and methods of their
parent classes.
Types of Inheritance
1. Single inheritance (only one super class)
2. Multiple inheritance (a class with several super classes)
3. Hierarcheal inheritance(one super class, many sub classes)
4. Multilevel inheritanace(derived from a derived class(intermediate base class)
5. Hybrid inheritance(combination of multipath forms of inheritances ie multilevel
+ multiple)
6. Multipath Inheritance(creation of class from other super class which are derived
from common super class)
Note : Java does not directly implement multiple inheritance. However, this
concept is implemented using a secondary inheritance path in the form of
interfaces.
Advantages of Inheritance
1. Reusability
2. Elimination of duplication of code
3. Time
4. Size
Syntax:
class subclassname extends superclassname
{
Variables declaration
Methods Declaration
}
The keyword “extends” signifies the properties of superclass name are extended to
subclassname. The sub class will now contain its own variables and methods as
well as those of the superclass.
=>Hybrid Inheritance:
The combination of more than one type of inheritance is called hybrid inheritance
//Demonstration on Hybrid inheritance:
class Base
{ Base
int x,y,z;
void setxy()
{
Derived1 Derived2
x=7;
y=5;
}
} Derived3
class Derived1 extends Base
{
void add()
{
z=x+y;
System.out.println("Sum="+z);
}
}
class Derived2 extends Base
{
void mul()
{
z=x*y;
System.out.println("product="+z);
}
}
class Derived3 extends Derived1
{
void sub()
{
z=x-y;
System.out.println("subtraction="+z);
}
}
class Hybridtest
{
public static void main(String args[])
{
Derived1 d1=new Derived1();
d1.setxy();
d1.add();
Derived2 d2=new Derived2();
d2.setxy();
d2.mul();
Derived3 d3=new Derived3();
d3.setxy();
d3.add();
d3.sub();
}
}
=>Multiple Inheritance:
If a subclass is derived from more than one super class such type of inheritance is
called multiple inheritance.
But classes in java cannot have more than one super class that means a class
cannot extend more than one class.
Java provides an alternative for multiple inheritance using interfaces.
Method Overriding:
A method defined in a super class is inherited by its subclass and is used by
the objects created by the subclass. Method inheritance enables us to use methods
repeatedly in subclasses without having to define the methods again in subclass.
However, there may be a situation when we want an object to respond to the
same method but have different behavior when that method is called. That means,
we should override the method defined in the superclass. This is possible by
defining a method in the subclass that has the same name, same arguments and
same return type as a method in the superclass. Then, when that method is called,
the method defined in the subclass is invoked and executed instead of one in the
superclass. This is known as overriding.
Method Overriding
The process of defining a method in a sub class that has same name, same
number and same type of parameters and same return type with same method in
the super class.
In java, overriding takes place in 2 ways namely
1. replacement
2. refinement
Replacement
It is a type of overriding in which parent class functionality is overridden by
child class i.e. only child class functionality is exhibited.
Ex:
class A
{
void display()
{
System.out.println(“Iam in base class”);
}
}
class B extends A
{
void display()
{
System.out.println(“Iam in child class”);
}
}
class ReplaceTest
{
Public static void main(String args[])
{
B b1=new B();
B1.display();
}
}
Refinement
It is another type of overriding. In this, parent class functionality is extended
by the child class by adding new features. Here we can observe both parent class
functionality and child class functionality
Ex:
class A
{
void display()
{
System.out.println(“Iam in base class”);
}
}
class B extends A
{
void display()
{
super.display();
System.out.println(“Iam in child class”);
}
}
class RefinementTest
{
public static void main(String args[])
{
B b1=new B();
B1.display();
}
}
super keyword
super keyword is a reference variable that is used to refer immediate parent
class object.
Uses of super:
1)super is used to invoke immediate parent class method
Example:
Super.m1(); //invoke parent class method
2)super is used to invoke immediate parent class constructor
Example:
Child()
{
super(); //invoke parent class constructor
}
3)super is used to refer immediate parent class variable.
Example:
Super.i; //invoke parent class variable
// write a program to invoke the parent class variable using super keyword
class Parent
{
int i=10;
}
class child extends Parent
{
int i=20;
void m1()
{
System.out.println("\n value of i in child class="+i);
System.out.println("\n value of i in parent class="+super.i);
}
}
class Supervartest
{
public static void main(String args[])
child c1=new child();
c1.m1();
}
}
// write a program to invoke the parent class constructor using super keyword
class Parent
{
Parent()
{
System.out.println("In parent");
}
}
class Child extends Parent
{
Child()
{
super();// invoke parent class constructor
System.out.println(" In child");
}
}
class Supertest
{
public static void main(String args[])
{
Child c1 = new Child();
}
}
The private members of super class are not inherited into sub class where as
default, public, protected members are inherited.
Therefore private members of super class cannot be accessed inside or
outside of sub class where as default, public, protected members of super class can
be accessed inside or outside of sub class but outside the class using object name.
- private members are non inheritable and they can be accessed only within the
class but not outside the class
- public members are globally accessible ie within or outside the class thus
violating the data hiding concept which is one of the important concept of OOPs
- protected members are accessible within the class and the class which is
immediately derived from it.
class AccessSpecifiers
{
public static void main(String args[ ])
{
B obj=new B();
obj.show();
//System.out.println("private obj.x="+obj.x); //error
System.out.println(" public obj.y="+obj.y);
System.out.println(" protected obj.z="+obj.z);
System.out.println(" default obj.p="+obj.p);
}
}
Final keyword:
final is a keyword which is used in several different content with a variable,
method and class.
=>final is a keyword which cannot be changed .
1)final method:
A final method cannot be overriding or overridden in any of its subclass
Example:
class Base
{
final void display()
{
System.out.println("In Base display");
}
}
class Derived extends Base
{
/*void display()
{
System.out.println("In Derived display");
}*/
void print()
{
System.out.println("In Derived print");
}
}
class Finalmethod
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.print();
}
}
2)final class:
A class is declared as final cannot be extends to further subclass
Example:
class Base
{
final void display()
{
System.out.println("In Base display");
}
}
/*class Derived extends Base
{
}*/
class Finalclass
{
public static void main(String args[])
{
Base b1=new Base();
b1.display();
}
}
3)final variable:
Final variable cannot be changed.
Example:
Class Finaltest
{
public static void main(String args[])
{
final int i=10;
// i=i+10;
System.out.println(“i=”+i);
}
}
Abstract classes and methods:
=> We have seen that by making a method final we ensure that the method is
not redefined in a subclass i.e the method never be subclass
=> Java allows us to something that is exactly opposite to this i.e. we can
indicate that a method must always be redefined in a subclass thus making
overriding compulsory this is done by using the keyword abstract in the method
definition.
=> We cannot create object for an abstract class.
=> The abstract class can be used for holding subclass object
=> Any class that has at least one abstract method has to be compulsory
declared as an abstract class
=> abstract class can contain both abstract and non abstract method
=> An abstract method has no body.
=> child class needs to override the definition of all abstract methods.
//Exampe1:
abstract class Parent
{
abstract void m1();
void show()
{
System.out.println("In parent show");
}
}
class Child extends Parent
{
void m1()
{
System.out.println("In child");
}
void display()
{
System.out.println("In child display");
}
}
public class Abstest
{
public static void main(String arg[])
{
Child c1=new Child();
c1.m1();
c1.display();
c1.show();
}
}
//Example2:
abstract class Shape
{
abstract void draw();
void display()
{
System.out.println("In shape display");
}
}
class Circle
extends Shape
{
void draw()
{
System.out.println("In draw");
}
/* void show()
{
System.out.println("In circle show");
}*
}
class Square extends Shape
{
void draw()
{
System.out.println("In square");
}
/*void print()
{
System.out.println("In square print");
}*/
}
public class Abstest1
{
public static void main(String arg[])
{
Shape s1;
s1=new Circle();
s1.display();
s1.draw();
// s1.show();
Shape s2;
s2=new Square();
s2.display();
s2.draw();
//s2.print();
}
}
Interfaces:
- Interface is a kind of class which contains methods and variables with a
difference.
- The difference is that interface defines only abstract methods and final fields.
This means that interfaces do not specify any code to implement these methods and
data fields contain only constants.
=>Therefore, it is the responsibility of the class that implements a interface to
define the code for implementation of these methods.
Syntax:
interface <interfacename>
{
variable declaration;
methods declaration;
}
Declaration of Variables:
final type variablename=value;
Declaration of Methods:
returntype methodname(parameterlist);
Example:
interface product
{
static final int code=999; //final variable
static final String name="xyz:";
void display(void); //abstract method
}
Note :
- Code for the method is not included in the interface and the method declaration
simply ends with ;
- The class that implements this interface must define the code for the method.
Example:
interface Area
{
final static float pi=3.142F; //final variable
//final method which cannot be overidden
final calculate(float a,float b);
void show(void); //abstract method
}
=>Implementing Interface:
A class can implement interfaces by using implements keyword
Syntax:
class classname implements interfacename
{
Body of class
}
// Implementing interface and accessing interface variable(single inheritance)
interface Base
{
int i=20;
public void display();
}
class Derived implements Base
{
public void display()
{
System.out.println(“in Derived display”);
}
public void show()
{
System.out.println(“in Derived show”);
}
}
calss Interfacetest
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.show();
System.out.println(“i=”+Base.i);
}
}
Extending interfaces
Like classes, interfaces can be extended. That is interface can be subinterfaced
from other interfaces.
Syntax:
interface <interfacename2> extends <interfacename1>
{
body of interface2
}
For example, we keep all constants in one interface & the methods in the other.
Example:
interface Itemconstants
{
static final int pcode=999; //final data members
static final string name="TV";
}
interface Item extends Itemconstants
{
void display(void); // declaration of abstract method
}
Note : The interface Item would inherit both the constants code and name into it.
=>We can also combine several interfaces together into a single interfaces.
Example:
interface name1
{
}
interface name2
{
}
interface name3 extends name1,name2
{
}
//Example1 :interface extending other interface(Multilevel inheritance with
interfaces).
interface A A Interface
{
public void display();
} B Interace
interface B extends A
{
public void print();
C class
}
Class C implements B
{
public void display()
{
System.out.println(“In diasplay”);
}
public void print()
{
System.out.println(“In print”);
}
public void show()
{
System.out.println(“In show);
}
}
class Multileveltest
{
public static void main(String args[])
{
C c1=new C();
C1.display();
C1.show();
C1.print();
}
}
interface A
{ A => Interface
public void display();
}
class B implements A
{ B => classs C => class
public void display()
{
System.out.println(“In class B display”);
}
public void print()
{
System.out.println(“In class B print”);
}
}
Class C implements A
{
public void display()
{
System.out.println(“In class C display”);
}
public void show()
{
System.out.println(“In class C show”);
}
}
Class Heirarchicaltest
{
public static void main(String args[])
{
B b1=new B();
b1.display();
b1.print();
C c1=new C();
c1.display();
c1.show();
}
}
This shows that a class can extend another class while implementing interfaces.
interface A
{
public void display(); A =>interface B => class
}
class B
{
C =>class
public void show()
{
System.out.println(“In class B show”);
}
Class C extends B implements A
{
public void display()
{
System.out.println(“In class C display”);
}
public void print()
{
System.out.println(“In class C print”);
}
}
Class Mulpleinhtest
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.show();
c1.print();
}
}
Packages
One of the important features of OOP is its ability to reuse the code which
is already created and is achieved by extending classes (inheritance) and
implementing the interfaces but the same is limited to reusing the classes within a
program.
Packages in java are used to reuse classes from other programs without
physically copying them into the program under development which are very much
similar to "class libraries" in other languages.
Packages are way of grouping a variety of classes and/or interfaces
together which is done according to functionality which acts as container of
classes.
Benefits of packages:
1. The classes contained in the packages of other programs can be easily reused
2. In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have same name which may be
referred by their name comprising of package name and class name.
3. Packages provide a way to “hide” classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding” ie first we
design classes and decide their relationships and then we can implement the java
code needed for the methods. It is possible to change the implementation of any
method without affecting the rest of the design.
There is a need to use different set of classes, one for internal representation of
our programs data and the another for external representation ie we have to build
our own classes for handling of our own data and use existing class libraries for
designing user interfaces.
=>java.lang: Language support classes. These are classes that Java compiler
itself uses and therefore they are automatically imported which include classes for
primitive types, strings, math functions, threads and exceptions.
=>java.util: Language utility classes like vectors, hash tables ,random numbers,
date etc
=>java.io: Input/Output support classes. They provide facilities for input
and output of data
=>java.awt : Set of classes for implementing graphical user interfaces(GUI).
They include classes for windows, buttons, lists, menus and so on.
=>java.net : Classes for networking. They include classes for
communicating with local computers as well as internet servers.
=>java.applet : Classes for creating & implementing applets.
java
awt -> package containing awt package
Color
Graphics
Example:
To refer the class color in the awt package
java.awt.color
where awt is a package within the package java and the hierarchy is represented
by separating the levels with dots.
Naming Conventions
Syntax:
package <packagename>
public class <classname>
{
------
------
}
example:
1. where myfirstpackage is the name of the package and the class Firstclass is a
class which is a part of this package myfirstpackage.
2. The above should be saved as Firstclass.java and should be located in a direcory
named myfirstpackage.
When the source file is compiled, java will create .class file and stored in the
same directory
Note:
The .class files must be located in a directory that has the same name as the
packagename and this directory should be a sub directory of the directory where
classes that will import the package are located.
where package1 is the name of top level package , package2 is the name of the
package that is inside package1 and so on. Finally, class name is specified and
statement must be ended with ;.
The import statement should appear before any class definitions in a source file.
Multiple import statements are allowed.
example:
import firstPackage.secondPackage.MyClass;
After defining this statement, all the members of the class MyClass can be directly
accessed using the class name or its objects directly without using the package
name.
syntax:
import packagename.*;
package p1;
public class Testpack
{
public void display()
{
System.out.println(“In display)
}
}
C:\java1\p1>javac Testpack.java
C:\java1\p1>edit Ptest.java
import p1.Testpack;
public class Ptest
{
public static void main(String args[])
{
Testpack tp=new Testpack();
tp.display();
}
}
=>compile the program
C:\java1\p1>javac –d C:\java1\p1 Ptest.java
=>execute the program
C:\java1\p1>java Ptest
Output: In display
=>create a directory
C:\>md arithmetic
C:\>cd arithmetic
C:\arithmetic>
package arithmetic;
public class Mymath
return x+y;
return x-y;
return x*y;
return x/y;
return x%y;
}
=>Save and exit
C:\arithmetic>javac Mymath.java
C:\arithmetic>cd..
import arithmetic.*;
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
C:\<set classpath=C:\;.;
C:\>javac Aptest.java
C:\java Aptest
Strings
In Java, strings are classs objects and implemented using two classes , namely
String and StringBuffer
declaration of string
String <stringname>;
stringname=new String(“string”);
ex:
String str;
Str=new String(“college”);
( or )
ex:
String str=new String(“college”);
String Array
The group of strings in a single array is string array.
Syntax:
String Methods:
6. replace() – replaces the old character with new character in the string
character by character/
ex:
String str=new String(“vaagdevi”);
str.replace(‘g’,’j’);
8. substr() – extracts the part of the string from the main string by extracting
number of characters from the position specified.
ex:
String str=new String(“vaagdevi degree and pg college”);
str.substr(3,4);
import java.io.*;
import java.lang.*;
class stringmethods
{
public static void main(String args[])
{
String str1=new String(“vaagdevi”);
String str2=new String(“VAAGDEVI”);
String str3=new String(“college”);
System.out.println(“string length is :”+str1.length());
System.out.println(“string in uppercase is :”+str1.toUpperCase());
System.out.println(“string in lowercase is :”+str2.toLowerCase());
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.replace(‘g’,’j’));
System.out.println(str1.substr(3));
System.out.println(str1.substr(3,4));
System.out.println(str1.charAt(3));
System.out.println(str1.length());
System.out.println(str1.concat(str3));
}
}
StringBuffer Class:
String creates strings of fixed length, StringBuffer creates strings of flexible length
that can be modified in terms of both length and co ntent.
=>s1.setCharAt(n,’x’)
=>s1.append(s2)
=>s1.insert(n,s2)
=>s1.setLength(n)
Vectors:
Vector class contained in java.util package. This class can be used to create a
generic dynamic array known as vector that can hold objects of any type and any
number.
=>We cannot directly store simple data type in a vector, we can store only objects,
therefore we need to convert simple types to objects. This can be done using the
wrapper classes.
Wrapper classes:
Vectors cannot handle primitive data types like int, float, long, char, and double.
Primitive data types may be converted into objects by using the wrapper classes
contained in the java.lang package
=>Simple data types and their corresponding wrapper class types
Simple Type Wrapper class
Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long
=>Converting Primitive numbers to Object number using constructor
methods:
Integer IntVal=new Integer(i); //Primitive integer to Integer object
Float FloatVal=new Float(f); //Primitive float to Float object
Double DoubleVal=new Double(d); //Primitive double to Double object
Long LongVal=new Long(l); //Primitive long to Long object
For example:
Double d_object=98.42;
double d_primitive=d_object.doubleValue();
using the autoboxing and unboxing feature, we can rewrite the above code as:
Double d_object=98.42;
double d_primitive=d_object;
UNIT-III
Exception
Managing Errors & Exception Handling:
Error is bugs which make a program go wrong.
Types of Errors
1. Compile-time errors
2. Run-time Errors
Compile-time errors
These are the syntax errors which are detected and displayed by the java
compiler. Whenever compiler displays an error, it will not create the .class file. It
is therefore necessary that we fix all the errors before we can successfully compile
& run the program.
Exception Handling:
If we want the program to be continued with the execution for the remaining code,
then we should try to catch the exception object thrown by the error condition and
then display an appropriate message for taking corrective actions. This task is
known as exception handling.
Tasks performed by error handling code
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
Categories of exceptions in java
Checked exceptions - These exceptions are explicitly handled in the code itself
with the help of try & catch blocks. Checked exceptions are extended from the
java.lang.Exception class.
. Unchecked exceptions - These exceptions are not essentially handled in the
program code, instead JVM handles such exceptions. Unchecked exceptions are
extended from the java.lang.Runtime.Exception.
NOTE : Checked & Unchecked exceptions are absolutely similar as far as their
functionality is concerned, but the difference lies only in the way they are handled.
- The try block can have one or more statements that could generate an exception.
If anyone statement generates an exception, the remaining statements in the block
are skipped and the execution jumps to the catch block that is placed next to the try
block.
- The catch block can also have one or more statements that are necessary to
process the exception.
NOTE : Every try statement should be followed by at least one catch statement
otherwise compilation error occur.
//demonstration of usage of try and catch block to handle arithemetic exceptio
//ExceptionArith.java
import java.lang.Exception;
class ExceptionArith
{
public static void main(String args[ ])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c); //exception here
System.out.println("value of x="+x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero ");
}
y=a/(b+c);
System.out.println("value of y="+y);
}
}
o/p
Division by Zero
y=1
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}
}
}
o/p:
Array index is out of bounds
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y=a[1] / a[0];
System.out.println("value of y="+y);
}
}
o/p
Array index is out of bounds
value of y=2
finally statement
It is used to handle an exception that is not caught by any of the previous catch
statements. Finally block can be used to handle any exception generated within a
try block. It may be added immediately after the try block or after the last catch
block.
1)try
{
-----------
-----------
}
finally
{
----------
-----------
}
2)try
{
---------
---------
}
catch(-----)
{
------
------
}
catch(----)
{
-------
-------
}
.
.
.
finally
{
-------
------
}
// catch(ArithmeticException e)
// {
// System.out.println("Division by zero");
// }
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
finally
{
// int y=a[1] / a[0];
//System.out.println("value of y="+y);
System.out.println("Division by zero");
}
}
}
o/p
Division by zero
// Array index is out of bounds
// value of y=2
Syntax:
throw new throwable's subclass;
example:
throw new MyException();
throw new NumberFormatException();
//demonstration of throwing of our exception
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[ ])
{
int x=5,y=10000;
//int x=5,y=100;
try
{
float z=(float) x / (float) y; //type casting
if(z < 0.01) //raising an userdefined exception(checked) explicitly basing on
condition
{
throw new MyException("number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage( ) );
// getMessage() method displays message "Number is too small" caught by
catch block sent
// by object e
}
finally
{
System.out.println("Good Luck. Better try next time");
}
}
}
o/p
Caught my exception
Number is too small
Good Luck. Better try next time
NOTE :
The above example demonstrates the use of user-defined subclass of
Throwable class ie Exception is a subclass of Throwable and therefore
MyException is a subclass of Throwable class. An object of a class that extends
Throwable can be thrown and caught.
Throws Clause:
There could be certain situations where there is a possibility that a method
might throw certain kinds of exceptions but there is no exception handling
mechanism within the method. In such case, it is important that the method caller
is intimated explicitly that certain types of exceptions could be expected from the
caller method, and the caller must get prepared with some catching mechanism to
deal with it.
The throws clause is used in such a situation which is specified immediately
after the method declaration statement and just before the opening brace.
//use of throws
//ExampleThrows.java
import java.lang.Exception;
class ExampleThrows
{
static void divide( ) throws ArithmeticException
{
int x=22,y=0,z;
z=x/y;
System.out.println("value of z ="+z);
}
public static void main(String args[ ])
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println("Caught the exception "+e);
}
}
}
o/p
Caught the exception java.lang.ArithmeticException: / by zero
Once initiated by the main thread, the threads A,B and C run concurrently and
share the resources jointly. It is just like a Joint Family sharing resources among all
of them.
The ability of a language to support multithreads is referred as concurrency.
Since threads in java are subprograms of a main application program and share the
same memory space, they are known as lightweight threads or lightweight
processes.
Applications of Multi Threading
Threads are extensively used in java-enabled browsers like HotJava. These
browsers can download a file to the local computer, display a web page in the
window, output another web page to a printer and so on.
Multithreading Multitasking
1.It is programming concept in which 1. It is an O/S concept in
a program or a process is divided into which multiple tasks are
two or more sub programs or threads performed simultaneously.
that are executed at the same time in
parallel.
Creating threads:
Threads are implemented in the form of objects that contain a method called
run() which is the heart and soul of any thread.
The run() method should be invoked by an object of the concerned thread which
can be achieved by creating the thread and initiating it with the help of another
thread method called start().
1. By creating a thread class - Define a class that extends thread class and override
its run() method with the code required by the thread.
NOTE : when a new thread is started, java call's the threads' run( ) method, so it is
in the run( ) where all the action takes place.
The first line initiates a new of class MyThread which just creates the object.
The thread that will run this object is not yet running. The thread is in a newborn
state.
The second line calls the start( ) method causing the thread to move into
runnable state. Then, the java runtime will schedule the thread to run by invoking
its run( ) method. Now, the thread is said to be in the running state.
NOTE : The program creates three threads A,B and C undertaking 3 different
tasks.
The statement,
new A( ).start( );
// in the main thread is the way of starting a thread
which is equivalent to
A threadA=new A( );
threadA.start();
Immediately after threadA is started, there will be two threads running in the
program ie main thread and the thread A. The start( ) method returns back to the
main thread immediately after invoking the run( ) method, thus allowing the main
thread to start the thread B. Similarly, it starts C thread. By the time, the main
method has reached the end of its main method, there are total of four(4) seperate
threads running in parallel.
Stopping a thread
Blocking a thread
A thread can also be temporarily suspended or blocked from entering into
runnable and running state by using either
sleep( ) // blocked for a specified time
suspend( ) // blocked until further orders
wait( ) // blocked until certain condition occurs
These methods cause the thread to go into blocked or not/non-runnable state. The
thread will return to the runnable state when the specified time is elapsed in the
case of sleep(), the resume() method is invoked in the case of suspend(), and the
notify() method is called in case of wait().
Following are the different states that occur, during the life time of a thread
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn state
when a thread is created, the thread is born and said to be in newborn state ie the
thread is not yet scheduled for running.
At this position, we can do
- schedule it for running using start() method. If scheduled, it moves to runnable
state
- kill using stop() method
Runnable state
Means that the thread is ready for execution and is waiting for the availability of
the processor. That is, the thread has joined the queue of threads that are waiting
for execution. If the thread have equal priority,
they are given time slots in round robin fashion ie First come - first serve(FIFO)
basis. This process of assigning time to threads is known as time-slicing. However,
if we want a thread to relinquish control to another thread to equal priority before it
turn comes, yield() method can be used.
Running state
Running means the processor has given 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.A running thread may relinquish its control in one of
following situations
1. It has been suspended using suspend() which can be revived using resume(). It
is used when we want to suspend a thread for some time due to some reason but
do not want to kill it.
Relinquishing control using suspend() method
2. Sleep(time) method is used to make a thread to sleep for specified time period
where time is in milli seconds which means that thread is out of queue for some
time and thread reenters the runnable state as soon as the time period is elapsed.
3. Wait( ) method is used to make the thread wait until some event occurs and the
thread can be sheduled to run again using notify() method.
Dead state
Every thread has a life cycle and a running thread end its life when it has
completed executing its run() method. It is a natural death. However, we can kill it
by sending the stop message to it at any state thus causing premature death to it. A
thread can be killed as soon as it is born, or while it is running or even when not is
in "not runnable"(blocked) condition.
class ThreadMethods
{
public static void main(String args[ ])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
NOTE :
1) uses the yeild() method in thread A at the iteration i=1. Therefore, the thread A
although started first, has relinquished control to thread B. The stop() method in
thread B as killed it after implememting the for loop only 3 times. Mind that it has
not reached end of run(). (pre mature death). The thread C started sleeping after
executing the for loop only once. When it woke up (after 10000 mill seconds), the
other 2 threads have already completed their runs and therefore was running alone.
The main thread died much earlier than the other 3 threads.
2) The call to sleep( ) method is enclosed in a try block and followed by catch
block() which is necessary because the sleep( ) method throws an exception which
should be caught.If we fail to catch the exception, program will not compile.
Thread Exceptions
Java run system will throw illegalThreadStateException whenever attempt is
made to invoke a method that a thread cannot handle in given state. For example, a
sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions and the same is true for suspend() method when it
is used on a blocked(Not Runnable) state.
catch (ThreadDeath e)
{
----------- // killed thread
-----------
}
catch(Interruptedexception e)
{
catch(IllegalArithmeticException e)
{
Thread Priority
In java, each thread is assigned a priority, which effects the order in which
it is scheduled for running. The threads which are discussed so far are of same
priority. The threads of the same priority are given equal treatment by java
scheduler, they share the processor on first come, first serve basis.
Priority of a thread can be set using setPriority() method
syntax:
Threadname.setPriority(intNumber);
intNumber is an integer value to which thread's priority is set. The Thread class
defines several priority constants
MIN_PRIORITY=1
NORM_PRIORITY=5(default)
MAX_PRIORITY=10
Whenever multiple threads are available for execution, the Java system
chooses the highest priority thread and executes it.
For a thread of lower priority to gain control, one of the following things should
happen
1. It stops running at the end of run( )
2. It is made to sleep using sleep( )
3. It is hold to wait using wait( )
However, if another thread of highest priority comes along, currently running
thread will be preempted by incoming thread thus forcing the current thread to
move to the runnable state.
class ThreadPriority
{
public static void main(String args[ ])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
// threadB.setPriority(threadA.getPriority()+1);
threadB.setPriority(Thread.NORM_PRIORITY);
threadA.setPriority(Thread.MIN_PRIORITY);
Synchronized (lock-object)
{
---------------- // code here is synchronized
---------------
}
Whenever a thread has completed its work of using synchronized method (or
block of code), it will hand over the monitor to the next thread that is ready to use
the same resource.
An interesting situation may occur when two or more threads are waiting to
gain control of a resource. Due to some reasons, the condition on which the
waiting threads rely on to gain control does not happen. These results what is
known as deadlock?
For example, assume that the thread A must access method1 before it can
release method2 but the thread B cannot release method1 until it get holds of
method2. Because these are mutually exclusive conditions, a deadlock occurs.
Thread A
{
Synchronized method2()
{
Synchronized method1()
{
-------
-------
}
}
Thread B
{
Synchronized method1()
{
Synchronized method2()
{
-------
-------
}
}
// Runnable interface
//RunnableTest.java
class X implements Runnable //step1
{
public void run() // step2
{
for(int i=1;i<=10;i++)
{
System.out.println("Thread x="+i);
}
System.out.println("End of Thread X");
}
}
class RunnableTest
{
public static void main(String args[])
{
X Runnable = new X();
Thread threadx = new Thread(Runnable); //step 3
threadx.start(); //step 4
System.out.println("end of main threead");
}
}
Java I/O (Input and Output)
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream
InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure
given below.
OutputStream class
Method Description
OutputStream Hierarchy
InputStream class
Method Description
1) public abstract int reads the next byte of data from the
read()throws IOException input stream. It returns -1 at the end of
the file.
2) public int returns an estimate of the number of
available()throws bytes that can be read from the current
IOException input stream.
InputStream Hierarchy
If you have to write primitive values into a file, use FileOutputStream class. You
can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to
use FileWriter
FileOutputStream class declaration
void write(byte[] ary, It is used to write len bytes from the byte
int off, int len) array starting at offset off to the file output
stream.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileOutputStream example 2: write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java ";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
int read() It is used to read the byte of data from the input
stream.
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be
created.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
UNIT-IV
Applets
Applications written for www is commonly referred as applets. Applets are
web based applications which are used to write GUI applications.
Types of applets
Applets can be embedded into WebPages in 2 ways i.e we can write our own
applets and embed them into web pages or down load from remote system and
embed into webpage.
1. local applets
2. remote applets
local applet - an applet developed locally and stored in a local system is known as
local applet.
java.awt.Component
|
java.awt.Container
|
java.awt.Panel
|
java.applet.Applet
running state
Applet enters into this state when the system calls the start() method of Applet
class which occurs automatically after the applet is initialized .
Starting can also occur , if the applet is already in "stopped"(idle) state.
Dead state
An applet is said to be dead when it is removed from memory which occurs
automatically by invoking the destroy() method when we quit the browser.
NOTE : like initialization, destroying stage occurs only once in the applets life
cycle.
Display state
Applet moves to display state whenever it has to perform output operations on
the screen which happens immediately after the applet enter into running state.
paint() method is called to accomplish the task.
public void paint(Graphics g) //applet code imports the java.awt package that
contains the Graphics class
{
---- //applet code here
}
3) Body section - it contains the information about the web page and its behaviour.
<BODY>
<CENTER>
<H1> Welcome to the world of Applets </H1>
</CENTER>
<BR>
<APPLET ------>
</APPLET>
</BODY>
Applet tag
The <APPLET ...> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires.
<BODY>
<CENTER>
<APPLET>
=======
=======
</APPLET>
</CENTER>
</BODY>
//HelloJava.java
import java.io.*;
import java.awt.*;
import java.applet.*;
d:\rjv>appletviewer HelloJava.html
<HTML>
<HEAD>
---
<TITLE> ----- </TITLE>
<BODY>
----
----
</BODY>
</HEAD>
</HTML>
ex:
<APPLET>
<PARAM = COLOR VALUE="red">
</APPLET
ex:
<APPLET>
<PARAM NAME=text VALUE = " JAVA IS TRUE OOPL">
</APPLET>
NOTE : passing parameters to an applet code using <PARAM> tag is similar to
passing parameters to main() method using command line arguments which are
passed to an applet when it is loaded.
To set up and handle parameters,
//java program
//HelloJavaParameter.java
import java.io.*;
import java.awt.*;
str="HELLO"+str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
o/p HELLOApplet!
note : now remove <PARAM> Tag from HTML file and run again.
//HelloJavaParameter.html
//HTML program
<HTML>
<!Parameterized HTML file with PARAM TAG>
<HEAD>
<TITLE>Welcome to java Applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE="HelloJavaParameter.class width=400 height=200>
<PARAM NAME="string" value ="Applet!">
</APPLET>
</BODY>
</HTML>
Running an applet
d:\rjv>appletviewer HelloJavaParameter.html
//HelloJavaParameter1.html
//HTML program
<HTML>
<!Parameterized HTML file without PARAM TAG>
<HEAD>
<TITLE>Welcome to java Applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE="HelloJavaParameter.class"
width=500
height=200 >
// <!PARAM NAME="string" value ="Applet!">
</APPLET>
</BODY>
</HTML>
//HTML program
<!align.html>
<html>
<body>
<APPLET CODE=align.class
width=500
height=200
align=right>
</applet>
</body>
</html>
Displaying numerical values
In Applets, numerical values can be displayed by first converting them into
strings and then using the drawString() of Graphics class which can be done easily
by calling ValueOf() method of String class.
<BODY>
<APPLET CODE="NumValues.class"
width=300
height=300 >
</APPLET>
</BODY>
</HTML>
getting/reading values/input from the user
Applets treats inputs as text string. so, we must first create an area of the
screen in which user type and edit input items which can be done using textField
class of applet package.
Once the text fields are create fro receiving input, we can type values in the fields
and edit.
secondly, is to retrieve the items from the fileds for display of calculations.
note : text fields contain items in string form which need to converted to the
correct form.
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception ex)
{ }
z=x+y;
s=String.valueOf(z);
g.drawString("sum is :",10,75);
g.drawString(s,100,75);
}
//HTML program
//UserInput.html
<!getting input from user>
<html>
<applet
code=UserInput.class
width=300
height=200 >
</applet>
</html>
running an applet
d:\rjv>appletviewer UserInput.html
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button,
textfield etc.
When we press a button and release it, AWT sends an instance of ActionEvent to
that button by calling processEvent on the button. The processEvent method of
the button receives the all the events, then it passes an action event by calling its
own method processActionEvent. This method passes the action event on to
action listeners that are interested in the action events generated by the button.
The object
It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the ActionEvent
is enabled on the text field, then the ActionEvent may be fired by pressing return
key. The event is handled by the ActionListener interface.
The AWT TextField class inherits the methods from below classes:
java.awt.TextComponent
java.awt.Component
java.lang.Object
import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");
The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text
area becomes larger than the viewable area, the scroll bar appears automatically
which helps us to scroll the text up and down, or right and left.
o java.awt.Component
o java.lang.Object
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits Component class.
o java.awt.Component
o java.lang.Object
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the Component
class.
In the following example, we are creating a List component with 5 rows and
adding it into the Frame.
import java.awt.*;
// main method
public static void main(String args[])
{
new ListExample1();
}
}
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it
on the JFrame object inside the main() method.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
We can also write all the codes of creating JFrame, JButton and method call inside
the java constructor.
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.
We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an application
but a user cannot edit it directly. It inherits JComponent class.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}