JAVA Notes-1
JAVA Notes-1
JAVA Notes-1
By Nitin sir
RKDEMY
DIPLOM / DEGREE ENGINEERING CLASSES
Ch :1 Basics of JAVA
What is JAVA
Java is general purpose, object-oriented programming language.
NITIN SIR 2
Nitin Sir
JAVA PROGRAMMING
• Exception Handling-
which detain serious errors and reduces all kind of threat of
crashing the system.
Security is an important feature of Java and this is the strong
reason that programmer use this language for programming on
Internet.
The absence of pointers in Java ensures that programs cannot
get right of entry to memory location without proper approval.
• Distributed
Java is called as Distributed language for constructing applications
on networks which can contribute both data and programs.
Java applications can open and access remote objects on Internet
easily.
NITIN SIR 3
Nitin Sir
JAVA PROGRAMMING
• High performance
• Java performance is very extraordinary for an interpreted language,
majorly due to the use of intermediate bytecode.
• Java architecture is also designed to reduce overheads during
runtime.
• The incorporation of multithreading improves the execution speed of
program.
NITIN SIR 4
Nitin Sir
JAVA PROGRAMMING
Java C++
Compiler compiles java source code into byte code for a machine that does not
exist, that why java virtual machine.
This machine is called the Java Virtual machine and it exits only inside
the computer memory.
NITIN SIR 5
Nitin Sir
JAVA PROGRAMMING
Java Machine
Byte Code
Interpreter code
Virtual machine Real Machine
The machine specific code is generated by Java interpreter by acting as
an intermediary between the virtual machine and real machines shown
below
Syntax:
C:\java filename
If there are syntax errors, go back to Notepad and edit the program.
NITIN SIR 6
Nitin Sir
JAVA PROGRAMMING
If it does not run correctly, go back to Notepad and edit the program.
Data Types
The data type is type of data represented by a variable.
Java data types are case sensitive.
There are two types of data types
1. Primitive data types
1. Numeric
1. Integer
2. Floating Points
2. Non-numeric means
1. Character and
2. Boolean
2. In non-primitive types, there are three categories
1. Classes
2. Arrays
3. Interface
char 2 A-Z,a-z,0-9,etc.
NITIN SIR 7
Nitin Sir
JAVA PROGRAMMING
int n1,n2,ans;
n2 = Integer.parseInt(args[1]);
n1 = Integer.parseInt(args[o]);
ans = n1 + n2;
NITIN SIR 8
Nitin Sir
JAVA PROGRAMMING
• Example :
int x = 60 ;
long y = (long) x ;
byte z = (byte) x ;
• Casting of large data type into smaller type may result in a loss of data.
• For assigning one type of data value to another type of data variables
Casting is required but java provides automatic type conversion.
• It is possible only if destination type has enough precision to store.
Example
int a = 5 ;
float b = 𝑎 ;
Operators
Operator is symbol which is used to perform operation on operand.
Arithmetic operator
NITIN SIR 9
Nitin Sir
JAVA PROGRAMMING
Relational operator
Logical operator
• OR Operator :-
NITIN SIR 10
Nitin Sir
JAVA PROGRAMMING
o The OR operator checks for any one or all conditions from the given
conditions to be true then it evaluates true.
o Otherwise if all conditions are false then it returns false.
o For example a statement
o y >5 || y <10;
o will result in “true” i.e. 1 if the value of y is greater than 5 OR less
than 10, else it will result in false i.e.0
Bitwise operator
Conditional operator
Syntax :
Program :
class Demo
NITIN SIR 11
Nitin Sir
JAVA PROGRAMMING
n1 = Integer.parseInt(args[o]);
n1 = Integer.parseInt(args[1]);
• Increment operator(++)
o Pre-increment (+ + 𝑥)
o Post-increment (𝑥 + +)
E.g. :
int x = 4 ;
int y = + + x ; //𝑦 = 5 ;
• Decrement operator(−−)
o Pre-decrement (− − 𝑥)
o Post-decrement (𝑥 − −)
E.g. :
int x = 4 ;
int y = − − x ; //𝑦 = 3 ;
NITIN SIR 12
Nitin Sir
JAVA PROGRAMMING
class Demo
{
Public static void main(String args [ ])
{
int a = 1, b = 2, c = 3;
a = (b++) + (b--);
b = b + (c--) × (--a);
System.out.println(“a = ” +a);
System.out.println(“b = ” +b);
System.out.println(“c = ” +c);
}
}
NITIN SIR 14
Nitin Sir
JAVA PROGRAMMING
1. If Statement
2. If – else Statement
3. Nested if- else Statement
4. Switch – Case
NITIN SIR 15
Nitin Sir
JAVA PROGRAMMING
1. If Statement
Syntax
if (condition)
{
Statements1;
}
the condition given with the if statement is true. Then statements1 are executed in
this case.
If the condition specified in the if statements is false then the statements named
as statements1 are not executed in this case.
2. If Else Statement
• Syntax
if (condition)
{
Statements-1;
}
else
{
Statements-2;
}
• The set of statements named as statements 1 in the above syntax are executed if
the condition given with the if statement is true.
• If the condition specified in the if statements is false then the statements named
as statements2 in the above syntax are executed.
3. Nested if-else
• In some cases we have to check multiple cases of a particular condition. In such
cases we have to use an nested if-else.
NITIN SIR 16
Nitin Sir
JAVA PROGRAMMING
Syntax:
If (condition-1)
{
if(condition-2)
statement1;
else
statement2;
}
else
{
if(condition-3)
statement13;
else
statement4;
}
In this case the first condition is checked, if it is true then statements inside that if
block are executed. But if the condition is false it goes to the else statement. Again
there is a condition with if; the statements are executed if this second condition is
true. Else it again goes to the else and again checks the condition associated with
this if statement.
Else if ladder
NITIN SIR 17
Nitin Sir
JAVA PROGRAMMING
If statement looks very confusing & complex when more conditions are
introduced.
If all conditions are false then the default statement will get executed.
Syntax
Switch (expression)
case value 1:
Statement – 1 ;
case value 2:
Statement – 2 ;
Break ;
default :
Default statement ;
NITIN SIR 18
Nitin Sir
JAVA PROGRAMMING
FOR LOOP
1. Initialization statement is executed first. They are used to initialize the value
of the variables.
2. The second step is checking the condition. If condition is true then statement
will be excited If the condition is false the execution of the loop will be
terminated.
3. The third step is to execute all the statements inside the curly braces. These
statements will be executed sequentially.
4. The fourth step is the increment / decrement or updating operations.
NITIN SIR 19
Nitin Sir
JAVA PROGRAMMING
WHILE LOOPS
Statements;
} operation of the while loop is such that, first the condition is checked.
The
If the condition is true, then the statements are executed. Once the statements are
executed, the condition is again checked and this keeps on repeating, until the
condition is false.
If the condition is false, the statements insides the loop is not executed, instead
the control directly comes out of the loop.
DO-WHILE LOOPS
Eg:-
i=10;
do
{
S.o.println(“%d”);
i++;
} While (i! =0);
NITIN SIR 20
Nitin Sir
JAVA PROGRAMMING
class compare
n1 = Integer.parseInt(args[o]);
n1 = Integer.parseInt(args[1]);
NITIN SIR 21
Nitin Sir
JAVA PROGRAMMING
else
* *
* * *
* * * *
class Demo
int i, j;
System.out.print(“ * ”);
System.out.println( );
class Demo
int n = Integer.parseInt(args[o]);
while(n! = 0)
rem = n % 10;
n = n/10;
System.out.println(“Reverse = ” +rev);
NITIN SIR 23
Nitin Sir
JAVA PROGRAMMING
class Demo
int n = Integer.parseInt(args[o]);
while(n! = 0)
rem = n % 10;
n = n/10;
if(temp == rev)
System.out.println(“Palindrome number”);
Else
{
NITIN SIR 24
Nitin Sir
JAVA PROGRAMMING
System.out.println(“not a palindrome”);
class Demo
int n = Integer.parseInt(args[o]);
int n1 = 0, n2 = 1;
System.out.print(n1 + “ ” + n2);
System.out.print(“ ” + ans);
n1 = n2;
n2 = ans;
NITIN SIR 25
Nitin Sir
JAVA PROGRAMMING
class Demo
{
Public static void main(String args [ ])
{
int n = Integer.parseInt(args[o]);
int Flag = 0;
for(int i = 2; i < 2; i++)
{
if(n % i == 0)
{
Flag == 1;
break;
}
}
if(Flag = 0)
{
System.out.println(“Prime number”);
}
else
{
System.out.println(“not a prime number”);
}
}
}
NITIN SIR 26
Nitin Sir
JAVA PROGRAMMING
What is class
• Class is a user defined data type with a predefined template that
serves to define its properties.
• Any concept/logic that we want to implement in a Java program
must be encapsulated within a class.
• From class we create objects and objects use the methods to
communicate with class.
• Class provides the easy and convenient way to pack together a
logically related data items and functions that works on the data
items.
• In java the data items are called as fields and function are called
methods
Syntax
• The data or variables , defined inside the class are called as instance
variables. Data is encapsulated in a class by putting required data
fields inside the body of the class definition.
• The dot operator is used to access the instance variable from outside
the class with the objects.
e.g
class Box
{
double width;
double height;
double depth;
double area;
void GetData(double x, double y, double z)
NITIN SIR 27
Nitin Sir
JAVA PROGRAMMING
{
x=width;
y=height;
z=depth;
}
double AreaofBox()
{
area=x*y*z;
return area;
}
}
What is Object :
• An object is instance of a class or a variable of a user defined data type
class.
• Objects are created by using new operator (memory allocation
operator).
• The new operator creates an object of the specified class and returns a
reference to the object created.
• The new() operator dynamically allocates memory for an objects and
returns a reference to it.
For example
Rectangle Rec;
NITIN SIR 28
Nitin Sir
JAVA PROGRAMMING
class Rectangle
{
int length;
int breath;
void getdata(int a, int b)
{
length = a;
breath = b;
}
int calculate()
{
int area;
return (area);
}
}
NITIN SIR 29
Nitin Sir
JAVA PROGRAMMING
class Demo
{
Public static void main(String args[])
{
Rectangle rect = new Rectangle[ ];
int area=rect.calculate()
WAP to create to a class one having data member access name, Balance.
Accept and display data one objects.
class Account
int acc_no;
string name;
float balance;
acc_no = a;
name = n;
NITIN SIR 30
Nitin Sir
JAVA PROGRAMMING
balance = b;
void putdata()
class Demo
{
Public static void main(String args[])
{
Account acc = new Account[ ];
acc.putdata();
Array of object
Syntax
Example
Rectangle R[5];
NITIN SIR 31
Nitin Sir
JAVA PROGRAMMING
Create class employee with data member, name and salary accept data for five
objects and display it.
import java.io.*;
import java.lang.*;
class Employee
int emp_id;
string name;
int salary;
void getdata()
System.out.println(“enter emp_id”);
emp = Integer.parseInt(br.readline());
System.out.println(“enter name”);
name = br.readline();
System.out.println(“enter salary”);
salary = Integer.parseInt(br.readline());
void putdata()
NITIN SIR 32
Nitin Sir
JAVA PROGRAMMING
System.out.println(“Emp_Name = ” + name);
System.out.println(“salary = ” + salary);
class Demo
{
Public static void main(String args[])
{
Employee e[ ] = new Employee[5];
for(int i=0; i<5; i++)
{
e[i] = new Employee();
}
for(int i=0; i<5; i++)
{
e[i].getdata();
}
for(int i=0; i<5; i++)
{
e[i].putdata();
}
}
}
NITIN SIR 33
Nitin Sir
JAVA PROGRAMMING
class Rectangle
{
int length;
int breath;
Rectangle (int l, int b)
{
length = l;
breath = b;
}
}
int Area()
{
int a;
a = length*breath;
return(0);
}
Class Demo
{
Public static void main(String args[])
{
Rectangle r = new Rectangle(10,20);
int a;
a=r.area();
NITIN SIR 34
Nitin Sir
JAVA PROGRAMMING
System.out.println(“Area =”+a);
}
Characteristics :
• It performs automatic initialization of an object.
• Constructors have same name as the class name.
• The constructor returns the instance of the class itself. So it returns
nothing or they do not specify a return type not even void.
Default Constructor :
When no constructor has been explicity defined , then Java creates a
default constructor for the class.
class Box
double width;
double height;
double depth;
Box()
System.out.println("Constructing Box");
width = 10;
height = 10;
NITIN SIR 35
Nitin Sir
JAVA PROGRAMMING
depth = 10;
double volume()
Parameterised Constructor :
When the parameters are added to the constructor or when constructor
takes parameter then it is called as parameterized constructor.
e.g
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo
NITIN SIR 36
Nitin Sir
JAVA PROGRAMMING
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
This keyword:
• Sometimes a method will need to refer/denote to the object that
invokes it.
• To allow this, Java defines the this keyword. t his can be used inside any
method to refer to the current object. Following example shows the
example of this keyword.
Box(double width, double height, double depth)
this.width = width;
this.height = height;
this.depth = depth;
NITIN SIR 37
Nitin Sir
JAVA PROGRAMMING
Method Overloading
In Java it is possible to define two or more methods within the same
class that share the same name, but their parameter declarations are different.
In this case the methods are called as overloaded, and the process is
referred as method overloading.
e.g
class Over
{
float a;
static final float PI=3.14f;
void area(float r)
{
float redius;
a=0.5f*PI*r*r;
System.out.println("Area of circle is:"+a);
}
void area(float l, float b)
{
NITIN SIR 38
Nitin Sir
JAVA PROGRAMMING
a=l*b;
System.out.println("Area of square is:"+a);
}
void area(int h, int b)
{
a=b*h;
System.out.println("Area of triangle is:"+a);
}
}
class OverloadingDemo
obj.area(52.67f);
obj.area(5,4);
obj.area(7.65f,2.0f);
Static Members
NITIN SIR 39
Nitin Sir
JAVA PROGRAMMING
• When the class is loaded the static variables are created first.
• When the member is declared as static it can be accessed before any object
of its class is created, and without reference to any object.
• Both methods and variables can be declared as static.
• The most common example of static member or method that is used so far
is main(). main() is declared as static because it must get executed before
any object is created/existed.
• Generally variables declared as static are global variables.
• When object of its class are declared, no copy of static variable is created,
instead all instances of the class share the same static variable.
• While using static method or members following rules must be followed:
1. They can only call other static methods.
2. They must access only static data.
3. They cannot refer to this or super in any condition
Garbage Collection :
Finalize method
• The finalize() method is called by garbage collection of an object when
garbage collection determines that there are more reference to the
objects.
NITIN SIR 40
Nitin Sir
JAVA PROGRAMMING
Arrays
• Types of Array
• There ar e two types of array.
NITIN SIR 41
Nitin Sir
JAVA PROGRAMMING
o Multidimensional Array
Syntax
dataType arrayName[ ];
arrayName=new datatype[size];
Example :-
class B
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
NITIN SIR 42
Nitin Sir
JAVA PROGRAMMING
Multidimensional array
Data is stored in row and column based index (also known as matrix
form).
Syntax
dataType [ ]arrayRefVar[ ];
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
NITIN SIR 43
Nitin Sir
JAVA PROGRAMMING
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class B
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
NITIN SIR 44
Nitin Sir
JAVA PROGRAMMING
Strings
The String class is commonly used for holding and manipulating strings of
text.
• In java, strings are class objects and implemented using two classes
namely, String and StringBuffer.
String name;
name = new String(“John");
Strings can also be created using the + operator. The + operator, when
applied to Strings means concatenation.
”Problem".length(); 7
Method — substring
television
NITIN SIR 46
Nitin Sir
JAVA PROGRAMMING
Methods — Concatenation
int num = 2;
result += word3;
name.indexOf (‘P'); 0
name.indexOf (‘e'); 2
name.indexOf (“George"); 10
name.indexOf (“Bob"); -1
name.lastIndexOf (‘e'); 15
NITIN SIR 47
Nitin Sir
JAVA PROGRAMMING
Methods — Equality
boolean b = word1.equals(word2);
boolean b = word1.equalsIgnoreCase(word2);
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
Methods — Comparison
NITIN SIR 48
Nitin Sir
JAVA PROGRAMMING
Vectors
NITIN SIR 49
Nitin Sir
JAVA PROGRAMMING
2. It contains many legacy methods that are not part of the collection
framework.
Declaring VECTORS
NITIN SIR 50
Nitin Sir
JAVA PROGRAMMING
import java.util.vector*;
import java.io.*;
class Demo
{
Public static void main(String args[ ])
{
Vector v = new Vector();
bufferedReader br = new buffered Reader (New
InputStreamReader(System.in));
System.out.println(“enter no of integer”);
int n = Interger.parseInt(br.readline());
for(int i=0; i<n; i++)
{
System.out.println(“enter an integer”);
int no = Interger.parseInt(br.readline());
v.addElement(new integer(5));
}
System.out.println(“vector contents before remove:”);
for(int i=0; i<v.size(); i++)
NITIN SIR 51
Nitin Sir
JAVA PROGRAMMING
{
System.out.println(v.get(i));
}
System.out.println(“enter index no of element to remove”);
for(int i=0; i<v.size(); i++)
{
System.out.println(v.get(i));
}
}
}
Wrapper class
NITIN SIR 52
Nitin Sir
JAVA PROGRAMMING
WAP to accept number from user and convert it into binary by using
wrapper class.
import java.io.*;
import java.lang.*;
class Wrapper
System.out.println(“enter an integer”);
n = Interger.parseInt(br.readline());
String str;
NITIN SIR 53
Nitin Sir
JAVA PROGRAMMING
Single inheritance
When one subclass is derived from one subclass or when
one new class is derived from one old class is called as single
inheritance.
A
NITIN SIR 54
Nitin Sir
JAVA PROGRAMMING
import java.io.*;
class Student
{
int roll_no;
string name;
Student(int r, string s)
{
roll_no = r;
Name = s;
}
void display()
{
System.out.println(“Roll_no =”+ rollno);
System.out.println(“name =” + name);
}
}
class Student extends Student
NITIN SIR 55
Nitin Sir
JAVA PROGRAMMING
{
string subject_name;
Exam int(int r, string s, String subject)
{
super(r,s);
subject_name = subject;
}
void display()
{
System.out.println(“subject name=”+subject_name);
}
}
class Demo
{
Public static void main(String args[ ])
{
Exam e = new Exam(101,“nitin”,“java”);
e.display();
}
}
• Syntax
abstract rect_type method_name (parameter list)
{
------
}
class Students
{
abstract students(int r)
{
-----
}
Abstract class :-
NITIN SIR 57
Nitin Sir
JAVA PROGRAMMING
1. Public access
Any variables or method declared inside the class is visible
to entire class.
3. Protected Access
When protected access is used as modifier it permits field
visible not only to all classes and subclasses in same package
but also to subclass in other package.
4. Private access
The member that are declared as private are accessible from
within the class in which they are declared.
NITIN SIR 58
Nitin Sir
JAVA PROGRAMMING
Interfaces
• Interface is similar to class which contain methods and variables but with a
major difference, the difference is that interfaces define 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.
• So it is the responsibility of the class that implements an interface to define
the code implementation of these methods.
• Syntax
interface interface_Name
{
Variable declaration;
Methods declaration;
}
• Variable declaration
static final type VariableName = Value;
• Methods declaration
return-type methodName1 (parameter_list);
Note that all variables are declared as constants. Methods declaration will contain
only a list of methods without anybody statements.
• Example:
interface Item
{
static final int code=1001;
static final String name ="Fan";
void display( );
}
NITIN SIR 59
Nitin Sir
JAVA PROGRAMMING
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber( )
{
System.out.println (" Roll No : " + rollNumber);
}
}
Class Test extends Student
{
float partl, part2;
void getMarks(float ml, float m2)
{
partl = ml;
part2 = m2;
}
void putMarks( )
{
System.out.println("Marks obtained ");
System.out.println("Part 1 = " + part 1);
System.out.println("Part 2 = " + part 2);
}
}
interface Sports
{
float sportWt = 6.0F;
void putwt( );
}
class Results extends Test implements Sports
{
float total; public void putWt( )
{
NITIN SIR 60
Nitin Sir
JAVA PROGRAMMING
System.out.println(“Sports Wt = “+ sportWt);
}
void display( )
{
total = partl + part2 + sportWt;
putNumber( );
putMarks( );
putWt( );
System.out.println(“Total score = “+ total);
}
}
class Hybrid
{
public static void main (String args[ ])
{
Results studentl = new Results( );
studentl.getNumber(1234);
studentl.getMarks(27.5F, 33.0F);
studentl.display( );
}
}
Class Interface
Class is user defined type Interface is a java object.
Starts with keyword “class” Starts with keyword “interface”
Class contains one or more or no Interface contains all abstract methods
abstract methods. and final declarations.
The variables can have any access The Variables should be public, static,
specifier. final
Multiple inheritance is not possible Multiple inheritance is possible
Class can contain method definition Class contain only method
declaration
NITIN SIR 61
Nitin Sir
JAVA PROGRAMMING
PACKAGES
• Packages are containers for classes that are used to keep the class name
space compartmentalized.
• Packages are java’s way of grouping a variety of classes and/ or
interfaces together.
• The grouping is usually done according to functionality.
• Packages act as containers for classes.
• Examples of packages:
• lang, awt, util, applet, javax, swing, net, io, sql ,etc.
• Advantages of packages
o The classes contained in the package can be easily reused.
o Two classes in two different packages can have the same name.
o Package provide a way to hide classes thus preventing other
programs or packages from accessing classes that are for internal
use only.
o Provide a way of separating “design” from “coding”.
• Different Types of Packages:
There are two types of packages in Java:
o Built-in packages
o User-defined packages
• Built-in packages
• They are also called as Java API Packages.
• Java API provides a large number of classes grouped into different
packages according to functionality.
NITIN SIR 62
Nitin Sir
JAVA PROGRAMMING
User-Defined packages:
• The users of the Java language can also create their own packages.
• User-defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages.
NITIN SIR 63
Nitin Sir
JAVA PROGRAMMING
• User-defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages.
• Creating Packages
package packagename.subpackagename;
e.g
package pack;
d1 = a;
d2 = b; }
• Compile and save .java and .class file in pack directory (folder).
NITIN SIR 64
Nitin Sir
JAVA PROGRAMMING
package packagename;
3. Create a subdirectory under the directory where main source files are
stored.
NITIN SIR 65
Nitin Sir
JAVA PROGRAMMING
2. Runtime errors
• Missing semicolon
• Missing (or mismatch of) bracket in classes & methods
• Misspelling of identifiers & keywords
• Missing double quotes in string
• Use of undeclared variables
• Bad references to objects.
2. Runtime error
Sometimes a program may compile successfully creating the .class
file but may not run properly.
Such programs may produce wrong results due to wrong logic or may
terminate due to errors such as stack overflow.
When such errors are encountered java typically generates an error
message and aborts the program.
The most common run-time errors are:
• Dividing an integer by zero
• Accessing an element that is out of bounds of an array
NITIN SIR 66
Nitin Sir
JAVA PROGRAMMING
1. try:
Syntax:
try
NITIN SIR 67
Nitin Sir
JAVA PROGRAMMING
2. catch:
This block includes the actions to be taken if a particular exception
occurs.
Syntax:
catch(ExceptionType1 exOb)
A catch block that is written for catching the class Exception can catch
all other exceptions.
Syntax:
catch(Exception e)
NITIN SIR 68
Nitin Sir
JAVA PROGRAMMING
3. finally:
finally block includes the statements which are to be executed in
any case, in case the exception is raised or not.
Syntax:
finally
. . .
4. throw:
The throw keyword is used to explicitly throw an exception
Syntax
5. throws:
“throws” keyword can be used along with the method definition to
name the list of exceptions which are likely to happen during the
execution of that method.
NITIN SIR 69
Nitin Sir
JAVA PROGRAMMING
...
class Demo
int a=10,b=5,c=5;
try{
int x=a/(b-c);
NITIN SIR 70
Nitin Sir
JAVA PROGRAMMING
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
int y=a/(b+c);
System.out.println(“Y= “ +y)
super(msg);
class TestMyException
int age=-2;
NITIN SIR 71
Nitin Sir
JAVA PROGRAMMING
try {
if(age < 0)
catch (MyException e)
System.out.println(e.getMessage());
Write a program to input name and age of a person and throws an user
define exception if entered age is negative.
import java.io.*;
Negative(String msg)
super(msg);
classNegativeDemo
{
public static void main(String args[])
{
NITIN SIR 72
Nitin Sir
JAVA PROGRAMMING
int age=0;
String name;
BufferedReaderbr=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter age and name of person");
try
{
age=Integer.parseInt(br.readLine());
name=br.readLine();
if(age<0)
else
catch(Negative n)
System.out.println(n);
catch(Exception e)
NITIN SIR 73
Nitin Sir
JAVA PROGRAMMING
import java.io.*;
PasswordException(String msg)
super(msg);
classPassCheck
BufferedReaderbr=new BufferedReader(new
InputStreamReader(System.in));
try
System.out.println("Authenticated ");
}
NITIN SIR 74
Nitin Sir
JAVA PROGRAMMING
Else
catch(PasswordException e)
System.out.println(e);
catch(IOException e)
System.out.println(e);
Multithreaded Programming:-
The run() method makes up entire body of thread and is the only
method in which the threads behaviour can be implemented.
• Creating Object:
MyThread myObject = new MyThread();
NITIN SIR 76
Nitin Sir
JAVA PROGRAMMING
• Start Execution:
thr1.start();
To create thread is to create new class that extends Thread and then to
create an instance of that class.
i) Declare the class extending the Thread class. The Thread class can be
extended as follows
--------
ii) Implements the run() method That is responsible for executing the
sequence of code that the thread with execute.
--------
//Thread code
iii) Create a thread object and call the start() method to initiate the
thread execution.
NITIN SIR 77
Nitin Sir
JAVA PROGRAMMING
NITIN SIR 78
Nitin Sir
JAVA PROGRAMMING
classThreadDemo
new A().start();
new B().start();
Output –
Exit from A
NITIN SIR 79
Nitin Sir
JAVA PROGRAMMING
Thread Life Cycle Thread has five different states throughout its life. 1.
Newborn State 2. Runnable State 3. Running State 4. Blocked State 5.
Dead State
Thread should be in any one state of above and it can be move from one
state to another by different methods and ways.
1. Newborn state:
2. Runnable State:
It means that thread is ready for execution and is waiting for the
availability of the processor i.e. he thread has joined the queue and is
waiting for execution. If all threads have equal priority then they are
given time slots for execution in round robin fashion. The thread that
relinquishes control joins the queue at the end and again waits for its
NITIN SIR 80
Nitin Sir
JAVA PROGRAMMING
turn. A thread can relinquish the control to another before its turn
comes by yield().
3. Running State:
In this state processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it
is pre-empted by a higher priority thread.
4. Blocked state:
5. Dead State:
The statement causes the thread to move to a dead state. A thread will
also move to dead state automatically when it reaches to end of the
method. The stop method may be used when the premature death is
required
1) suspend() –
syntax : public void suspend()
This method puts a thread in suspended state and can be resumed
using resume() method.
2) resume()
syntax : public void resume()
This method resumes a thread which was suspended using
suspend() method.
3) yield()
syntax : public static void yield()
The yield() method causes the currently executing thread object
to temporarily pause and allow other threads to execute.
4) wait()
syntax : public final void wait() This method causes the current
thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
MIN_PRIORITY = 1
MAX_PRIORITY = 10
Thread Methods:
NITIN SIR 82
Nitin Sir
JAVA PROGRAMMING
1. setPriority:
2. getPriority:
Syntax:public intgetPriority();
e.g
for(int k=1;k<=5;k++)
classThreadPriorityDemo
NITIN SIR 84
Nitin Sir
JAVA PROGRAMMING
objC.setPriority(Thread.MAX_PRIORITY);
objB.setPriority(objA.getPriority() +1);
objA.setPriority(Thread.MIN_PRIORITY);
objA.start();
objB.start();
objC.start();
classorgrevDemo
NITIN SIR 86
Nitin Sir
JAVA PROGRAMMING
new original().start();
new reverse().start();
NITIN SIR 87
Nitin Sir
JAVA PROGRAMMING
Basically, an applet is dynamic and interactive java program that inside the
web page or applets are small java programs that are primarily used in
internet computing
– Applets.
A applet is typically embedded in a Web page and can be run from a browser.
Applets can be transported over the Internet from one computer to another.
Applet Application
Applet does not use main() method Application use main() method for
for initiating execution of code initiating execution of code
Applet cannot run independently Application can run independently
Applet are restricted from using Application are not restricted from
libraries from other language such as using libraries from other language
C or C++
NITIN SIR 89
Nitin Sir
JAVA PROGRAMMING
//implementation
Applet enters the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. start()
can also be called if the applet is already in idle state. start() may be called
more than once. start() method may be overridden to create a thread to
control the applet.
//implementation
NITIN SIR 90
Nitin Sir
JAVA PROGRAMMING
//implementation
d) Dead state:
//implementation
//implementation
NITIN SIR 91
Nitin Sir
JAVA PROGRAMMING
<APPLET
</APPLET>
• CODEBASE is an optional attribute that specifies the base URL of the applet
code or the directory that will be searched for the applet‟s executable class
file.
• CODE is a required attribute that give the name of the file containing your
applet‟s compiled class file which will be run by web browser or
appletviewer.
• ALT: Alternate Text. The ALT tag is an optional attribute used to specify a
short text message that should be displayed if the browser cannot run java
applets.
• NAME is an optional attribute used to specifies a name for the applet
instance.
• WIDTH AND HEIGHT are required attributes that give the size(in pixels) of
the applet display area.
• ALIGN is an optional attribute that specifies the alignment of the applet.
The possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE,
BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
• VSPACE AND HSPACE attributes are optional, VSPACE specifies the space,
in pixels, about and below the applet. HSPACE VSPACE specifies the space,
in pixels, on each side of the applet
NITIN SIR 92
Nitin Sir
JAVA PROGRAMMING
• PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with
the get Parameter() method.
Example
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username"); str = "Hello "+ str;
}
public void paint(Graphics g)
{
NITIN SIR 93
Nitin Sir
JAVA PROGRAMMING
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
import java.awt.*;
g.drawString(―Welcome to java‖,25,50);
3. After successfully compiling java file, it will create the .class file,
e.g Welcome.class. then we have to write applet code to add this class into
applet.
4. Applet code
NITIN SIR 95
Nitin Sir
JAVA PROGRAMMING
<html>
OR
C:\java\jdk1.7.0\bin> Welcome.html
Graphics Class
The Graphics class of java includes methods for drawing different types
of shapes, from simple lines to polygons to text in a variety of fonts.
1. drawString( ) [S-15]
Displaying String:
Syntax:
Example:
drawLine( )
Syntax :-
g.drawLine(x1,y1,x2,y2);
e.g. g.drawLine(20,20,80,80);
Syntax:
This method takes four arguments, the first two represents the x and y
co- ordinates of the top left corner of the rectangle and the remaining two
represent the width and height of rectangle.
Example:
g.drawRect(10,10,60,50);
NITIN SIR 97
Nitin Sir
JAVA PROGRAMMING
(x, y)
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.red);
g.fillRect(10,60,40,30);
g.setColor(Color.blue);
• These two methods are used to draw and fill rectangle with rounded
corner.
• These methods takes 6 arguments first four are similar to drawRect(
) method.
• The two extra arguments represents how much of corners will be
rounded.
• The drawOval() and fillOval() methods are used to draw circle and
ellipse.
• The drawOval() method takes four arguments fisrt two represent the
top left corners and other two represents width and height of oval.
Syntax :-
• drawOval(int x, int y, int w, int h);
• fillOval(int x, int y, int w, int h);
(x, y)
NITIN SIR 99
Nitin Sir
JAVA PROGRAMMING
Drawing Arcs
• The drawArc () method is used to draw arc which takes six arguments,
o first four are the same as arguments of drawOval().
o and last two represent the starting angle of the arc and the
number of degrees (sweep angle) around the arc.
• Java actually formulates the arc as an oval draws only part of it.
• Java Consider the 3 O’clock position as zero degree position and degrees
increase in anti-clockwise direction.
Syntax :-
import java.awt.*;
import java.applet.*;
g.drawArc(30,30,60,60,90,180);
g.fillArc(90,30,60,60,270,180);
g.drawOval(40,40,120,150); // Head
g.drawOval(85,100,30,30); //Nose
g.fillArc(60,125,80,40,180,180); //Mouth
g.drawPolygon(x,y, x.length);
g.drawPolyline(x, y, x.length);
(x[4], y[4])
(x[4], y[4])
(x[2], y[2])
(x[2], y[2])
Concept of Streams
• A stream in java is a path along which data flows (like river or pipe).
• Input Stream
• Output Stream
• An Input Stream extracts data from the source (file) and sends it to the
program.
• An Output stream takes data from the program and sends (i.e. writes)
it to the destination (file).
• One stream used to get raw data in binary format and then use another
stream in series to convert it to integers
Stream Classes
• The java.io package contains number of stream classes for processing all
type of data.
• The streams are unidirectional therefore java provides two types of byte
streams classes:
• Reading Bytes
• Closing streams
InputStream Methods
InputStream Methods
• readShort( )
• readLine( )
• readInt( )
• readLine( )
• readLong( )
• readChar( )
• readFloat( )
• readBoolean( )
• readUTF( )
• readDouble( )
ByteArrayInputStream:
❖ This byte array contains all the bytes provided by this stream
FileInputStream:
FilterInputStream: