JAVA Notes-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 108

Java Programming

By Nitin sir

RKDEMY
DIPLOM / DEGREE ENGINEERING CLASSES

THANE NERUL DADAR


Nitin Sir
JAVA PROGRAMMING

Ch :1 Basics of JAVA
What is JAVA
Java is general purpose, object-oriented programming language.

Features Of Java [S-19 2M]

• Compiled and interpreted.


• Platform – Independent and portable.
• Object oriented programming.
• Robust and secure.
• Distributed
• Simple and small
• High performance
• Dynamic and extensible

Compiled and interpreted

 Basically a computer language is either compiled or interpreted.


 Java comes together both these approach thus making Java a two-stage
system.
1. Java compiler translates Java code to Bytecode instructions.
2. Java Interpreter generate machine code that can be executed by
machine.

Explain the concept of platform independence and portability [4M S-19]

Platform – Independent and portable.

• Java supports the feature portability.


• Java programs can be easily moved from one computer system to
another and anywhere.
• Changes and upgrades in operating systems, processors and system
resources will not force any alteration in Java programs.

NITIN SIR 2
Nitin Sir
JAVA PROGRAMMING

Object oriented programming.


 Java is truly object-oriented language.
 In Java, almost everything is an Object.
 All program code and data exist in objects and classes.

• Robust and Secure :


i) Robust : Java is more robust language than others. As it has
two time execution strategy that is compilation and
interpretation , therefore provides reliability.
Garbage-collection is one of the features of Java
language , which reduces programmer’s task of
memory management.
ii) Secure : The programming languages which are used for
programming on internet should provide the security
as the hazard of viruses and exploitation of resources
are everywhere.

• 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.

• Simple and small


 Java is very small and simple language.
 Java does not use pointer and header files, goto statements, etc.
 It eliminates operator overloading and multiple inheritance.

NITIN SIR 3
Nitin Sir
JAVA PROGRAMMING

• Multithreaded and Interactive


 Multithreaded means managing multiple tasks simultaneously.
 Java maintains multithreaded programs.
 That means we need not wait for the application to complete one
task before starting next task.
 This feature is helpful for graphic applications.

• 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.

• Dynamic and extensible


• Java is capable of dynamically linking in new class, libraries, methods
and objects.
• Java program is support functions written in other language such as
C and C++, known as native methods.

NITIN SIR 4
Nitin Sir
JAVA PROGRAMMING

Java C++

1 Java is true OO language. C++ is basically C with OO extension.


2 does not support operator C++ supports operator overloading.
overloading.
3 It supports labels with loops It supports goto statement.
4 Java does not have template classes C++ has template classes.
5 Java compiled into byte code for the C++ code compiled into M/s code.
Java Virtual Machine.
6 Java does not support multiple C++ supports multiple inheritance of
inheritance of classes classes.
7 Runs in a protected virtual machine. Exposes low-level system facilities.
8 does not support global variable. C++ support global variable.
9 Java does not use pointer. C++ uses pointer.
10 There are no header files in Java. We have to use header file in C++.

Java Virtual Machine (JVM)


Java is compiled and interpreted language.

Compiler compiles java source code into byte code for a machine that does not
exist, that why java virtual machine.

Java Java Virtual


Program Compiler Machine
Source Code Byte Code

 This machine is called the Java Virtual machine and it exits only inside
the computer memory.

 The Virtual machine code is not machine specific.

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

Compiling and Running the program


javac (Java compiler)

Java compiler convert the source code or program in bytecode and


interpreter convert .java file in .class file.

Syntax:

C:\ javac filename.java

1. Java (Java Interpreter)

C:\java filename

 If my filename is abc.java then the syntax will be

C:\ java abc

How to compile and run the program


Steps.

 Edit the program by the use of Notepad.

 Save the program to the hard disk.

 Compile the program with the javac command. (Java compiler)

 If there are syntax errors, go back to Notepad and edit the program.

 Run the program with the java command. (Java Interpreter)

NITIN SIR 6
Nitin Sir
JAVA PROGRAMMING

 If it does not run correctly, go back to Notepad and edit the program.

 When it shows result then stop.

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

Datatypes with size and range

Data type Size (byte) Range

byte 1 -128 to 127

boolean 1 true or false

char 2 A-Z,a-z,0-9,etc.

short 2 -32768 to 32767

Int 4 (about) -2 million to 2 million

NITIN SIR 7
Nitin Sir
JAVA PROGRAMMING

long 8 (about) -10E18 to 10E18

float 4 -3.4E38 to 3.4E18

double 8 -1.7E308 to 1.7E308

Write a program for addition of two numbers using command


line arguments.
class Add

public static void main(String args [ ])

int n1,n2,ans;

n2 = Integer.parseInt(args[1]);

n1 = Integer.parseInt(args[o]);

ans = n1 + n2;

System.out.println(“Addition =”+ ans);

Type Casting (Conversion)


• The process of converting one data type to another is called casting.
• The casting occurs when there is need to store a value of one data type
into variable of another type.
• Syntax :

NITIN SIR 8
Nitin Sir
JAVA PROGRAMMING

Type variable 2 = (type) variable 2 ;

• 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.

• Types of operators are as follows:


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special Operators

Arithmetic operator

NITIN SIR 9
Nitin Sir
JAVA PROGRAMMING

Arithmetic operator is used to perform arithmetic operations like addition,


subtraction, multiplication, division and modulo.

1. + to find the sum


2. - to find the difference
3. * to find the product
4. / to find the quotient after division
5. % to find the remainder after division
Division ‘/’ operator is used to find quotient and MOD ‘%’ operator is used
to find remainder after division of two numbers.

Relational operator

The operation which is used to check relation between two operand.

o ‘<’ (less than)


o >’ (greater than)
o “= =” (equality operator)
o ‘<=’ (less than equal to)
o ‘>=’ (greater than equal to)
o ‘!=’ (not equal to)

Logical operator

• Logical operators are used to evaluate conditions or expressions.


• The logical operators are AND and OR.
• AND Operator (&)
o The AND operators checks for all conditions to be true then only it
returns true else 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 AND less
than 10, else it will result in false i.e.0

• 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

• These operators work bitwise on a data.


• They perform different operations on bits of a data like AND, OR, EXOR and
NOT.
• The operators are listed below :
1. ~ to perform bitwise NOT operation.
2. & to perform bitwise AND operation.
3. | to perform bitwise OR operation.
4. ^ to perform bitwise EXOR operation.
5. << to perform bitwise left shift operation.
6. >> to perform bitwise right shift operation.

Conditional operator

It is also known as ternary operators.

Syntax :

(condition)? (Exp 1) : (Exp 2);

Program :

class Demo

NITIN SIR 11
Nitin Sir
JAVA PROGRAMMING

Public static void main(String args [ ])

int n1, n2, max;

n1 = Integer.parseInt(args[o]);

n1 = Integer.parseInt(args[1]);

max = (n1 > n2) ? n1 : n2;

System.out.println(“maximum no is” + max);

Increment / Decrement operator :

Increment / decrement operator is used to increase or decrease the value of


operand by 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);
}
}

WAP to find average marks of 𝟓 subjects.


class Avg
{
Public static void main(String args [ ])
{
int n1,n2,n3,n4,n5,ans;
n1 = Integer.parse Int(args[o]);
n2 = Integer.parse Int(args[1]);
n3 = Integer.parse Int(args[3]);
n4 = Integer.parse Int(args[4]);
n5 = Integer.parse Int(args[5]);
NITIN SIR 13
Nitin Sir
JAVA PROGRAMMING

ans = (n1 + n2 + n3 + n4 + n5) / 5;


System.out.println(“Avg =” + ans);
}
}

NITIN SIR 14
Nitin Sir
JAVA PROGRAMMING

Control Flow Statement

Condition Looping Branching


al
• If Statement • For loop
• While loop • Break
• If – else Statement • goto
• Nested if- else • Do-while loop
• continue
• Else if ladder
• Switch - Case

• In programming we need to sometimes control the flow of operation other than


just the sequential statements. In this case we need the control statements.

• Control statements are of two types


1. Conditional (Selection) statements are used to perform the operations
based on a particular condition i.e. if a condition is true performing one task
else perform another task.
2. Iterative statements (Looping) are used to perform certain operation
repetitively for certain number of times. In C we have three iterative
statements viz. for loop, while loop and do-while loop.

Selection Statement is of following types.

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

If condtion1 is true then statement1 will be executed otherwise condition2 will be


check if it is true then statment2 will be executed otherwise statement 3 will be
executed.
Syntax:
if(condition1)
{
Statment1;
}
elseif(condition2)
{
Statment2;
}
else
{

NITIN SIR 17
Nitin Sir
JAVA PROGRAMMING

If statement looks very confusing & complex when more conditions are
introduced.

Another way to make decision among multiple conditions is with switen


case statement.

Switch statement accepts value & tests it for various conditions.

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 ;

Importance of break statement:

Break statements is needed in the switch case as some case is executed, no


other case to should be checked.

without break it will be difficult to break the switch case.

NITIN SIR 18
Nitin Sir
JAVA PROGRAMMING

FOR LOOP

• For is a iterative statement.


It is used to repeat a set of statements number of times.
Syntax:-
for (initializations; condition; increment / decrement)
{
Statement;
}

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.

E.g.:- Program to display hello 10 times.


for(i=1; i<=10; i++)
{
S.o.println(“Hello”);
}
o/p
Hello
Hello
Hello
.
.
. Hello

NITIN SIR 19
Nitin Sir
JAVA PROGRAMMING

WHILE LOOPS

While and do-while loops are also for iterative operation.


The while loop is used when you want to execute a block of code repeatedly with
checked condition before making iteration.
Syntax:
While (condition)
{

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

• First the code block is executed and then condition is evaluated.


Syntax
do
{
Statements;
} while (condition);
• First the statements are executed and then the condition is checked.
• If the condition is true the statements are executed again. If the condition is false,
the statements are not executed again.

Eg:-
i=10;
do
{
S.o.println(“%d”);
i++;
} While (i! =0);
NITIN SIR 20
Nitin Sir
JAVA PROGRAMMING

WAP to display factorial of a number.


class Factorial
{
Public static void main(String args [ ])
{
int n1,n2,ans=1;
n1 = Integer.parseInt(args[o]);
for(int i = n; i >= 1; i--)
{
ans = ans × i;
}
System.out.println(“Factorial =” + ans);
}
}

WAP to compare two numbers.

class compare

Public static void main(String args [ ])

int n1, n2;

n1 = Integer.parseInt(args[o]);

n1 = Integer.parseInt(args[1]);

if(n1 > n2)

NITIN SIR 21
Nitin Sir
JAVA PROGRAMMING

System.out.println(“maxi number is” + n1);

else

System.out.println(“maxi number is” + 2);

WAP in java to display following output.

* *

* * *

* * * *

class Demo

Public static void main(String args [ ])

int i, j;

for(int i = 1; i <= 4; i++)

for(int j = 1; j <= i; j++)


NITIN SIR 22
Nitin Sir
JAVA PROGRAMMING

System.out.print(“ * ”);

System.out.println( );

WAP to find a reverse of a number.

class Demo

Public static void main(String args [ ])

int n = Integer.parseInt(args[o]);

int rem, rev = 0;

while(n! = 0)

rem = n % 10;

rev = rev × 10 + rem;

n = n/10;

System.out.println(“Reverse = ” +rev);
NITIN SIR 23
Nitin Sir
JAVA PROGRAMMING

WAP to find a whether given no is palindrome or not.

class Demo

Public static void main(String args [ ])

int n = Integer.parseInt(args[o]);

int rem, rev = 0;

while(n! = 0)

rem = n % 10;

rev = rev × 10 + rem;

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”);

WAP to find a fibonacci series of given number.

class Demo

Public static void main(String args [ ])

int n = Integer.parseInt(args[o]);

int n1 = 0, n2 = 1;

System.out.print(n1 + “ ” + n2);

for(int i = 1; i <= n-2; i++)

int ans = n1 + n2;

System.out.print(“ ” + ans);

n1 = n2;

n2 = ans;

NITIN SIR 25
Nitin Sir
JAVA PROGRAMMING

WAP to find a whether given no prime or not.

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

class class _ name


{
[field declaration ; ]
[method declaration ; ]
}
Fields Declaration or Instance Variable or Member Variables :

• 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;

Rec = new Rectangle () ;

Both the statements can be combined into single statement like

Rectangle Rec = new Rectangle ( ) ;

Accessing Class Members :


• Each objects has its own memory space for data members.
• The dot operator is used to access the method from outside the class.

NITIN SIR 28
Nitin Sir
JAVA PROGRAMMING

• The objects is used to invoke the method.


• It can be accessed directly from within the class to which it is defined.
Syntax :

object_name.variable_name = value; //Accessing data members.


object_name.method_name(parameter_list); //Accessing methods of
class.
Example:
obj.width = 25.47;
obj.height = 85.69;
obj.depth = 7.35;
obj.GetData();

WAP to create class rectangle that will calculate area of rectangle.

class Rectangle
{
int length;
int breath;
void getdata(int a, int b)
{
length = a;
breath = b;
}
int calculate()
{
int area;

area = length * breagth;

return (area);

}
}

NITIN SIR 29
Nitin Sir
JAVA PROGRAMMING

class Demo
{
Public static void main(String args[])

{
Rectangle rect = new Rectangle[ ];

rect.getdata (5, 7);

int area=rect.calculate()

System.out.println(“Area of rectangle = ” + area)

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;

void getdata(int a, int b)

acc_no = a;

name = n;

NITIN SIR 30
Nitin Sir
JAVA PROGRAMMING

balance = b;

void putdata()

System.out.println(“Account No = ” + acc_no + “Name = ”


+ name +” Balance = ” + balance);

class Demo
{
Public static void main(String args[])

{
Account acc = new Account[ ];

acc.getdata (101,“nitin”, 1500);

acc.putdata();

Array of object

Array of objects is a collection of objects of the same class.

Syntax

class-name array name [size];

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;

BufferedReader br = new buffered Reader(New


InputStreamReader(System.in));

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_ID = ” + emp id);

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

Ch :2 Derived construct in JAVA


Constructor :

• Java support special method is called constructor which is used to


initialize variable at the time of object creation.
• Constructor is a special method that enables an object to initialize
itself when it is created.
• This process is known as automatic initialization of an object.
• It performs automatic initialization of an object.
• Constructor have same name as the class name.
• Constructor do not specify a return type not even void.
E.g

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.

The default constructor automatically initializes all instance variables to


zero.

class Box

double width;

double height;

double depth;

// This is the constructor for Box.

Box()

System.out.println("Constructing Box");

width = 10;

height = 10;

NITIN SIR 35
Nitin Sir
JAVA PROGRAMMING

depth = 10;

} // compute and return volume

double volume()

return width * height * depth;

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

public static void main(String args[])

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box(3, 6, 9);

double vol;

vol = mybox1.volume();

System.out.println("Volume is " + vol);

vol = mybox2.volume();

System.out.println("Volume is " + vol);

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

The members of the current object like instance method or constructor


or instance variable can be referred by using this pointer.

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.

Method overloading is one of the ways that Java supports


polymorphism.

When an overloaded method is called/invoked java matches the method


name first and then the number and type if parameters to decide which
method is to execute.

Overloaded methods must differ in the type or number of their


parameters.

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

public static void main(String args[])

Over obj=new Over();

obj.area(52.67f);

obj.area(5,4);

obj.area(7.65f,2.0f);

Static Members

• Sometimes there is need to use or define a class members or variables that


can be used independently without the object of class.
• Generally we access class members using the object of its class.
But we can create members that can be used by itself, without reference to
any specific instance or object.

• To create such members static keyword is preceded to variable or


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 :

• Garbage collection is a process in which the memory allocated to object,


which are no longer in use can be reclaimed for further use.
• In Java , the destruction of objects takes place automatically.
• An object because eligible for garbage for garbage collection if there are no
reference in it.
• The garbage collection is a technique, which handles the destroying of the
objects in java.
• When no reference to an object exist, that object assumed to be no longer
needed.
• There is no explicitly need to destroy the object.
• Java uses a procedure called garbage collection to reaction memory
occupied by objects that are no longer accessible to a program.

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

• It automatically free memory resources used by objects but if objects


holds other non-object resources.
• Such as descriptor etc, then garbage collection can not free there
resources.
• In order to free there resources which can be done by finalize method
which is same as destructor.
• The finalize method may take any action making the objects available to
other thread.
• The basic purpose of finalize is to perform cleanup actions before the
object is discorded this mechanism is called finalization.
• The finalize method is invoked any once by JVM.
Example
Protected void finalize()
{
//code;

Arrays

• Array is a collection of similar type of elements that have contiguous


memory location.
• Array provides a convenient means of grouping related information.
• We can store only fixed elements in an array.
• First element of the array is stored at 0 index.

• Types of Array
• There ar e two types of array.

o Single Dimensional Array

NITIN SIR 41
Nitin Sir
JAVA PROGRAMMING

o Multidimensional Array

Single Dimensional Array


A list of items are given in one variable name using only one subscript.

Syntax

dataType[ ] arrayName; (or)

datatype [ ]arrayName (or)

dataType arrayName[ ];

Instantiation of an Array in java

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

for(int i=0; i<a.length; i++) //length is the property of array


System.out.println(a[i]);
}
}

Multidimensional array

Data is stored in row and column based index (also known as matrix
form).

Syntax

dataType[ ][ ] arrayRefVar; (or)

dataType [ ][ ]arrayRefVar; (or)

dataType arrayRefVar[ ][ ]; (or)

dataType [ ]arrayRefVar[ ];

Example to instantiate Multidimensional Array in java

int[ ][ ] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java

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.

• A java string is an instantiated object of the String class.

• A java string is not a character array and is not NULL terminated.

• String objects are handled specially by the compiler.

o String is the only class which has "implicit" instantiation.

o The String class is defined in the java.lang package.

• Strings are immutable.

o The value of a String object can never be changed.

o For mutable Strings, use the StringBuffer class.

• Normally, objects in Java are created with the new keyword.


Creating String Objects

String name;
name = new String(“John");

However, String objects can be created "implicitly":

Strings can also be created using the + operator. The + operator, when
applied to Strings means concatenation.

int age = 21;


String name;
String message = “John wishes he was " + age + " years old";
name = “John"; NITIN SIR 45
Nitin Sir
JAVA PROGRAMMING

String Methods - length, charAt


int length(); Returns the number of characters in the string.

char charAt(i); Returns the char at position i.

”Problem".length(); 7

”Window".charAt (2); ’n'

Method — substring

Returns a new String by copying characters from an existing String.

String subs = word.substring (i, k);

returns the substring of chars in positions from i to k-1

television

String subs = word.substring (i);

returns the substring from the i-th char to the end

”television".substring (2,5); “lev"

“immutable".substring (2); “mutable"

“bob".substring (9); "" (empty string)

NITIN SIR 46
Nitin Sir
JAVA PROGRAMMING

Methods — Concatenation

String word1 = “re”, word2 = “think”; word3 = “ing”;

int num = 2;

String result = word1 + word2;

//concatenates word1 and word2 “rethink“

String result = word1.concat (word2);

//the same as word1 + word2 “rethink“

result += word3;

//concatenates word3 to result “rethinking”

result += num; //converts num to String


//and concatenates it to result “rethinking2”

Methods — Find (indexOf)

String name =“President George Washington";

name.indexOf (‘P'); 0

name.indexOf (‘e'); 2

name.indexOf (“George"); 10

name.indexOf (‘e', 3); 6

name.indexOf (“Bob"); -1

name.lastIndexOf (‘e'); 15

NITIN SIR 47
Nitin Sir
JAVA PROGRAMMING

Methods — Equality

boolean b = word1.equals(word2);

returns true if the string word1 is equal to word2

boolean b = word1.equalsIgnoreCase(word2);

returns true if the string word1 matches word2, case-blind

b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true

Methods — Comparison

int diff = word1.compareTo(word2);

returns the “difference” word1 - word2

int diff = word1.compareToIgnoreCase(word2);

returns the “difference” word1 - word2, case-blind

Usually programmers don’t care what the numerical “difference” of word1


- word2 is, just whether the difference is

negative (word1 comes before word2),

zero (word1 and word2 are equal) or

positive (word1 comes after word2).

Often used in conditional statements.

NITIN SIR 48
Nitin Sir
JAVA PROGRAMMING

String Buffer class

• String buffer class is important class of string.


• String creates string of fixed length and string buffer creates string of
flexible length.
• It is possible to insert characters and sub strings in the middle of string
or append another string to the end.
• String buffer is a mutable sequence of characters.
• String buffer is similar to string but the contents of the string buffer can
be modified after creation.
• Every stringbuffer has capacity associated it. The capacity string buffer
is number of character it can hold.

Vectors

• Vector implements a DYNAMIC ARRAY.


• Vectors can hold objects of any type and any number.
• The vector class provide array of variable size.
• Vector automatically grow when they run out of allocated space.

NITIN SIR 49
Nitin Sir
JAVA PROGRAMMING

• Vector class is contained in java.util package.


• Vector has extra methods for adding and removing elements.
• Vector is different from ARRAY in two ways:-
1. Vector is synchronized.

2. It contains many legacy methods that are not part of the collection
framework.

Declaring VECTORS

1. Vector list = new Vector(); Creates a default vector


2. Vector list = new Vector(int size); Creates a vector, whose initial
capacity is specified by size.
3. Vector list = new Vector(int size, int incr); Creates a vector, whose
initial capacity is specified, by size and whose increment is specified by
incr.

NITIN SIR 50
Nitin Sir
JAVA PROGRAMMING

Difference between vector and array


Vector Array
Vector is similar to array holds Array is collection of data elements of
multiple objects. An objects can be similar data type elements or
retrieved using index value. homogeneous.
Vector class provides array of variable An array is a fixed size.
size.
Vector automatically grows when they Array never grows when they run out
run out of allocated space. of allocated space.
Vector provides extra method for No methods are provides for adding
adding and removing elements. and removing elements.

WAP to accept as many integers as user wants in a vector. Delete specific


elements and display remaining list.

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

• Wrapper class is a wrapper around a primitive data type.


• It represents primitive data types in their corresponding class instances.
• Each of eight data types has class dedicated in it.
• There is an integer class that holds on int variable, there is double class that
holds a double variable and so on.
• Wrapper class are part of the java.lang package.
• Many built in java classes work any with objects and not on primitive data
types.like vector cannot store primitive data type.
• Primitive data type :- int, float, char
• Wrapper classes are provided which have method for converting primitive
data types to objects.
• The wrapper class method are static methods these can be invoked using
class name.
• Example :-
Int x = 25;
Integer y = new Integer(33);

Data Type Wrapper Class


int Integer
float Float
char Character
boolean Boolean
double Double
long Long

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

Public static void main(String args[ ])

int n = new Vector();

bufferedReader br = new buffered Reader (New


InputStreamReader(System.in));

System.out.println(“enter an integer”);

n = Interger.parseInt(br.readline());

String str;

str = Integer to binary string(n);

System.out.println(“binary number is =”+str);

NITIN SIR 53
Nitin Sir
JAVA PROGRAMMING

Ch :3 Derived construct in JAVA


Inheritance

• Inheritance is reusability of code.


• A creating new classes reusing the properties of existing one is
nothing but inheritance in java clases.
• The mechanism of deriving new class from already developed
class is called inheritance.
• The old class is known as base class or super class and the new
class is called as subclass or derived class.
• Types of Inheritance
o Single inheritance
o Multiple inheritance
o Multi-level inheritance
o Hierarchical inheritance
• Syntax :-
class subclass_name extend subclass_name
{

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

Write a program for following inheritance


Class Name : Student
Member variable
Rollno, name

Class Name : Exam


Member variable
Subject_name

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();
}
}

Abstract method and abstract classes


Abstract method :-

• Abstract keyword indicated that a method must always be


redefined in a subclass using modifier keyword abstract.
• These methods are referred of subclasses responsibility
because they have no implementations specified in the
superclass thus subclass must override them.
NITIN SIR 56
Nitin Sir
JAVA PROGRAMMING

• Syntax
abstract rect_type method_name (parameter list)
{
------
}
class Students
{
abstract students(int r)
{
-----
}

Abstract class :-

• Abstract keyword is used to declare class abstract.


• Abstract class no objects.
• Abstract class cannot be directly instantiated by new
operation.
• Any subclass of an abstract class must either implements.
• All the abstract method in the super class or be itself declared
abstract.
• Syntax
abstract class_name
{
……….
}
• When class contains one or more abstract method it should be
declared as abstract.

NITIN SIR 57
Nitin Sir
JAVA PROGRAMMING

Visibility control / Access specifiers parameter

• To restrict access like creating variables and methods from


outside the class, visibility modifiers or access specifies are
used.
• Java provides following types of visibility modifiers :-

1. Public access
Any variables or method declared inside the class is visible
to entire class.

2. Friendly access (public and private)


In situation where no access modifier is specified, the
member known as ‘friendly level access’.

When friendly access is used it makes field visible only in


the same package.

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( );
}

Program illustrates the implementation of the concept of multiple inheritance using


interfaces.
class Student
{

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( );
}
}

DIFFERENCES BETWEEN CLASSES AND INTERFACES

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.

• Java API Packages


o Java.lang: lang stands for language.

NITIN SIR 62
Nitin Sir
JAVA PROGRAMMING

This package got primary classes and interfaces essential for


developing a basic Java program.
It consists of wrapper classes , String, SttringBuffer, StringBuilder
classes to handle strings, thread class.
o Java.util: util stands for utility.
This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, Date and Time classes.
o Java.io: io stands for input and output.
This package contains streams. A stream represents flow of data
from one place to another place. Streams are useful to store data in the
form of files and also to perform input-output related tasks.
o Java.awt: awt stands for abstract window toolkit.
This helps to develop GUI(Graphical user Interfaces) with colorful
screens, paintings and images etc., can be developed. It consists of ,
classes which are useful to provide action for components like push
buttons, radio buttons, menus etc.
o Java.net: net stands for network.
Client-Server programming can be done by using this package.
Classes related to obtaining authentication for network, client and
server to establish communication between them are also available in
java.net package.
o Java.applet:
applets are programs which come from a server into a client
and get executed on the client machine on a network. Applet class
of this package is useful to create and use applets.

User-Defined packages:

• The users of the Java language can also create their own packages.

• They are called user-defined 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; //to create a package

package packagename.subpackagename;

e.g.: package pack;

• The first statement in the program must be package statement while


creating a package.

• While creating a package except instance variables, declare all the


members and the class itself as public then only the public
members are available outside the package to other programs.

e.g

package pack;

public class Addition

private double d1,d2;

public Addition(double a, double b) {

d1 = a;

d2 = b; }

public void sum()

{ System.out.println ("Sum is : " + (d1+d2) ); }

• Compile and save .java and .class file in pack directory (folder).

NITIN SIR 64
Nitin Sir
JAVA PROGRAMMING

Steps to create a package in java

1. Declare the package at the beginning of a file using form

package packagename;

2. Define a class that is be put in the package and declare it public.

3. Create a subdirectory under the directory where main source files are
stored.

4. Store the listing as the classname.java file in the subdirectory created.

5. Compile the file. This creates .class file in the subdirectory.

NITIN SIR 65
Nitin Sir
JAVA PROGRAMMING

Ch :4 Exception Handling and


Multithreading
Error and Exception:-

Types of Error [W-14]

Errors are broadly classified into two categories:-

1. Compile time errors

2. Runtime errors

1. Compile time error-


All syntax errors will be detected and displayed by java compiler and
therefore these errors are known as compile time errors.

The most of common problems are:

• 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

• Trying to store value into an array of an incompatible class or


type
• Passing parameter that is not in a valid range or value for method
• Trying to illegally change status of thread
• Attempting to use a negative size for an array
• Converting invalid string to a number
• Accessing character that is out of bound of a string

Exception [W-15, S-15]

An exception is an event, which occurs during the execution of a program,


that stop the flow of the program's instructions and takes appropriate
actions if handled

 An Exception is a condition that is caused by a run-time error in the


program.

 When java interpreter encounters an error such as dividing an integer


by zero, it creates an exception object and throws it.(i.e. informs us that
error has occurred.)

Exception Handling Java handles exceptions with 5 keywords:

1) try 2) catch 3) finally 4) Throw 5) throws

1. try:

The try block contains a block of program statements within which an


exception might occur.

If there exist any exception, the control is transferred to catch or finally


block.

Syntax:

try

NITIN SIR 67
Nitin Sir
JAVA PROGRAMMING

// block of code to monitor for errors

2. catch:
This block includes the actions to be taken if a particular exception
occurs.

The corresponding catch block executes if an exception of a particular


type occurs within the try block.

For example if an arithmetic exception occurs in try block then the


statements enclosed in catch block for arithmetic exception executes.

Syntax:

catch(ExceptionType1 exOb)

// exception handler for ExceptionType1

Multiple catch Statements

 A try block can have any number of catch blocks.

 A catch block that is written for catching the class Exception can catch
all other exceptions.

 Syntax:

catch(Exception e)

//This catch block catches all the exceptions

NITIN SIR 68
Nitin Sir
JAVA PROGRAMMING

 If multiple catch blocks are present in a program then the above


mentioned catch block should be placed at the last as per the exception
handling best practices.

3. finally:
finally block includes the statements which are to be executed in
any case, in case the exception is raised or not.

After all other try-catch processing is complete, the code inside


the finally block executes.

Syntax:

finally

. . .

4. throw:
The throw keyword is used to explicitly throw an exception

This keyword is generally used in case of user defined exception,


to forcefully raise the exception and take the required action.

When throw statement is executed, the flow of execution stops


immediately after throw statement, and any subsequent statements are not
executed.

Syntax

throw new AnyThrowableInstance;

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

In that case , try … catch block is not necessary in the code.

void method_name() throws exception_class_name

...

class Demo

public static void main(String args[])

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)

Write a program to throw user defined exception when age is negative

class MyException extends Exception

public MyException (String msg)

super(msg);

class TestMyException

public static void main(String[] args)

int age=-2;

NITIN SIR 71
Nitin Sir
JAVA PROGRAMMING

try {

if(age < 0)

throw new MyException("Age can't be less than zero");

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.*;

class Negative extends Exception

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)

throw new Negative("age is negative");

else

throw new Negative("age is positive");

catch(Negative n)

System.out.println(n);

catch(Exception e)

NITIN SIR 73
Nitin Sir
JAVA PROGRAMMING

Write a program to accept password from user and throw


„Authentication failure‟ exception if password is incorrect. [W-15]

import java.io.*;

classPasswordException extends Exception

PasswordException(String msg)

super(msg);

classPassCheck

public static void main(String args[])

BufferedReaderbr=new BufferedReader(new
InputStreamReader(System.in));

try

System.out.println("Enter Password : ");


if(br.readLine().equals("EXAMW16"))

System.out.println("Authenticated ");

}
NITIN SIR 74
Nitin Sir
JAVA PROGRAMMING

Else

throw new PasswordException("Authentication


failure");

catch(PasswordException e)

System.out.println(e);

catch(IOException e)

System.out.println(e);

Multithreaded Programming:-

• A multithreaded program contains two or more parts that


can run concurrently.
• Each part of such a program is called a thread, and each thread
defines a separate path of execution.
• Thus, multithreading is a specialized form of multitasking.
NITIN SIR 75
Nitin Sir
JAVA PROGRAMMING

• We can create a thread by instantiating an object of type


Thread.Java.
• Thread defines two ways in which this can be accomplished:

1. Implement theRunnable interface.

2. Extends the Thread class, itself.

1. Implement the Runnable interface

• First define a class that implements the Runnable interface.


class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}

• The Runnable interface contains only one method, run().


The run() method is defined in method with the code to be
executed by the thread.

The run() method makes up entire body of thread and is the only
method in which the threads behaviour can be implemented.

public void run( )


{
---------
}
Threads are implemented in form of objects that contain a method
called run().

• Creating Object:
MyThread myObject = new MyThread();

• Creating Thread Object:


Thread thr1 = new Thread( myObject );

NITIN SIR 76
Nitin Sir
JAVA PROGRAMMING

• Start Execution:
thr1.start();

Extending the Threads class

To create thread is to create new class that extends Thread and then to
create an instance of that class.

Extending the Thread class includes following steps

i) Declare the class extending the Thread class. The Thread class can be
extended as follows

classMyFirstThread extends Thread

--------

ii) Implements the run() method That is responsible for executing the
sequence of code that the thread with execute.

The extending class must override the run() method, which is


the entry point of new thread.

public void run()

--------

//Thread code

iii) Create a thread object and call the start() method to initiate the
thread execution.

Following statement create new thread

NITIN SIR 77
Nitin Sir
JAVA PROGRAMMING

MyFirstThread t= new MyFirstThread();


iv) Run instance of thread class or involve run()
T.start( );

class A extends Thread

public void run()

for(int i=1;i<=5; i++)

System.out.println(“From thread A: i=” +i);

} System.out.println(“Exit from A”); }

} class B extends Thread

public void run()

for(int j=1; j<=5; j++)

System.out.println(“From thread B: j=” +j);

System.out.println(“Exit from B”);

NITIN SIR 78
Nitin Sir
JAVA PROGRAMMING

classThreadDemo

public static void main(String args[])

new A().start();

new B().start();

Output –

From Thread A:i=1

From Thread A:i=2

From Thread A:i=3

From Thread A:i=4

From Thread A:i=5

Exit from A

From Thread B:j=1

From Thread B:j=2

From Thread B:j=3

From Thread B:j=4

From Thread B:j=5

NITIN SIR 79
Nitin Sir
JAVA PROGRAMMING

Life Cycle of Thread [S-15, S-16, W-14, W-15]

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:

When a thread object is created it is said to be in a new born


state. When the thread is in a new born state it is not scheduled
running from this state it can be scheduled for running by start() or
killed by stop(). If put in a queue it moves to runnable 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:

A thread can be temporarily suspended or blocked from entering into


the runnable and running state by using either of the following thread
method.

suspend() : Thread can be suspended by this method. It can be


rescheduled by resume().

wait():If a thread requires to wait until some event occurs, it can be


done using wait method andcan be scheduled to run again by notify().
sleep():We can put a thread to sleep for a specified time period using
sleep(time)

where time is in ms. It re-enters the runnable state as soon as period


has elapsed.

5. Dead State:

Whenever we want to stop a thread form running further we can


call its stop().

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

Thread Methods: 1) suspend(), 2) resume(), 3) yield(), 4) wait()


NITIN SIR 81
Nitin Sir
JAVA PROGRAMMING

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.

Thread priority & methods

In java each thread is assigned a priority which affects the order in


which it is scheduled for running.

Thread priority is used to decide when to switch from one running


thread to another.

Threads of same priority are given equal treatment by the java


scheduler.

Thread priorities can take value from 1-10.

Thread class defines default priority constant values as

MIN_PRIORITY = 1

NORM_PRIORITY = 5 (Default Priority)

MAX_PRIORITY = 10

Thread Methods:
NITIN SIR 82
Nitin Sir
JAVA PROGRAMMING

1. setPriority:

Syntax:public void setPriority(int number);

This method is used to assign new priority to the thread.

2. getPriority:

Syntax:public intgetPriority();

It obtain the priority of the thread and returns integer value

e.g

class A extends Thread

public void run()

System.out.println(“Thread A started ”);

for(int i=1;i<=5; i++)

System.out.println(“From thread A: i=” +i);

System.out.println(“Exit from A”);

class B extends Thread

public void run()


NITIN SIR 83
Nitin Sir
JAVA PROGRAMMING

System.out.println(“Thread B started ”);

for(int j=1;j<=5; j++)

System.out.println(“From thread B:j=” +j);

System.out.println(“Exit from B”);

class C extends Thread

public void run()

System.out.println(“Thread C started ”);

for(int k=1;k<=5;k++)

System.out.println(“From thread C: k=” +k);

System.out.println(“Exit from C”);

classThreadPriorityDemo
NITIN SIR 84
Nitin Sir
JAVA PROGRAMMING

public static void main(String args[])

A objA= new A().;

B objB= new B().;

C objC= new C().;

objC.setPriority(Thread.MAX_PRIORITY);
objB.setPriority(objA.getPriority() +1);
objA.setPriority(Thread.MIN_PRIORITY);

System.out.println(“Start Thread A”);

objA.start();

System.out.println(“Start Thread B”);

objB.start();

System.out.println(“Start Thread C”);

objC.start();

System.out.println(“End of main Thread”);

Write a program to create two threads; one to print numbers in original


order and other to reverse order from 1 to 50. [W-14]

class original extends Thread

public void run()


NITIN SIR 85
Nitin Sir
JAVA PROGRAMMING

for(int i=1; i<=50;i++)

System.out.println(" First Thread="+i);

class reverse extends Thread

public void run()

for(intj=50; i >=1; i--)

System.out.println(" Second Thread="+i);

classorgrevDemo

public static void main(String args[])

NITIN SIR 86
Nitin Sir
JAVA PROGRAMMING

System.out.println("first thread printing 1 to 50 in ascending


order");

new original().start();

System.out.println("second thread printing 50 to 1 in reveres


order");

new reverse().start();

System.out.println("Exit from Main");

NITIN SIR 87
Nitin Sir
JAVA PROGRAMMING

Java Applets and Graphics programming


What is applet

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

There are two kinds of Java programs-

– Applications (stand-alone programs)

– Applets.

An Applet is a small Internet-based program that has the Graphical User


Interface (GUI), written in the Java programming language.

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.

Differentiate between applet and application (4 points). [W-14,


S-15, W-15 ]

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

Application can run independently Application can read from or write to


Applet cannot read from or write to files in local computer
files in local computer

Applet cannot communicate with Application can communicate with


other servers on network other servers on network
Applet cannot run any program from Application can run any program
local computer. from local computer.
NITIN SIR 88
Nitin Sir
JAVA PROGRAMMING

Applet are restricted from using Application are not restricted from
libraries from other language such as using libraries from other language
C or C++

Applet life Cycle [ W-14, S-15 ]

Applets are small applications that are accessed on an Internet


server, transported over the Internet, automatically installed, and run as
part of a web document.

The applet states include:

• Born or initialization state


• Running state
• Idle state
• Dead or destroyed state

a) Born or initialization state [S-15]

Applet enters the initialization state when it is first loaded.


This is done by calling the init() method of Applet class. At this stage
the following can be done:

NITIN SIR 89
Nitin Sir
JAVA PROGRAMMING

1. Create objects needed by the applet


2. Set up initial values
3. Load images or fonts
4. Set up colors

Initialization happens only once in the life time of an applet.

public void init()

//implementation

b) Running state: [S-15]

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.

public void start()

//implementation

c) Idle or stopped state:

An applet becomes idle when it is stopped from running. Stopping


occurs automatically when the user leaves the page containing the currently
running applet. stop() method may be overridden to terminate the thread
used to run the applet.

public void stop()

NITIN SIR 90
Nitin Sir
JAVA PROGRAMMING

//implementation

d) Dead state:

An applet is dead when it is removed from memory. This occurs


a/utomatically by invoking the destroy method when we quit the
browser. Destroying stage occurs only once in the lifetime of an applet.
destroy() method may be overridden to clean up resources like threads.

public void destroy()

//implementation

e) Display state: [S-15]

Applet is in the display state when it has to perform some output


operations on the screen. This happens after the applet enters the running
state. paint() method is called for this. If anything is to be displayed the
paint() method is to be overridden.

public void paint(Graphics g)

//implementation

NITIN SIR 91
Nitin Sir
JAVA PROGRAMMING

Applet Tag & Attributes [ W-15, S-16 ]


APPLET Tag: The APPLET tag is used to start an applet from both an HTML
document and from an applet viewer.

The syntax for the standard APPLET tag:

<APPLET

[CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME


= appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]> [< PARAM NAME = AttributeName1
VALUE = AttributeValue>] [<PARAM NAME = AttributeName2 VALUE =
AttributeValue>] . . .

</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.

Explain <PARAM> tag of applet with suitable example. [S-15]


• To pass parameters to an applet <PARAM… > tag is used.
Each <PARAM…> tag has a name attribute and a value attribute. Inside
the applet code, the applet can refer to that parameter by name to find
its value.
• Syntax of <PARAM…> tag is as follows
<PARAM NAME = name1 VALUE = value1>
• To set up and handle parameters, two things must be done.
1. Include appropriate <PARAM..> tags in the HTML document.
2. Provide code in the applet to parse these parameters.
• Parameters are passed on an applet when it is loaded. Generally init()
method in the applet is used to get hold of the parameters defined in the
<PARAM…> tag.
• The getParameter() method, which takes one string argument
representing the name of the parameter and returns a string containing
the value of that parameter.

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>

Program for an applet to accept user name in the form of


parameter and print „Hello<username>‟ [W-15]
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)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
NITIN SIR 94
Nitin Sir
JAVA PROGRAMMING

Write a simple applet which display message “Welcome to


Java‟. [W-15]
import java. applet.*;

import java.awt.*;

public class Welcome extends Applet

public void paint( Graphics g)

g.drawString(―Welcome to java‖,25,50);

/*<applet code= WelcomeJava width= 300 height=300> </applet>*/

Step to run an Applet


1. Write a java applet code and save it with as a class name declared in a
program by extension as a .java.

e.g. from above java code file we can save as a Welcome.java

2. Compile the java file in command prompt jdk as shown below


C:\java\jdk1.7.0\bin> javac Welcome.java

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>

<Applet code= ― Welcome.class‖ width= 500 height=500> </applet>


</html>

5. Save this file with Welcome.html in ‗bin‘ library folder.

6. Now write the following steps in command prompt jdk.

C:\java\jdk1.7.0\bin> appletviewer Welcome.java

C:\java\jdk1.7.0\bin> appletviewer Welcome.html

(Shows output in applet viewer)

OR

C:\java\jdk1.7.0\bin> Welcome.html

(Shows output in internet browser)

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:

drawString() method is used to display the string in an applet window

Syntax:

void drawString(String message, int x, int y);

where message is the string to be displayed beginning at x, y


NITIN SIR 96
Nitin Sir
JAVA PROGRAMMING

Example:

g.drawString(―WELCOME‖, 10, 10);

Lines and Rectangle.

drawLine( )

The drawLine ( ) method is used to draw line which takes two


pair of coordinates (x1,y1) and (x2, y2) as arguments and draws a line
between them. The graphics object g is passed to paint( ) method.

Syntax :-

g.drawLine(x1,y1,x2,y2);

e.g. g.drawLine(20,20,80,80);

drawRect( ) [W-14, S-15,W-15, S-16 ]

The drawRect() method display an outlined rectangle

Syntax:

void drawRect(int top, int left, int width, int height)

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)

Design an Applet program which displays a rectangle filled with red


color and message as “Hello Third year Students” in blue color. [S-16]

Program-

import java.awt.*;

import java.applet.*;

public class DrawRectangle extends Applet

public void paint(Graphics g)

g.setColor(Color.red);

g.fillRect(10,60,40,30);

g.setColor(Color.blue);

g.drawString("Hello Third year Students",70,100);

/* <applet code="DrawRectangle.class" width="350" height="300">


</applet> */
NITIN SIR 98
Nitin Sir
JAVA PROGRAMMING

Drawing Rounded Rectangles


drawRoundRect() and fillRoundRect()

• 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()

• 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 :-

• drawArc(int x, int y, int w, int h, int angle1, int angle2);

• fillArc(int x, int y, int w, int h, int angle1, int angle2);

import java.awt.*;

import java.applet.*;

public class Arc extends Applet

public void paint(Graphics g)


NITIN SIR 100
Nitin Sir
JAVA PROGRAMMING

g.drawArc(30,30,60,60,90,180);

g.fillArc(90,30,60,60,270,180);

/*<applet code=Arc.class height=250 width=200></applet>*/

public void paint(Graphics g)

g.drawOval(40,40,120,150); // Head

g.drawOval(57,75,30,20); // Left Eye

g.drawOval(110,75,30,20); //Right Eye

g.fillOval(68,81,10,10); //Pupil (left)

g.fillOval(121,81,10,10); //Pupil (Right)

g.drawOval(85,100,30,30); //Nose

g.fillArc(60,125,80,40,180,180); //Mouth

g.drawOval(25,92,15,30); //Left ear

g.drawOval(160,92,15,30); //Right ear

NITIN SIR 101


Nitin Sir
JAVA PROGRAMMING

Drawing Polygons and Polylines

• The drawPolygon() method takes three arguments


o An array of integers containing x coordinates
o An array of integers containing y coordinates
o An integer for the total number of points.
• It is obvious that x and y arrays be of same size and we must repeat the
first point at the end of array for closing polygon.

int[] x = {40, 70, 60, 45, 20};

int[] y = {20, 40, 80, 45, 60};

g.drawPolygon(x,y, x.length);

g.drawPolyline(x, y, x.length);

NITIN SIR 102


Nitin Sir
JAVA PROGRAMMING

(x[0], y[0]) (x[0], y[0])


(x[1], y[1]) (x[1], y[1])

(x[3], y[3]) (x[3], y[3])

(x[4], y[4])
(x[4], y[4])
(x[2], y[2])
(x[2], y[2])

Concept of Streams

• In file processing, input refers to the flow of data into a program


and

• Output means the flow of data out of a program.

• Streams represent the ordered sequence of data.

• A stream in java is a path along which data flows (like river or pipe).

• It has source and destination.

• Java Streams are classified in two basic types

• 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).

Input and Output Streams

NITIN SIR 103


Nitin Sir
JAVA PROGRAMMING

• Streams can be used to filter data.

• 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.

• These classes are categorized in two groups

• Byte Stream classes

• Character Stream Classes

• Byte Stream classes handle I/O operations on Bytes.

• Character Stream classes manage I/O operations on Characters.

NITIN SIR 104


Nitin Sir
JAVA PROGRAMMING

Byte Stream Classes

• Byte stream classes provide functional features for creating and


manipulating streams and files for reading and writing bytes.

• The streams are unidirectional therefore java provides two types of byte
streams classes:

• Input stream classes and

• output stream classes.

Input Stream Classes

• The Super class InputStream is abstract class.

• It defines methods for performing functions such as –

NITIN SIR 105


Nitin Sir
JAVA PROGRAMMING

• Reading Bytes

• Closing streams

• Marking position in streams

• Skipping Ahead in stream

• Finding the number of bytes in a stream

InputStream Methods

read() -: Reads a byte from input stream.

read( byte b[]) :- Reads an array of bytes into b.

read( byte b[], int n, int m) :- Reads m bytes into b


starting from nth byte

available( ) :- Gives number of bytes availble in the input

skip( n) :- Skips over n bytes from the input stream

reset( ) :- Goes back to the beginning of the stream

close( ) :- Closes the input stream

InputStream Methods

• The DataInputStream Class extends FilterInputStream and implements


interface DataInput.

• So additional methods are available:

• readShort( )

• readLine( )

NITIN SIR 106


Nitin Sir
JAVA PROGRAMMING

• readInt( )

• readLine( )

• readLong( )

• readChar( )

• readFloat( )

• readBoolean( )

• readUTF( )

• readDouble( )

Output Stream Classes

• There are 3 main read methods:


o int read()
▪ Reads a single character. Returns it as integer
o int read(byte[] buffer)
▪ Reads bytes and places them into buffer
▪ returns the number of bytes read
o int read(byte[] buffer, int offset, int length)
▪ Reads up to length bytes and places them into buffer
▪ First byte read is stored in buffer[offset]
▪ returns the number of bytes read
• Creating an InputStream

ByteArrayInputStream:

❖ Constructor is provided with a byte array.

❖ This byte array contains all the bytes provided by this stream

❖ Useful if the programmer wishes to provide access to a byte array


using the stream interface.

NITIN SIR 107


Nitin Sir
JAVA PROGRAMMING

FileInputStream:

❖ Constructor takes a filename, File object or FileDescriptor Object.

❖ Opens a stream to a file.

FilterInputStream:

❖ Provides a basis for filtered input streams

NITIN SIR 108

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy