Java Full Notes
Java Full Notes
CSE – II SEM
UNIT-I: Object Oriented Thinking: Need for OOP paradigm, A way of viewing
world – Agents, responsibility, messages, methods, classes and instances, class hierarchies
(Inheritance), method binding, overriding and exceptions, summary of OOP concepts, coping
with complexity, abstraction mechanisms.
1 ---
2 ---
.
.
100 ---
GLOBAL DATA
Function Function
RAKESH.C.M Page 1
2. Difficult to maintain program code.
3. It doesn’t model to support real world problems.
Programs are divided into individual procedures that perform discrete tasks.
Procedures are independent of each other.
Procedures have their own local data and processing logic.
Introduction of the concepts of user defined data types.
Maintenance of a large software system.
GLOBAL DATA
DATA DATA
FUN FUN
MODULE1 MODULE2
OBJECT A OBJECT B
RAKESH.C.M Page 2
DATA Communication DATA
FUNCTION FUNCTION
DATA
FUNCTION
OBJECT C
• You first found an appropriate agent (Fred, in this case) and you passed to
this agent a message containing a request.
• It is the responsibility of Fred to satisfy the request.
• There is some method (an algorithm or set of operations) used by Fred to do
this.
• We do not need to know the particular methods used to satisfy the request
such information are hidden from view.
Agents and Communities
RAKESH.C.M Page 3
“An object-oriented program is structured as community of interacting
agents called objects. Each object has a role to play. Each object provides a service
or performs an action that is used by other members of the community.”
“A class is a blueprint that defines the variables and the methods common to
all objects of a certain kind.”
Objects
Object
RAKESH.C.M Page 4
Object Oriented Programming Concepts
a) Encapsulation
b) Abstraction
c) Inheritance
d) Polymorphism
a) Encapsulation: The mechanism by which the data and functions are bound
together with an object definition. By means of encapsulation, it is possible to protect
the data.
b) Abstraction: It is the process of defining a new data type called abstract data
type (ADT) with the principle of data hiding.
ADT refers to the program defined data type together with a set of operations
that can be performed on the data.
Data hiding is a property where the internal data structure of an object is
hidden from the rest of the program.
RAKESH.C.M Page 5
Summary of Object-Oriented Concepts
1. Everything is an object.
2. Computation is performed by objects communicating with each other,
requesting that other objects perform actions. Objects communicate by
sending and receiving messages.
A message is a request for action bundled with whatever arguments may
be necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a
grouping of similar objects, such as integers or lists.
5. The class is the repository for behavior associated with an object. That is,
all objects that are instances of the same class can perform the same
actions.
6. Classes are organized into a singly rooted tree structure, called the
inheritance hierarchy. Memory and behavior associated with instances of
a class are automatically available to any class associated with a
descendant in this tree structure.
***
RAKESH.C.M Page 6
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, ANANTAPUR
II YEAR B.Tech. CSE – II SEM
UNIT-II: Java Basics: History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion
and casting, simple java program, classes and objects – concept of classes, objects,
constructors, methods, Introducing access control, this keyword, garbage collection,
overloading methods and constructors, parameter passing, recursion, string handling.
History of Java
Application programs are run on the computer under the operating system of the
computer. This is similar to the other programming languages.
Applet programs are designed to be transmitted over the Internet and executed by a
java-compatible web browser.
Java Versions
Java 1.0
Java 1.1
Java 2 (Second Generation)
Java 1.2
J2SE (Java 2 Platform Standard Edition)
J2SE 1.3
J2SE 1.4
J2SE 5
J2SE 1.5
J2SE 6
J2SE 1.6
RAKESH.C.M Page 7
a) Platform Independent: Java is a platform independent language. Once we
create the program in one operating system, that program will be worked on any other
operating system that is transmitted to the operating system.
b) Portable: The most significant contribution of Java over other languages is its
portability. Java programs can be easily mover from one computer system to another
anywhere and any time. Changes and upgrades in operating system, processor, and
system resources will not force any changes in Java programming.
c) Object Oriented: Java is a true object oriented language. Since, without class we
can’t run the program but without main function, we can run the program. Almost
everything in java is an object. All program code and data reside within objects and
classes. The object model in Java is simple and easy.
d) Robust & Secure: Java is a Robust language. It provides many safe guards to
ensure reliable code. It is designed as garbage collected language relieving the
programmers, virtually all memory management problems. Java also incorporates the
concept of exception handling, which captures serious errors and eliminates any risk
on crashing the system.
Security becomes an important issue for a language that is used for
programming on internet. Java systems not only verify all memory access but also
ensure that no viruses are communicated with the applet.
f) Simple and Small: Java is a simple and small language. Many features of C and
C++ that are sources are unreliable code are not part of java. For example, Java
doesn’t use pointers, preprocessors, header files, goto statements and many others.
g) Multi Threaded: Java was designed to meet the real-world requirement of creating
interactive, networked programs. Java supports multithreaded programming, which
allows to handling multi task simultaneously. This means we need not wait for the
application to finish one task before beginning another one.
RAKESH.C.M Page 8
j) High Performance: Java performance is impressing for an interpreted language due
to the use of intermediate code. Java architecture is also design to reduce overheads
during runtime. The incorporation of multithreading enhances, the overall executions,
speed of Java programs.
Disk
Phase 1: Java programs are typed in a text editor (Note Pad, Edit Plus etc.,) and
makes corrections if necessary. The programmer specifies that the file in the editor
RAKESH.C.M Page 9
should be saved. The program is stored on a second storage device such as a disk.
Java program files are stored with .java extension.
Phase 3: This phase is called loading. The program must be place in memory
before it can be executed. This is done by the class loader, which takes the .class file
containing in byte code and translates it into the memory. The .class file can be
loaded from a disk on your system or over a network.
Phase 4: Byte code verifier confirms that all byte codes are valid or don’t valid
the Java security instructions.
Phase 5: Java Interpreter reads byte code and translates them into a language
that the computer can understand and it can be executed the code.
javac: The java compiler converts java source code into byte code
Syntax: javac filename.java
java: The java interpreter ,executes java application byte does directly from
class file.
Syntax: java filename
jdb: The java debugger that allows to step through the program one line at a
time, set break points and examine variables.
Syntax: jdb filename
RAKESH.C.M Page 10
Java provides both compiler and a software machine called JVM for each
computer machine. The java compiler translates the java source code (Java program)
into an intermediate code known as byte code, which executes on special type of
machine. The machine is called Java Virtual Machine and exists only inside the
computer memory. The byte code is machine independent code and can run in any
system.
The byte code is not a machine specific code. Java interpreter takes the byte code and
translates it into its own system machine language and runs the results.
The Java Virtual Machine is an interpreter that translates and runs each byte
code instructions separately whenever it is needed by the computer program. In some
cases it is very slow.
As an alternative, Java also provides local compiler for each system that will
compile byte code file into executable code for faster running. Java calls these
compilers just in Time compilers.
RAKESH.C.M Page 11
1. Java does not include structure and union.
2. It is not possible to declare unsigned integer in Java.
3. Pointers don’t exist in Java.
4. Java does not have a preprocessor.
5. There are no header files and delete operators.
6. Java does not allow goto, sizeof and typedef.
7. Java does not support the multiple inheritance.
Java Tokens
Tokens are smallest individual units in a program. The compiler reads the
source program one character at a time grouping the source program into a sequence
of atomic units called tokens.
Reserved words, identifiers, constants, operators etc., are the examples of Java tokens.
Keywords
The keywords (or) reserved words have a special and predefined meaning by
the Java compiler. There are 48 reserved words currently used in Java. These words
cannot be used as names for a variable, constant, class or method. Reserved words
are:
Note: true, false and null are used to represent the values.
Data Types
Data types are used to specify the type of data that a variable can attain. There
are 2 types of data types. Those are
1. Primitive data types
2. Non-Primitive data types
RAKESH.C.M Page 12
Characters : char
Boolean : Boolean
Note:
Variables
The name given to the various elements to store the information is called an
identifier or variable. The rules for variables are as follows:
Declaring a Variable:
RAKESH.C.M Page 13
All variables must be declared before they can be used. The basic form of a
variable declaration is:
Where,
datatype specifies type of the variable
identifier specifies the name of the variable.
Ex: int x;
More than one variable of the same type can be declared in a single statement by
using comma operator.
Initializing a Variable:
Variables can also be initialized with some value at the time of its declaration
as:
Syntax: datatype identifier = value;
Ex: int x = 100;
Java also has identifiers of static duration. Variables and references of static
duration exist from the point at which the class that defines them is loaded into
memory for execution until the program termination.
Methods and instance variables of a class have class scope. Class scope
begins at the beginning left brace of the class definition and ends at the closing right
brace of the class definition
RAKESH.C.M Page 14
Identifiers declared inside a block have block scope. Block scope begins at
the identifiers declaration and ends at the terminating right brace of the block. Local
variables of the method have block scope.
Comments in a Program
1. Single line comments: For single line comment, we use double slash (//) to be
the comment. It ends at the end of the line.
Ex: // JAVA PROGRAM
2. Multi line comments: For more than one line of information, we use multi line
comments. Multi line comments are starts with /* and ends with */.
Ex: /* JAVA
PROGRAM */
System.out class consists of two methods to print the strings and values on the screen.
They are: 1. print() 2. println()
RAKESH.C.M Page 15
1. print(): Syntax: System.out.print(list);
This statement prints the values of the variable name specified in the lists of
output unit.
Ex: System.out.print(“HELLO”);
System.out.print(“HAI”);
O/P: HELLOHAI
O/P: HELLO
HAI
Note: Java has a version of the ‘+’ operator for string concatenation that enables a
string and a value of another data type.
O/P: Total = 10
Java has the facility of command line arguments. Java main method consists
of array of string objects. When we run the program, the array will fill with the
values of any arguments it was given in the command line of the operating system.
import statement
RAKESH.C.M Page 16
BUILDING JAVA PROGRAM
The keyword class is used to declare the new class is being defined.
FName is a valid identifier that defines the name of the class.
Entire class definition will be in between the opening curly brace ‘{‘ and the
closing curly brace ‘}’.
‘public’ keyword is an access specifier, which allows the user to control the
visibility of class members.
‘static’ keyword allows main( ) function to be called without having to
instantiate a particular instance of the class. Since, main( ) method is called by
the Java Interpreter before creation of any objects.
‘void’ keyword used to tell the compiler that main( ) does not return any
value.
main( ) is a method called when a Java application begins.
String args[] declares a parameter named args, which is an array of instance of
the class String. args receives any command line arguments present when the
program is executed.
Now, save the file name with .java extension. Since, every java program must end
with .java extension.
RAKESH.C.M Page 17
2. Compiling the Program
To compile the program, use javac compiler by using the syntax as:
Here, the Java compiler creates a file called Example.class that contains byte
code version of the program.
Now the class file is run by the Java Interpreter called java by using the
syntax as:
After performing all these phases successfully, it display the output on output devices
as
O/P : Hello
Note:
Primitive data types are to be converted into object type by using the wrapper
classes. Integer class is used as wrapper class for primitive data type int. parseInt()
method converts string into an int.
import java.lang.*;
class Add
{
public static void main(String[] args)
{
int x,y,z;
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("Total="+z);
}
}
RAKESH.C.M Page 18
javax.swing PACKAGE
1. showInputDialog( ):
Syntax: JOptionPane.showInputDialog(argument);
The argument indicates to the user what to do in the text field.
Then, the user type characters in the text filed and click on the ok button, it
returns the string to the program.
2. showMessageDialog( ):
The title bar of message dialog box contains the string “Message” to indicate
that the dialog is presenting a message to the user. The default icon is
INFORMATION_MESSAGE.
RAKESH.C.M Page 19
Syntax 2:
JOptionPane.PLAIN_MESSAGE
JOptionPane.ERROR_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
Ex:
JOptionPane.showMessageDialog(null,"Total="+z,"ADDITION
RESULT",JOptionPane.WARNING_MESSAGE);
RAKESH.C.M Page 20
OPERATORS
which is equivalent to
+= a+=4 a=a+4
-= a-=5 a=a–5
*= a*=3 a=a*3
/= a/=5 a=a/5
%= a%=2 a=a%2
OPERATOR MEANING
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or Equal to
RAKESH.C.M Page 21
<= Less than or Equal to
6. Logical Operators: Logical operators are used to check for compound
conditions, which are formed by the combination of two or more relation expressions.
Java provides the following logical operators and these are follows truth tables and
produce Boolean values.
EXP1 ! EXP1
T F
F T
RAKESH.C.M Page 22
8. Bit-Wise Operators: Bit-Wise operators are used to perform on bits of the
operands. Java language supports the following bit-wise operators.
OPERATOR MEANING
Bit-Wise Logical operators ( &, |, ^, and ~ ) follows the following truth tables.
OP1 OP2 OP1 | OP2 OP1 & OP2 OP1 ^ OP2 ~ OP1
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0
CONTROL STATEMENTS
a) if statement
b) if-else statement
c) Nested if-else statement
d) switch statement
RAKESH.C.M Page 23
a) if statement: The if statement process the statements when the specified
condition is true.
Syntax: if(condition)
{
// Block Statements
}
Next Statements
Flowchart:
Next Statements
Here,
If the condition is true then Block Statements are executed. Otherwise, Block
Statements are not executed and the control directly reaches to Next Statements
available after the if block statements.
The statements are either simple or compound statements. If the statements
are simple statement pair of braces is not necessary. If the statements are compound
statements, they must be placed within pair of braces.
class Max
{
public static void main(String[] args)
{
int a=10,b=78;
if(a>b)
System.out.println("Max="+a);
if(b>a)
System.out.println("Max="+b);
}
}
RAKESH.C.M Page 24
b) if-else statement: The general format of if-else statement is:
Syntax: if(condition)
{
// True Block Statements
}
else
{
// False Block Statements
}
Flowchart:
Condition F
False Block Statements
Next Statements
Here,
First the condition is evaluated.
If the condition is true, then True Block Statements are executed,
Otherwise, False Block Statements are executed.
RAKESH.C.M Page 25
c) Nested if-else statement: The if-else statement is placed within another if-else
statement; such methods are called nested if-else statements.
Syntax: if(condition 1)
{
// Block 1 Statements
}
else if(condition 2)
{
// Block 2 Statements
}
.
.
.
else
{
// Block n Statements
}
Next Statements
Example: Write a Java program that prints all real solutions to the
quadratic equation ax2+bx+c = 0.
import javax.swing.*;
import java.lang.*;
class Quadratic
{
public static void main(String args[])
{
double a,b,c,dis,r1,r2;
a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value"));
b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value"));
c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value"));
dis=b*b-4*a*c;
if(dis>0)
{
r1=(-b+Math.sqrt(dis))/(2*a);
r2=(-b-Math.sqrt(dis))/(2*a);
JOptionPane.showMessageDialog(null,"Roots are real. r1="+r1+" "+"r2="+r2);
}
else if(dis==0)
{
r1=r2=-b/(2*a);
JOptionPane.showMessageDialog(null,"Roots are equal.r1=r2="+r1);
}
else
JOptionPane.showMessageDialog(null,"Roots are imaginary");
}
}
RAKESH.C.M Page 26
d) switch statement: The switch statement allows section among the multiple section
of a code depending on the value of an expression. The objective is to check several
possible constant values for an expression.
Syntax: switch(Expression)
{
case value1 : Block 1 Statements
break;
case value2 : Block 2 Statements
break;
.
.
case valuen : Block n Statements
default : Default Block Statements
}
Here,
First the switch statement evaluates the expression and check whether the
evaluated value is coinciding with any case value or not. If any value is coinciding, it
executes that particular block of statements until the break statement is reached. After
executing the statements the control is transferred out of the statements that are
available after the switch statement.
If any value is not coinciding with the case value, then it executes Default
Block Statements. Default block is an optional block.
class Color1
{
public static void main(String[] args)
{
char ch='G';
switch(ch)
{
case 'R':System.out.println("RED");
break;
case 'G':System.out.println("GREEN");
break;
case 'B':System.out.println("BLUE");
break;
default: System.out.println("INVALID SELECTION");
}
}
}
RAKESH.C.M Page 27
2. Loop Control Statements
a) while statement: while loop executes the statements repeatedly as long as the
becomes true. When the condition becomes false, then the control immediately
passes to next statements available after the loop statements.
Syntax : while(condition)
{
// Block Statements
}
Flowchart:
T
Block Statements
class Fib1
{
public static void main(String[] args)
{
int a=1,b=1,c,i=3,n;
System.out.println(a+" ");
System.out.println(b+" ");
n=Integer.parseInt(args[0]);
RAKESH.C.M Page 28
while(i<=n)
{
c=a+b;
a=b;
b=c;
System.out.println(c+" ");
i++;
}
}
}
Syntax: do
{
// Block Statements
}
while(condition);
Next Statements
Flowchart:
Block Statements
T
Condition
Next Statements
Note: The main difference between while and do-while statements is do-while
statement executed the block statements at least once even the condition becomes
false.
RAKESH.C.M Page 29
// PROGRAM TO PRINT THE FIRST N FIBONACCI SEQUECE NUMBERS
class Fib2
{
public static void main(String[] args)
{
int a=1,b=1,c,i=3,n;
System.out.println(a+" ");
System.out.println(b+" ");
n=Integer.parseInt(args[0]);
do
{
c=a+b;
a=b;
b=c;
System.out.println(c+" ");
i++;
}
while(i<=n);
}
}
Flowchart:
Initialization
Condition F
RAKESH.C.M Page 30
Here,
First the control reaches to Initialization section. Initialization starts with
assigning value to the variable and executes only once at the start of the loop. Then
control enters into Condition section.
In Condition section, if the outcome of the Condition is true, then control
enters into Block Statements and is to be executed. After executing the statements
control reaches to Increment/Decrement section.
After incrementing or decrementing the variable in Increment/Decrement
section, again control reaches to Condition section.
This procedure is repeated as long as the condition becomes true. If the
Condition becomes false, then control comes out of the loop and the control reaches
to Next statements available after the loop.
// EXAMPLE PROGRAM
class Fact
{
public static void main(String[] args)
{
int i,n,f=1;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
f=f*i;
System.out.println("Factorial Value:"+f);
}
}
Note:
a) break statement: break statement placed in while, do-while, for and switch
statement causes immediate exit from that structure. It can be used in two ways as
unlabeled break and labeled break statements.
RAKESH.C.M Page 31
Unlabeled break:
Syntax: break;
class Loop1
{
public static void main(String[] args)
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
System.out.print(" "+i);
}
}
}
Labeled break: To break out of nested structures, we can use the labeled break
statements. This statement when executed in a while, do-while and for statements
causes immediate exit from that structure and any number of enclosing repetition
structures. Program execution resumes with the first statement after the enclosing
labeled compound statement.
class Loop2
{
public static void main(String[] args)
{
int i,j;
stop:
{
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
break stop;
System.out.print(" "+i);
}
System.out.println();
}
}
}
}
RAKESH.C.M Page 32
b) continue statement: continue statement placed in a while, do-while or for
statements causes to skip the remaining statements available after the continue
statement and the control reaches to next iteration of the loop. It can also be used in
two ways as unlabeled continue and labeled continue statements.
Unlabeled continue:
Syntax: continue;
class Loop3
{
public static void main(String[] args)
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
continue;
System.out.print(" "+i);
}
System.out.println();
}
}
}
class Loop
{
public static void main(String[] args)
{
int i,j;
stop:
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
continue stop;
RAKESH.C.M Page 33
System.out.print(" "+i);
}
System.out.println();
}
}
}
The program finish normally by placing Code as ‘0’; other value means error.
Syntax: System.exit(0);
Example: Write a Java program that prompts the user for an integer and
then print out all prime numbers up to that integer.
import javax.swing.*;
class Prime
{
public static void main(String args[])
{
int n,temp;
n=Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
System.out.println("The prime numbers from 1 to" +n+" are");
for(int i=2;i<=n;i++)
{
temp=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
temp=1;
break;
}
}
if(temp==0)
System.out.println(i);
}
}
}
RAKESH.C.M Page 34
ARRAYS
Or
Syntax: datatype ArrayName[] = new datatype[size];
Where,
datatype defines type of the variables stored in the array
ArrayName defines name of the array
new operator used to allocate dynamic memory in computer for the array
size defines the number of memory locations of the array.
It can also be possible to initialize array automatically, when they are declared.
For this use the syntax as:
Where,
List of values are separated by comma operator and surrounded by curly
braces.
Ex: int x[] = { 11,34,78,90};
In Java, all arrays are storing the allocated size in a variable named length. We
can access the length of the array using the syntax as:
Syntax: ArrayName.length;
RAKESH.C.M Page 35
// EXAPLE PROGRAM TO SORT LIST OF NUMBERS IN ASCENDING ORDER
import javax.swing.*;
class Arr1
{
public static void main(String[] args)
{
int n,temp,i,j;
n=Integer.parseInt(JOptionPane.showInputDialog("Enter how many numbers:"));
int x[]=new int[n];
for(i=0;i<n;i++)
x[i]=Integer.parseInt(JOptionPane.showInputDialog("Enter "+"x["+i+"]"));
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(x[i]>x[j])
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}
for(i=0;i<n;i++)
System.out.print(" "+x[i]);
}
}
RAKESH.C.M Page 36
It can also be possible to initialize array automatically, when they are declared.
For this use the syntax as:
Or
import javax.swing.*;
class Matmul
{
public static void main(String args[])
{
int[][] a=new int[10][10];
int b[][]=new int[10][10];
int c[][]=new int[10][10];
int m,n,p,q,i,j,k;
m=Integer.parseInt(JOptionPane.showInputDialog("Enter Rows of Matrix 1:"));
n=Integer.parseInt(JOptionPane.showInputDialog("Enter Columns of Matrix 1:"));
p=Integer.parseInt(JOptionPane.showInputDialog("Enter Rows of Matrix 2:"));
q=Integer.parseInt(JOptionPane.showInputDialog("Enter Columns of Matrix 2:"));
if(n==p)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter a["+i+"]["+j+"]:"));
}
}
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter b["+i+"]["+j+"]:"));
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
RAKESH.C.M Page 37
for(k=0;k<p;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
System.out.println("The resultant matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
else
System.out.println("Matrix multiplication is not possible");
}
}
Syntax:
datatype ArrayName[][]…[] = new datatype[size1][size2]……[sizen];
class Mt
{
public static void main(String[] args)
{
int i,j,k;
int x[][][]={ { {11,22},{33,44}},{{1,7},{3,4}}};
for(i=0;i<2;i++)
{
System.out.println();
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
System.out.print(" "+x[i][j][k]);
System.out.println();
}
}
}
}
RAKESH.C.M Page 38
TYPE CONVERSION AND CASTING
Java permits mixing of constants and variables of different types, but during
execution it follows type conversions. The process of converting data item from one
data type to another data type is called type casting.
In Java, type casting can be done in two ways. They are:
1. Implicit type casting
2. Explicit type casting
FROM TO
Note: The final result of an expression is converted to the type of the variable before
assigning to the left hand side variable. In such cases the following observations are
made.
RAKESH.C.M Page 39
Class: A class is a non-primitive data type that contains member variables (data) and
member functions (methods) that operates on the variables. A class is declared by the
use of the class keyword. The general form of class definition is as follows.
Syntax: class class-name
{
datatype instance-variable1;
datatype instance-variable2;
-
-
datatype instance-variablen;
datatype methodname1(parameter-list)
{
// method body
}
-
-
datatype methodnamem(parameter-list)
{
// method body
}
}
The data, or variables defined with in a class are called instance variables.
The code is present with in methods. Collection of methods and variables defined
with in a class are called members of the class.
1. Declare a variable of the class type. At this stage, the variable refers to an
object only.
2. Assigning an actual, physical copy of the object and assign it to that
variable by means of ‘new’ operator. The new operator dynamically
allocates memory for an object and returns a reference to that object.
RAKESH.C.M Page 40
The first statement declares a variable to hold the object reference.
null
rect1
The second statement assigns the object reference and allocates memory
Rectangle
rect1 object
Note: Each object contains its own instance variables of its class. This means that
any changes to the variables of one object have no effect on the variables of another.
But the function name is name for both objects.
It is also possible to create two or more references to the same object.
r1
Rectangle
object
r2
RAKESH.C.M Page 41
Example: int sum(int a, int b)
{
int c;
c=a+b;
return c;
}
Accessing class members: All variables must be assigned values before they
are used in our program. All class members are accessed by means of “dot” operator.
The general format of accessing instance variable of the class by dot operator is as:
Syntax: objectname.variablename;
Where,
objectname is name of the object, variablename is the name of the instance
variable.
Example: rect1.length=15;
rect1.width=10;
15 rect1.length
rect1
10 rect1.width
The general format of accessing instance methods of the class by dot operator is as:
Syntax: objectname.methodname(parameter-list);
Where,
objectname is name of the object, methodname is the name of the instance
method that calls with the object and paramerter-list is a list of actual values separated
by commas.
rect1.getdata(10,20);
RAKESH.C.M Page 42
// Write a program to calculate the area of a rectangle.
class Rectangle
{
int length1,width1;
void getdata(int x,int y)
{
length1=x;
width1=y;
}
int calarea()
{
int area=length1*width1;
return area;
}
}
class prg
{
public static void main(String[] args)
{
int a,b;
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
rect1.length1=15;
rect1.width1=4;
a=rect1.length1*rect1.width1;
System.out.println("Area of Rectangle1="+a);
rect2.getdata(2,3);
b=rect2.calarea();
System.out.println("Area of Rectangle2="+b);
}
}
Note: Two methods differ in only by return type will result in a syntax error.
RAKESH.C.M Page 43
// EXAMPLE PROGRAM FOR METHOD OVERLOADING
class overload
{
int square(int x)
{
return x*x;
}
double square(double x)
{
return x*x;
}
}
class check
{
public static void main(String[] args)
{
overload r1=new overload();
int k=r1.square(3);
double p=r1.square(4.0);
System.out.println("k value="+k);
System.out.println("p value="+p);
}
}
class overload1
{
int sum(int x)
{
return x+x;
}
int sum(int x,int y,int z)
{
return x+y+z;
}
}
class check1
{
public static void main(String[] args)
{
overload1 r1=new overload1();
int k=r1.sum(3,5,7);
System.out.println("k value="+k);
}
}
RAKESH.C.M Page 44
Constructors: A constructor is a special method of class, which is invoked
automatically, whenever an object of a class is created. It has the same name as its
class and resides similar to a method. A constructor has the following characteristics.
It doesn’t have any return type not even void
The constructor can be declared as public
It can be overloaded
It is normally used to initialize the member of the object
class Time1
{
int hour,min,sec;
public Time1()
{
hour=10;
min=45;
sec=23;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
}
}
class const1
{
public static void main(String[] args)
{
Time1 t=new Time1();
t.printdata();
}
}
O/P: 10hours:45minutes:23seconds
class Time1
{
int hour,min,sec;
RAKESH.C.M Page 45
public Time1(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
}
}
class const2
{
public static void main(String[] args)
{
Time1 t=new Time1(10,9,4);
t.printdata();
}
}
O/P: 10hours:9minutes:4seconds
class Time1
{
int hour,min,sec;
public Time1()
{
hour=0;
min=0;
sec=0;
}
public Time1(int h)
{
hour=h;
min=0;
sec=0;
}
public Time1(int h, int m)
{
hour=h;
min=m;
sec=0;
}
RAKESH.C.M Page 46
public Time1(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minute:"+sec+"sec");
}
}
class const3
{
public static void main(String[] args)
{
Time1 t=new Time1();
t.printdata();
Time1 t1=new Time1(9);
t1.printdata();
Time1 t2=new Time1(7,8);
t2.printdata();
Time1 t3=new Time1(10,9,4);
t3.printdata();
}
}
Static Class Members: Generally each class contains instance variables and
instance methods. Every time the class is instantiated, a new copy of each of them is
created. They are accessed using the objects with the dot operator.
If we define a member that is common to all the objects and accessed without
using a particular object i.e., the member belong to the class as a whole rather than the
objects created from the class. Such facility can be possible by using “static”
keyword.
The members declared with the static keyword are called static members.
RAKESH.C.M Page 47
Example1:
class static1
{
static int c=0;
void increment()
{
c++;
}
void display()
{
System.out.println("Value="+c);
}
}
class Mstatic
{
public static void main(String[] args)
{
static1 s=new static1();
static1 s1=new static1();
static1 s2=new static1();
s.increment();
s1.increment();
s2.increment();
s.display();
s1.display();
s2.display();
}
}
O/P: value=3
value=3
value=3
s1 s2 s3
s1 s2 s3
RAKESH.C.M Page 48
Example2:
class static1
{
static int a=10;
static int b=34;
static void call()
{
System.out.println("Value1="+a);
}
}
class Mstatic1
{
public static void main(String[] args)
{
static1.call();
System.out.println("Value2="+static1.b);
}
}
O/P: Value1=10
Value2=34
Example3:
class static2
{
static int a=10,b;
static void method(int x)
{
System.out.println("x="+x);
System.out.println("a="+a);
System.out.println("b="+b);
}
static
{
System.out.println("static block");
b=a*4;
}
}
class Mstatic2
{
public static void main(String[] args)
{
static2.method(35);
}
}
RAKESH.C.M Page 49
Access Modifiers/Control:
Java provides four types of Access Modifiers. They are public, protected, default and
private.
For good programming technique place member data as private and member functions
as public.
class modi
{
private int k=6;
void display()
{
System.out.println("K VALUE="+k);
}
}
class ex
{
public static void main(String[] args)
{
modi obj=new modi();
obj.display();
//System.out.println("k in main="+obj.k);
//this statement provides error since private variable
//can not be possible to access by other class
}
}
this keyword: Java define “this” keyword, that can be used inside any method to
refer the current object. “this” is always a reference to the object on which method
was invoked. “this” reference is implicitly used to refer to both the instance variables
and methods of current object.
RAKESH.C.M Page 50
// EXAMPLE PROGRAM FOR THIS KEYWORD
class Box
{
int len,dep,hei;
Box(int len,int dep, int hei)
{
this.len=len;
this.dep=dep;
this.hei=hei;
}
int volume()
{
return len*dep*hei;
}
}
class this1
{
public static void main(String[] args)
{
Box obj=new Box(1,2,3);
int x=obj.volume();
System.out.println("volume="+x);
}
}
O/P: volume=6
// EXAMPLE PROGRAM
class Box
{
int len=10;
void method()
{
int len=40;
System.out.println("local value="+len);
System.out.println("Instance value="+this.len);
}
}
class this2
{
public static void main(String[] args)
{
Box obj=new Box();
obj.method();
}
}
RAKESH.C.M Page 51
Argument Passing: Arguments passed to a sub-routine (method) is falls into two
categories.
1. Call by value
2. Call by reference
1. Call by Value: Call by value copies the value of an argument into the formal
parameter of the sub-routine. Therefore, if changes made to the parameter of the sub-
routine have no effect on the argument used to call it.
RAKESH.C.M Page 52
void change(Test ox)
{
ox.a*=2;
ox.b/=2;
}
}
class cbr
{
public static void main(String[] args)
{
Test obj=new Test(4,5);
System.out.println("Before calling a="+obj.a+" b="+obj.b);
obj.meth(obj);
System.out.println("After calling a="+obj.a+" b="+obj.b);
}
}
2. Indirect recursion: A method calls another method, which initiates to call the
initial method is called indirect recursion.
RAKESH.C.M Page 53
// Write a program to print the factorial of a given number using recursion
class a
{
double fact(double x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
}
class recur
{
public static void main(String[] args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
double t=obj.fact(p);
System.out.println("facatorial="+t);
}
}
// Write a program to print the first n Fibonacci sequence numbers using recursion
class a
{
int fib(int x)
{
if(x==0||x==1)
return x;
else
return (fib(x-1)+fib(x-2));
}
}
class Fibonacci
{
public static void main(String[] args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
for(int i=1;i<=p;i++)
{
int t=obj.fib(i);
System.out.println(" "+t);
}
}
}
RAKESH.C.M Page 54
// Write a program to print the sum of ‘n’ numbers using the recursive formula
sum (n) = 0 ; if n = 0
n + sum(n-1) ; if n 1
Example: Write a Java program that used both recursive and non-recursive
functions to print the nth value in the Fibonacci sequence.
import javax.swing.*;
class Fibo
{
int fibrec(int n)
{
int result;
if(n==1||n==2)
return 1;
else
return fibrec(n-1)+fibrec(n-2);
}
void fibnon(int n)
{
int a=1,b=1,i=3,c;
System.out.print(a+" "+b+" ");
while(i<=n)
{
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
i++;
}
System.out.println();
}
}
class Fibonacci
{
public static void main(String args[])
{
int n,p;
String sn;
Fibo obj=new Fibo();
sn=JOptionPane.showInputDialog("Enter how many numbers:");
n=Integer.parseInt(sn);
RAKESH.C.M Page 55
System.out.println("\nFibonacci series without recursion\n");
obj.fibnon(n);
}
}
The random( ) method generates a double value from 0.0 to 1.0(not included). The
range of values produced directly by random is often different than what is needed in
a specific application.
Example: A program that stimulates rolling six-sided die would required random
integers in the range (1,6)
The general formula for this type of problems using random method is:
a+(int)(Math.random( )*b)
Where,
‘a’ is a shifting value that is equal to the fist number in the range of integers
‘b’ is the scaling factor that is equal to the width of range of the integer.
class random
{
public static void main(String[] args)
{
for(int i=1;i<=20;i++)
{
int s=1+(int)(Math.random()*6);
System.out.print(s);
if(i%5==0)
System.out.print("\n");
}
}
}
RAKESH.C.M Page 56
Recursion Vs Iteration:
Recursion Iteration
Nested Class and Inner Classes It is possible to define a class within another
class such classes are known as nested classes. A nested class has access to all of the
variables and methods of its outer class. But the outer class doesn’t access the
variables and methods of nested class. Since the scope of a nested class is bounded
by the scope of its enclosing class.
A static nested class is a class started with ‘static’ modifier. Due to the static
it must access the members of its enclosing class through an object. Direct access
cannot be possible.
A non-static class is a class as ordinary representation of class. The most
important type of the non-static class is “Inner class”. The inner class has access to
all of the variables and methods of its outer class. Thus, inner class scope is fully
within the scope of its outer class.
Example:
class outer
{
int out_x=34;
void test()
{
inner in=new inner();
in.display();
}
class inner
{
void display()
{
System.out.println("value="+out_x);
}
}
}
RAKESH.C.M Page 57
class test
{
public static void main(String[] args)
{
outer y=new outer();
y.test();
}
}
STRINGS
1. String Class
2. StringBuffer Class
3. StringTokenizer Class
4.
String and StringBuffer classes are defined in java.lang pacakage.
StringTokenizer are defined in java.util package.
1. String Class:
It initializes string reference color to refer the anonymous string object blue.
Note: 1. Once we create a string object, we cannot change the contents of string
instance.
2. A variable declared as a string reference can be changed at any time.
String Constructors: String class provides several types of constructors. They are
a) String( ): It creates an empty string with no characters in it.
b) String(String): It takes one String as a parameter.
c) String(StringBuffer): Allocates a new string that contains the sequence of
characters currently contained in the string buffer argument.
d) String(byte[] bytes): Construct a new String by converting the specified array
of bytes using the platform's default character encoding.
e) String(bytes byte[], int startindex, int numberofcharacters): Allocates new
string positioned with the startindex by counting the number of charactes.
f) String(char chars[]): Creates a string initialized by an array of characters.
g) String(char chars[], int startindex, int numberofcharacters): Creates a string
initialized by an array of characters with the startindex by counting the number
of charactes.
RAKESH.C.M Page 58
Methods:
1. int length( ): It returns the number of characters in a given string.
Example: class len
{
public static void main(String[] args)
{
String s1=new String("hello");
System.out.println(s1.length());
}
}
2. char charAt(int where): It returns the character at the specified location. “where”
must be a nonnegative specified location within the string. The first element of a
string is considered to be at position “zero”.
Example:
class pos
{
public static void main(String[] args)
{
String s1=new String("hello java");
char c=s1.charAt(7);
System.out.println("character="+c);
}
}
O/P: a prog
RAKESH.C.M Page 59
4. boolean equals( ): It compares the two strings and returns true if the strings contain
the same characters in the same order, and false otherwise. The comparison is case-
sensitive.
Syntax: boolean equals(Object string);
Example:
class equal
{
public static void main(String[] args)
{
String s1=new String("india");
String s2=s1;
if(s1.equals(s2))
System.out.println("Strings are Equal");
else
System.out.println("Strings are not Equal");
}
}
5. boolean equalsIgnoreCase( ): It compares the two strings and returns true if the
strings contain the same characters in the same order, and false otherwise by ignoring
the case characters.
Syntax: boolean equalsIgnoreCase(String str);
Example:
class equall
{
public static void main(String[] args)
{
String s1=new String("india");
String s2=new String(“InDia”);
if(s1.equalsIgnoreCase(s2))
System.out.println("Strings are Equal");
else
System.out.println("Strings are not Equal");
}
}
6. int compareTo(String str ): It returns ‘0’ if the two strings are equal. ‘Negative
number’ if the invoking string is less than str and ‘postivite number’ if the invoking
string is greater than str that is passed as an argument. The comparision is case-
sensitive.
Example:
class comp
{
public static void main(String[] args)
RAKESH.C.M Page 60
{
String s1=new String("hello");
String s2=new String("india");
if((s1.compareTo(s2))>0)
System.out.println("S1 is greater than s2");
else if((s1.compareTo(s2))<0)
System.out.println("S2 is greater than s1");
else
System.out.println("Two stings are equal");
}
}
If we want to ignore case differences when comparing two strings, we use the
syntax of the form: int compareToIgnoreCase(String str)
This method was added by Java 2.
The first argument is the starting index of the string that invokes the method. The
second argument is a comparison string. The third argument is starting index in the
comparison string. The last argument is the number of characters to compare between
the two strings. IgnoreCase is true the method ignores the case of the objects being
compared.
Example 1:
class rmatch1
{
public static void main(String[] args)
{
String s1=new String("happy birthday");
String s2=new String("Happy birthday");
if(s1.regionMatches(0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not Match");
}
}
RAKESH.C.M Page 61
Example 2:
class rmatch1
{
public static void main(String[] args)
{
String s1=new String("happy birthday");
String s2=new String("Happy birthday");
if(s1.regionMatches(true,0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not Match");
}
}
Example:
class index
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.indexOf('v')); //O/P: 2
System.out.println(letter.indexOf("programming")); //O/P: 5
System.out.println(letter.indexOf('A')); //O/P: -1
}
}
Example:
class indexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.indexOf('m',2)); //O/P: 11
}
}
RAKESH.C.M Page 62
10. int lastIndexOf(int ch):
int lastIndexOf(char ch):
int lastIndexOf(String ch): It searches the last occurrence of the character. The
search is performed from the end of the string towards the beginning of the string. If
the character is found the index of that character in the string is return. Otherwise, it
returns ‘-1’.
Example:
class lindexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.lastIndexOf('n')); //O/P: 19
System.out.println(letter.lastIndexOf("language")); //O/P: 17
}
}
Example:
class lindexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.lastIndexOf('n',11)); //O/P: -1
}
}
12. String substring(int startIndex): It returns a copy of the sub string that begins
that startIndex and return to the end of the invoking string.
Example:
class sub
{
public static void main(String[] args)
{
String s=new String("Java programming language");
System.out.println(s.substring(8));
}
}
O/P: gramming language
RAKESH.C.M Page 63
13. String substring(int startIndex, int endIndex): It returns all the characters from
the beginning index upto but not including the ending index.
Example:
class s13
{
public static void main(String[] args)
{
String s=new String("program");
System.out.println(s.substring(2,5)); //O/P: ogr
}
}
Example:
class s14
{
public static void main(String[] args)
{
String s=new String("Java is a program");
if(s.startsWith("is"))
System.out.println("Match");
else
System.out.println("Not Match");
}
}
Example:
class s15
{
public static void main(String[] args)
{
String s=new String("Java ");
String s1=s.concat("program");
System.out.println(s1);
}
}
RAKESH.C.M Page 64
16. String replace(char original, char replacement): It replace all characters of one
character in the invoking string with another character.
Example:
class s16
{
public static void main(String[] args)
{
String s="Hello";
System.out.println(s.replace('l','w')); //O/P: Hewwo
}
}
Example:
class s17
{
public static void main(String[] args)
{
String s="HELLO";
System.out.println(s.toLowerCase()); //O/P: hello
}
}
Example:
class s17
{
public static void main(String[] args)
{
String s="hello";
System.out.println(s.toUpperCase()); //O/P: HELLO }
}
19. String trim(): It returns a copy of the invoking string from which any leading and
lining white space has been removed.
Example:
class s18
{
public static void main(String[] args)
{
RAKESH.C.M Page 65
String s=" hello";
System.out.println(s.trim());
}
}
Example:
class s20
{
public static void main(String[] args)
{
String s="hello";
char ch[]=s.toCharArray();
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}
Example:
class s21
{
public static void main(String[] args)
{
Integer i=new Integer(10);
System.out.println(i.toString()); //O/P: 10
}
}
class lab5
{
public static void main(String[] args)
{
String ch[]={"india","hai","andhra"};
String temp;
for(int i=0;i<ch.length-1;i++)
{
for (int j=i+1;j<ch.length;j++)
{
RAKESH.C.M Page 66
if((ch[i].compareTo(ch[j]))>0)
{
temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
}
}
}
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}
import javax.swing.JOptionPane;
class lab4
{
public static void main(String[] args)
{
String s;
s=JOptionPane.showInputDialog("Enter a String");
char ch[]=s.toCharArray();
int i,j,count=0;
for(i=0,j=ch.length-1;i<j;i++,j--)
{
if(ch[i]!=ch[j])
{
System.out.println("Not polindrome");
count=1;
break;
}
}
if(count==0)
System.out.println("Polindrome");
}
}
2. StringBuffer Class:
Once a string object is created its contents cannot be changed. But the
StringBuffer class provides the feature of creating and manipulating dynamic string
information i.e., mutable strings. Every StringBuffer class is capable for storing a
number of characters specified by its capacity. If the capacity of StringBuffer
exceeded the capacity is automatically expanded to accommodate the additional
characters.
RAKESH.C.M Page 67
StringBuffer Constructors:
Example:
class sb
{
public static void main(String[] args)
{
StringBuffer s1,s2,s3;
s1=new StringBuffer();
s2=new StringBuffer("hello");
s3=new StringBuffer(45);
System.out.println(s1.capacity()+s2.capacity()+s3.capacity()); //O/P: 82
}
}
Methods:
Example:
class sb1
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
System.out.println(s.length()); //O/P: 5
}
}
RAKESH.C.M Page 68
Example:
class sb2
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
System.out.println(s.capacity()); //O/P: 21
}
}
Example:
class sb3
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
s.ensureCapacity(75);
System.out.println(s.capacity()); //O/P: 75
}
}
Example:
class sb4
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdefghijkl");
s.setLength(5);
System.out.println(s); //O/P: abcde
}
}
Example:
class sb5
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdefghijkl");
System.out.println(s.charAt(7)); //O/P: h
}
}
RAKESH.C.M Page 69
6. void setCharAt(int where, char ch): It takes an integer and a character argument
and sets the character at the specified position of the character argument.
Example:
class sb6
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdef"); //O/P: Hbcdef
s.setCharAt(0,'H');
System.out.println(s);
}
}
Example:
class sb7
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abc def");
char ch[]=new char[s.length()];
s.getChars(3,s.length(),ch,0);
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]); //O/P: def
}
}
Example:
class sb8
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdef");
System.out.println(s.reverse());
}
}
RAKESH.C.M Page 70
3. StringTokenizer class:
StringTokenizer Constructors:
a) StirngTokenizer(Stirng str)
b) StirngTokenizer(Stirng str, String delimiters)
c) StirngTokenizer(Stirng str, String delimiters, boolean delimiterAsToken)
In all versions str is a string that is tokenized.
In the first version, the default delimiters are used.
In the second version and third versions delimiters in string that specifies the
delimiters.
In the third version if “delimiterAsToken” is true then the delimiters also
returned as tokens when the string is tokenized otherwise, the delimiters are not
returned. Delimiters are not returned as tokens by the first two forms.
Methods:
1. int countTokens(): Using the current set of delimiters the method determines the
number of tokens left to be tokenized and return the result.
2. boolean hasMoreTokens(): It returns true if one or more tokens remain in the
string and returns false if there are none.
3. String nextToken(): It returns the next token as string.
Example:
import java.util.*;
class st
{
public static void main(String[] args)
{
String s=new String("abc def gh");
StringTokenizer t=new StringTokenizer(s);
System.out.println(t.countTokens());
while(t.hasMoreTokens())
System.out.println(t.nextToken());
}
}
O/P: 3
abc
def
gh
RAKESH.C.M Page 71
Example: Write a program that reads a line of integers, then displays each integer and
the sum of all the integers
import javax.swing.JOptionPane;
import java.util.*;
class lab2c
{
public static void main(String[] args)
{
String s;
s=JOptionPane.showInputDialog("Enter the string");
StringTokenizer t=new StringTokenizer(s,"$");
int a,sum=0;
System.out.println("Integers Count:");
System.out.println(t.countTokens());
System.out.println("Given Values are:");
while(t.hasMoreTokens())
{
a=Integer.parseInt(t.nextToken());
System.out.println(a);
sum=sum+a;
}
System.out.println("Total="+sum);
}
}
Example: Write a java program to make frequency count of words in a given text
import java.io.*;
import java.lang.*;
import java.util.*;
class Frequency
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the line of text");
String str=dis.readLine();
System.out.println("Enter the string");
String s1=dis.readLine();
StringTokenizer st=new StringTokenizer(str);
int count=0;
while(st.hasMoreTokens())
{
if(s1.compareTo(st.nextToken())==0)
count++;
else
continue;
}
System.out.println("Frequency="+count);
}
}
RAKESH.C.M Page 72
Garbage Collection
Objects are dynamically allocated by using the new operator such objects are
destroyed automatically and their memory released for later reallocation in Java. The
technique that accomplishes this is called “Garbage Collection”. Garbage collection
works when no references to an object exist, the object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed. Java run-time
implementations will take various approaches to garbage collection.
finalize( ) method:
The garbage collector of an object called this method when the garbage
collection determines that those are no more references to the object. It is also placed
some actions inside the finalized method. The following points are related to
finalize() method.
Example:
RAKESH.C.M Page 73
class Mg
{
public static void main(String[] args)
{
Garbage obj=new Garbage();
Garbage obj1=new Garbage();
obj.setdata(10,20);
obj.printdata();
obj1=null;
System.gc(); // method to call garbage collector
//obj1.setdata(2,3); //error
obj.printdata();
}
}
***
RAKESH.C.M Page 74
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY,
II YEAR B.Tech. CSE – II SEM
INHERITANCE
The mechanism of deriving a new class from an old one is called inheritance.
A class that is inherited (old class) is called a super class or base class or parent class.
The class that does the inheriting (new class) is called a subclass or derived class or
child class. Inheritance allows subclasses to inherit all the variables and methods of
their parent classes.
a) Single Inheritance: Derivation a subclass from only one super class is called
Single Inheritance.
B C D
RAKESH.C.M Page 75
c) Multilevel Inheritance: Derivation of a class from another derived class s called
Multilevel Inheritance.
d) Multiple Inheritance: Derivation of one class from two or more super classes is
called Multiple Inheritance. But Java does not support Multiple Inheritance directly.
It can be implemented by using Interface concept.
A B
B C
RAKESH.C.M Page 76
Defining a Subclass: A subclass is defined as
The keyword extends signifies that the properties of the super class name are
extended to the subclass name. The subclass will now contain its own variables and
methods as well as those of the super class. But it is not vice-versa.
class A
{
int len,bre;
void getdata(int x,int y)
{
len=x;
bre=y;
}
void printdata()
{
System.out.println("length="+len);
System.out.println("Breadth="+bre);
}
}
class B extends A
{
int wid;
void putdata(int x,int y,int z)
{
len=x;
bre=y;
wid=z;
}
void printdata1()
{
printdata();
System.out.println("Width="+wid);
}
void calarea()
{
int area=len*bre*wid;
System.out.println("Area="+area);
}
}
RAKESH.C.M Page 77
class Single
{
public static void main(String[] args)
{
B obj=new B();
obj.putdata(10,20,30);
obj.printdata1();
obj.calarea();
}
}
class A
{
int len,bre;
void getdata(int x,int y)
{
len=x;
bre=y;
}
void printdata()
{
System.out.println("length="+len);
System.out.println("Breadth="+bre);
}
}
class B extends A
{
int wid;
void getdata1(int x,int y)
{
getdata(x,y);
}
void calarea()
{
printdata();
int area=len*bre;
System.out.println("Area="+area);
}
}
class C extends A
{
int wid;
void putdata(int x,int y,int z)
{
len=x;
RAKESH.C.M Page 78
bre=y;
wid=z;
}
void printdata1()
{
printdata();
System.out.println("Width="+wid);
}
void calarea1()
{
int area=len*bre*wid;
System.out.println("Area="+area);
}
}
class Hierarchical
{
public static void main(String[] args)
{
B obj=new B();
obj.getdata1(10,20);
obj.calarea();
C obj1=new C();
obj1.putdata(1,2,3);
obj1.printdata1();
obj1.calarea1();
}
}
import javax.swing.JOptionPane;
class Student
{
int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
void printdata1()
{
System.out.println("Roll Number="+rno);
}
}
RAKESH.C.M Page 79
class Exam extends Student
{
int m1,m2,m3;
void readdata2()
{
readdata1();
m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));
m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));
m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));
}
void printdata2()
{
printdata1();
System.out.println("Sub 1 marks="+m1);
System.out.println("Sub 2 marks="+m2);
System.out.println("Sub 3 marks="+m3);
}
}
class Results extends Exam
{
int avg;
void printdata3()
{
printdata2();
avg=(m1+m2+m3)/3;
if(avg<35)
System.out.println("FAIL");
else if(avg>=35 && avg<50)
System.out.println("THIRD CLASS");
else if(avg>=50 && avg<60)
System.out.println("SECOND CLASS");
else if(avg>=60 && avg<75)
System.out.println("FIRST CLASS");
else if(avg>=75)
System.out.println("DISTINCTION");
}
}
class Multilevel
{
public static void main(String[] args)
{
Results obj=new Results();
obj.readdata2();
obj.printdata3();
}
}
RAKESH.C.M Page 80
Member Access Rules:
1. By means of sub class object it is possible to access all the instance variables and
instance methods of the super class.
2. By means of sub class object it cannot be possible to access the instance variable of
super class, if it is declared as private. Since, the data is protected in that class.
import javax.swing.JOptionPane;
class Student
{
private int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
}
class Exam extends Etudent
{
void printdata1()
{
readdata1();
System.out.println("Roll Number="+rno); // produces compilation error
}
}
class MLevel
{
public static void main(String[] args)
{
Exam obj=new Exam();
obj.printdata1();
}
}
3. Referring to super class object with a subclass reference produces syntax error. In
such case we need type casting.
Example:
import javax.swing.JOptionPane;
class Student
{
int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
}
RAKESH.C.M Page 81
class Exam extends Student
{
void printdata1()
{
readdata1();
System.out.println("Roll Number="+rno);
}
}
class Mit
{
public static void main(String[] args)
{
Student s1=new Exam();
Exam e1=(Exam)s1;
e1.printdata1();
}
}
Example 1:
class Student
{
public Student()
{
System.out.println("super");
}
}
class Exam extends Student
{
public Exam()
{
System.out.println("sub");
}
}
RAKESH.C.M Page 82
class St
{
public static void main(String[] args)
{
Exam obj=new Exam();
}
}
O/P: super
sub
Example 2:
class Student
{
public Student()
{
System.out.println("super");
}
}
class Exam extends student
{
public Exam()
{
super( ); // explicit call of super( )
System.out.println("sub");
}
}
class Stl
{
public static void main(String[] args)
{
Exam obj=new Exam();
}
}
O/P: super
sub
Example 3:
class Student
{
int len,bre;
public Student(int a,int b)
{
len=a;
bre=b;
}
RAKESH.C.M Page 83
int area()
{
return len*bre;
}
}
class Exam extends Student
{
int ht;
public Exam(int x,int y,int z)
{
super(x,y);
ht=z;
}
int volume()
{
return len*bre*ht;
}
}
class s
{
public static void main(String[] args)
{
Exam obj=new Exam(2,3,4);
System.out.println("area="+obj.area());
System.out.println("volume="+obj.volume());
}
}
super.member;
Where,
member can be either a method or an instance variable
Example:
class A
{
int i=7;
}
class B extends A
{
int i=6;
RAKESH.C.M Page 84
void show()
{
System.out.println("super i="+super.i);
System.out.println("sub i="+i);
}
}
class s1
{
public static void main(String[] args)
{
B obj=new B();
obj.show();
}
}
FORMS OF INHERITANCE
Construction: The child class makes use jof the behavior provided by the
parent class but is not a subtype of the parent class.
Extension: The child class adds new functionality to the parent class, but
does not change any inherited behavior.
Limitation: The child class restricts the use of some of the behavior
inherited from the parent class.
Combination: The child class inherits features from more than one parent
class. Although multiple inheritance is not supported directly
by Java, it can be simulated in part by classes that used both
inheritance and implementation of an interface, or implementj
two or more interfaces.
BENEFITS OF INHERITANCE
1. Software Reusability:
When behaviour is inherited from another class, the code that provides that
behavior doesnot have to be rewritten.
RAKESH.C.M Page 85
2. Increased Reliability:
When the same components are used in two or more applications, the code
will be exercised more than code that is developed for a single application. Thus, the
bugs in each such code tends to be discovered more quickly, and later application
gains the benefit of using components that are more error free.
3. Code Sharing:
Code sharing can occur on several levels with object oriented techniques.
Form of sharing occurs when two or more classes developed by a single programmer
as part of a probject inherits from a single parent class.
4. Consistency of Interface:
When two or more classes inherits from the same upper class, we are assured
that the behavior they inherts will be same on all cases.
5. Software Components:
6. Rapid Prototyping:
8. Information Hiding:
RAKESH.C.M Page 86
THE COSTS OF INHERITANCE
1. Execution Speed
2. Program Size
3. Message-Passing Overhead
4. Program Complexity
POLYMORPHISM
Method Overriding
A method in a subclass has the same name, type of the variables and order of
the variables as a method in its super class, then the method in the subclass is said to
be override the method in the super class. The process is called Method Overriding.
In such process the method defined by the super class will be hidden.
When the method is called, the method defined in the super class has invoked
and executed instead of the method in the super class. The super reference followed
by the dot (.) operator may be used to access the original super class version of that
method from the subclass.
Note: 1. Method Overriding occurs only when the name and type signature of
the two methods are identical.
2. If method name is identical and the type signature is different, then the
process is said to be Method Overloading.
Example 1:
class A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}
RAKESH.C.M Page 87
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
System.out.println("k="+k);
}
}
class override
{
public static void main(String[] args)
{
B obj=new B(1,2,3);
obj.show();
}
}
O/P: k=3
Example 2:
class A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
RAKESH.C.M Page 88
void show()
{
super.show();
System.out.println("k="+k);
}
}
class Override
{
public static void main(String[] args)
{
B obj=new B(1,2,3);
obj.show();
}
}
O/P: i=1
j=2
k=3
“Super class reference variable can refer to a subclass object” is the principle
to resolve calls to overridden methods at run time. If a super class contains a method
that is overridden by a subclass, then when different types of objects are referred to
through a super class reference variable, different version of the methods are executed
and the determination is made at run time.
class Figure
{
double dim1,dim2;
Figure(double x,double y)
{
dim1=x;
dim2=y;
}
double area()
{
System.out.println("Area undefined");
return 0;
}
}
RAKESH.C.M Page 89
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Rectangle Area");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("Triangle Area");
return dim1*dim2/2;
}
}
class Run
{
public static void main(String[] args)
{
Figure obj=new Figure(10,10);
Rectangle obj1=new Rectangle(9,5);
Triangle obj2=new Triangle(10,8);
RAKESH.C.M Page 90
ABSTRACT CLASS
Classes from which objects cannot be instantiated with new operator are called
Abstract Classes. Each abstract class contains one or more abstract methods. In a
class if there exist any method with no method body is known as abstract method. An
abstract method is declared as:
RAKESH.C.M Page 91
class Abst
{
public static void main(String[] args)
{
//Figure obj=new Figure(10,10); //error
Example: Write a java program to create an abstract class name Shape that
contains an empty method named numberOfSides().Provide three classes named
Trapezoid, Triangle, Hexagon such that each one of the classes extends the class
Shape. Each one of the classes contains only the method numberOfSides() that
shows the number of sides in the given geometrical figures.
RAKESH.C.M Page 92
public class Sides
{
public static void main(String[] args)
{
Trapezoid t=new Trapezoid();
Triangle t1=new Triangle();
Hexagon h=new Hexagon();
t.numberOfSides();
t1.numberOfSides();
h.numberOfSides();
}
}
final keyword
a) final as constant: A variable can be declared as constant with the keyword final. It
must be initialized while declaring. One we initialized the variable with final
keyword it cannot be modified in the program. This is similar to the const in C/C++.
Example: final int x = 10;
x = 45 //error
Example: class A
{
final void show( )
{
System.out.println(“Hello”);
}
}
RAKESH.C.M Page 93
class B extends A
{
void show( )
{ //error
System.out.println(“Hai”);
}
}
c) final to prevent inheritance: The class that is declared as final implicitly declares
all of its methods as final. The class cannot be extended to its subclass.
OBJECT CLASS
Java provides a special class called “Object” class that is available in java.lang
package. It is the super class of all other classes. So, a reference variable of type
Object is created, it refers to object of any other class. Object class defines the
following methods that are available in every object.
Method Purpose
Object clone( ) Creates a new object that is the same as the
object being cloned
boolean equals(Object object) Determines whether one object is equal to
another
void finalize( ) Called before an unused object is recycled
Class getClass( ) Obtains the class of an object at run time
int hashCode( ) Returns the hash code associated with the
invoking object
void notify( ) Resumes execution of a thread waiting on
the invoking object
void notifyAll( ) Resumes execution of all threads waiting
on the invoking object
String toString( ) Returns a string that describes the object
RAKESH.C.M Page 94
void wait( ) Waits on another thread of execution
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds)
Array of Objects: To instantiate more than one object for a single class, we use
Array of Objects.
Example:
import javax.swing.JOptionPane;
class A
{
int x,y;
void readdata()
{
x=Integer.parseInt(JOptionPane.showInputDialog("Enter x value"));
y=Integer.parseInt(JOptionPane.showInputDialog("Enter y value"));
}
void printdata()
{
System.out.println("x="+x+"\n"+"y="+y);
}
}
class Aob
{
public static void main(String[] args)
{
a ob[]=new a[5];
for(int i=0;i<5;i++)
{
ob[i]=new a();
ob[i].readdata();
ob[i].printdata();
}
}
}
***
RAKESH.C.M Page 95
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY,
II YEAR B.Tech. CSE – II SEM
INTERFACES
Here,
access specifier is public or not used. public access specifier indicates that the
interface can be used by any class. Otherwise, the interface will accessible to
class that are defined in the same package as in the interface.
interface keyword is used to declare the class as an interface.
it-name is the name of the interface and it is a valid identifier.
Variables declared inside the interface are implicitly final and static. They
cannot be changed in the implementing class.
All the methods in an interface are implicitly abstract methods. Method
implementation is given in later stages.
The main difference between a class and interface is class contains methods
with method body and the interface contains only abstract methods.
RAKESH.C.M Page 96
Implementing Interfaces: Once an interface has been defined, one or more classes
can implement that interface. “implements” keyword used for implementing the
classes. The syntax of implements is as follows.
If a class implements more than one interface, the interfaces are separated with
a comma operator. The methods that implement an interface must be declared public.
Also type signature of the implementing method must match exactly the type
signature specified in the interface definition.
Example:
interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it2 obj=new it2();
obj.add(3,4);
obj.sub(5,2);
System.out.println(obj.x+obj.y);
obj.x=70; // error since x is final variable in interface
}
}
Note:
1. Interface methods are similar to the abstract classes so, that it cannot be
instantiated.
2. Interface methods can also be accessed by the interface reference variable
refer to the object of subclass. The method will be resolved at run time. This process
is similar to the “super class reference to access a subclass object”.
RAKESH.C.M Page 97
Example:
interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it2 obj=new it2();
it1 ref;
ref=obj;
System.out.println(ref.x+ref.y);
}
}
3. If a class includes an interface but does not fully implement the methods
defined by that interface, then the class becomes abstract class and must be declared
as abstract in the first line of its class definition.
Example:
interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
abstract class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
}
RAKESH.C.M Page 98
class it3 extends it2
{
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it3 obj=new it3();
obj.add(5,6);
}
}
1. interface A
implements
B
class
extends
class C
2. interface A
implements implements
interface B interface C
3.
class A D interface
extends extends
implements
class B E interface
extends
class C
RAKESH.C.M Page 99
4. interface A B interface
implements implements
C
interface
implements
D
class
A B
Example:
class Test
{
int sub1,sub2,sub3;
void readdata1(int x,int y,int z)
{
sub1=x;
sub2=y;
sub3=z;
}
void printdata1()
{
System.out.println("sub1 marks="+sub1);
System.out.println("sub2 marks="+sub2);
System.out.println("sub3 marks="+sub3);
}
}
RAKESH.C.M Page 100
interface Sports
{
int smarks=55;
public void printdata2();
}
class Multiple
{
public static void main(String[] args)
{
Result obj=new Result();
obj.readdata1(35,67,89);
obj.printdata2();
}
}
B C
import javax.swing.JOptionPane;
class Student
{
int rno;
String name;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
name=JOptionPane.showInputDialog("Enter name");
}
void printdata1()
{
System.out.println("Roll number="+rno);
System.out.println("Name ="+name);
}
}
class Test extends Student
{
int m1,m2,m3;
void readdata2()
{
m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));
m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));
m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));
}
void printdata2()
{
System.out.println("Sub1="+m1+" Sub2="+m2+" Sub3="+m3);
}
}
interface Sports
{
int smarks=55;
public void printdata3();
}
class Hybrid
{
public static void main(String[] args)
{
Result obj=new Result();
obj.readdata3();
obj.printdata4();
}
}
PACKAGES
Defining a Package:
Where,
pack-name is the name of the package.
The class that is defined in the package must be start with the public access
modifier. So, that it can be accessible by any another of them. If it is not
public, it is possible to access only in that package.
Java uses file system directories to store packages. We save the program with
number.java and compile the package is as
javac –d . number.java
Example 1:
import mypack.number;
class pack
{
public static void main(String[] args)
{
number obj=new number();
obj.add(3,4);
}
}
Example 2:
package math1;
public class Mcal
{
public void square(int x)
{
System.out.println("Square of "+x+" is"+(x*x));
}
import math1.Mcal;
class calc
{
public static void main(String[] args)
{
Mcal obj=new Mcal();
obj.square(3);
obj.cube(4);
}
}
Example 3:
package p6;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal<0)
{
System.out.println(name+"---"+bal);
}
}
}
import p6.Balance;
class Account
{
public static void main(String[] args)
{
Balance c[]=new Balance[3];
c[0]=new Balance("John",123.33);
c[1]=new Balance("Arun",157.02);
Note:
1. Java source file contains only one public class and any number of non-
pubic classes. The filename should be same as the name of the public class with .java
extension.
Let we want to access all the classes of information then the classes are
stored in different files with the same package name.
package mypack;
public class number1
{
public void sub(int a,int b)
{
System.out.println("sub="+(a-b));
}
}
Sub Packages: It is also possible to create sub packages for the main package.
Example:
package pack1;
public class x
{
public void show()
{
System.out.println("Super");
}
}
package pack1.pack2;
public class y
{
public void display()
{
System.out.println("Sub");
}
}
import pack1.x;
import pack1.pack2.y;
class che
{
public static void main(String[] args)
{
x obj=new x();
obj.show();
y obj1=new y();
obj1.display();
}
}
RAKESH.C.M Page 107
Access Protection
Java provides four types Access modifiers as public, private, default and
protected. Any variable declared as public, it could be accessed from anywhere. Any
variable declared as private cannot be seen outside of its class. Any variable declared
as default, it is visible to subclasses as well as to other classes in the same package.
Any variable declared as protected, it allows an element to be seen outside of current
package, but only to classes that subclass directly.
Example:
package p1;
public class protect
{
int n=1;
private int n_pri=2;
protected int n_pro=3;
public int n_pub=4;
public protect()
{
System.out.println("Super constructor");
System.out.println("default="+n);
System.out.println("private="+n_pri);
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}
package p1;
class derive extends protect
{
derive()
{
System.out.println("Sub constructor");
System.out.println("default="+n);
//System.out.println("private="+n_pri);
//since it is a private variable in package p1
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}
CLASSPATH
A class path is an environmental variable, which tells the java virtual machine and
other java tools (java, javac), where to find the class libraries, including user-defined
class libraries.
C:\jdk1.2.1\lib\classes.zip
C:\>SET CLASSPATH=%CLASSPATH%;C:\P
Data storage in variables and arrays is temporary. The data is loss when the
program terminates. Files are used for long term storage of large amounts of data,
even after the program that created the data terminates.
File: A File is a collection of related records placed in a specific area on the disk.
Data that is stored in files is often called persistent data. A record is a collection of
several fields and the field is a collection of characters. Each character in a computer
character set is represented as a pattern of 1’s and 0’s.
Creation, Updating, Managing data etc., using file is known as ‘File Processing’.
File Class: java.io package supports for Input & Output operations on files. This
package provides a class known as File Class to creating Files. File Object is used to
manipulate or obtain the information associated with a disk file, such as permission,
data, directory path and soon.
Methods:
1. boolean canRead( )
2. boolean canWrite( )
3. boolean exists( )
4. String getName( )
5. String getParent( )
6. String getPath( )
7. boolean isDirectory( )
8. boolean isFile( )
9. long length( )
10. long lastModified( )
11. boolean isHidden( )
12. String getAbsolutePath( )
13. boolean isAbsolute( )
14. String [] list( )
import java.io.*;
class FileDemo
{
public static void main(String[] args)
{
File f=new File("D:/shabbir/wish.java");
System.out.println(f.canRead()); //true
System.out.println(f.canWrite()); //true
System.out.println(f.exists()); //true
System.out.println(f.getName()); //wish.java
System.out.println(f.getParent()); //D:\shabbir
System.out.println(f.getPath()); //D:\shabbir\wish.java
System.out.println(f.isDirectory()); //false
System.out.println(f.isFile()); //true
System.out.println(f.length()); //210
System.out.println(f.lastModified()); //1165345688000
System.out.println(f.isHidden()); //false
System.out.println(f.getAbsolutePath()); //D:\shabbir\wish.java
System.out.println(f.isAbsolute()); //true
}
}
import java.io.*;
class All
{
public static void main(String[] args)
{
File f=new File("D:/shabbir");
String str[]=null;
if(f.isDirectory())
str=f.list();
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
}
FilenameFilter Interface: list( ) method, it returns all the files existed in the given
directory. When we want to limit the number of files returned by the list( ) method to
include only those files that match a certain filename pattern or filtered, such case use
the second form of list( ) method as
The accept( ) method returns true for files in the directory specified by
directory that should be included in the list; otherwise false.
Example: Write a program to list the filenames that are ended with .java extension
import java.io.*;
class Filter implements FilenameFilter
{
public boolean accept(File f,String str)
{
if(str.endsWith(".java"))
return true;
else
return false;
}
}
class AllDemo
{
public static void main(String[] args)
{
File f=new File("D:/shabbir");
Filter obj=new Filter();
String str[]=null;
if(f.isDirectory())
str=f.list(obj);
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
}
STREAMS
When a file is opened, an object is created and a stream is associated with the
object. Three stream objects are created by the java system automatically when the
program execution begins. They are:
I/O Streams
Java 2 defines two types of Streams called Byte Streams and Character
Streams.
Byte Stream provides a convenient way for handling input and output of bytes of data.
Character Stream provides a convenient way for handling input and output of
characters of data.
Byte Streams: Byte Stream classes are used for processing the data in the form of
bytes. This class defines two important abstract classes called InputStream and
OutputStream.
InputStream: It is an abstract class that defines Java’s model of streaming byte input.
The system is reading the data in the form of bytes from the physical device using
InputStream. The methods that are provided by the InputStream class are:
a) void close( ): Closes this output stream and releases any system resources
associated with this stream.
b) void flush( ): It clears the output buffers.
c) void write(int b): Write a single byte b to an output stream.
d) void write(byte buf[]):Writes buf.length bytes from the specified byte array
to this output stream.
e) void write(byte buf[], int off, int len): Writes len bytes from the specified
byte array starting at offset off to this output stream.
FileInputStream
Example:
import java.io.*;
class FISDemo
{
public static void main(String[] args)throws IOException
{
FileInputStream fis=new FileInputStream("d:/shabbir/wi.txt");
System.out.println(fis.available());
int k;
while((k=fis.read())!=-1)
System.out.print((char)k);
fis.close();
}
}
Example 1:
import java.io.*;
class FOSDemo1
{
public static void main(String[] args)throws IOException
{
FileOutputStream fos=new FileOutputStream("d:/shabbir/tt.txt");
fos.write(65); //O/P: A
fos.close();
FileOutputStream fos1=new FileOutputStream("d:/shabbir/tt.txt",true);
byte buf[]={66,67,68,69,70};
fos1.write(buf); //O/P: ABCDEF
fos1.close();
}
}
Example 2:
import java.io.*;
class FO SDemo2
{
public static void main(String[] args)throws IOException
{
FileOutputStream fos=new FileOutputStream("d:/shabbir/wi1.txt");
String s=new String("hello");
byte b[]=s.getBytes(); //this method converts string into byte array
fos.write(b);
fos.close();
}
}
//O/P: hello
import java.io.*;
class CopyDemo
{
public static void main(String[] args)throws IOException
{
FileInputStream fis=new FileInputStream("d:/shabbir/wi.txt");
FileOutputStream fos=new FileOutputStream("d:/shabbir/ci.txt");
int k;
while((k=fis.read())!=-1)
fos.write(k);
fos.close();
fis.close();
}
}
DataInputStream:
DataInputStream is an input stream that contains methods for reading the Java
standard data types.
DataInputStream extends FilterInputStream, which extends InputStream,
and it implements the DataInput interface.
Methods:
DataOutputStream:
Methods:
import java.io.*;
class Fileoperation
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter filename");
String str=dis.readLine();
File f=new File(str);
if(f.exists())
{
System.out.println("File exists");
if(f.canRead())
System.out.println("File is readable");
else
System.out.println("File is not readable");
if(f.canWrite())
System.out.println("File is writable");
else
System.out.println("File is not writable");
if(f.isFile())
System.out.println("Given string is a file");
else
System.out.println("Given string is not a file");
System.out.println("Length of file="+f.length()+" bytes");
}
else
System.out.println("File doesn't exists");
}
}
Example: Write a java program that reads a file and displays the file on the
screen with a line number before each line
import java.io.*;
class Addlineno
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
String str;
System.out.println("Enter a filename");
str=dis.readLine();
File f=new File(str);
FileInputStream fis=new FileInputStream(f);
Example: Write a java program that displays the no.of characters, lines and
words in a text file
import java.io.*;
class Count
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter a file name");
String str=dis.readLine();
FileInputStream fis=new FileInputStream(str);
int k,nc=0,nw=1,nl=1;
while((k=fis.read())!=-1)
{
char ch=(char)k;
if(ch==' '||ch=='\t'||ch=='\n')
nw++;
if(ch=='\n')
nl++;
nc++;
}
System.out.println("No.of characters="+nc);
System.out.println("No.of words="+nw);
System.out.println("No.of lines="+nl);
fis.close();
}
}
Character Streams: Character Stream classes are used for processing the data in the
form of characters. This class defines two important abstract classes called Reader
and Writer.
Reader: It is an abstract class that defines Java’s model of streaming character input.
The system is reading the data in the form of characters from the physical device
using Reader. The methods that are provided by the Reader class are:
a) void close( ): Closes the input source. Further read attempts will generate
an IOException
d) int read(char buf[], int off, int num): Attempts to read up to num
characters into buffer starting at buffer[off], returning the number of
characters successfully read. –1 is returned when the end of file is
encountered.
Writer: It is an abstract class that defines Java’s model of streaming character output.
The system is sending the data in the form of characters to the physical device using
Writer. The methods that are provided by the Writer class are:
a) void close( ): Closes the output stream. Further write attempts will
generate an IOException.
***
EXCEPTION HANDLING
class hello
{
public static void main(String[] args)
{
int a=10,b;
b=a/0;
System.out.println("value="+b);
}
}
When we try to compile this program, it does not produce any errors. But
when it runs the program it produces a message as “java.lang.ArithmeticException: /
by zero”. This exception error message is displayed and the program terminates
without executing the remaining statements.
Exception Handling is used in situation arises the system can recover from
causing the exception. The procedure is called Exception Handling and done by the
Exception Handler.
Errors Exceptions
(Asynchronous) (Synchronous)
Java defines several exception classes inside the java.lang package. These are
all subclass of Run-time Exceptions. The following are the some of the examples of
exceptions and these are unchecked exceptions because the compiler does not check
to see if a method handles or throws these exceptions.
Exception Meaning
java.lang package contains some another type of exceptions that does not
handle itself. Here, the compiler checks that what is to be done when this arise,
because of this checking that they are called checked exceptions. Examples for
checked exceptions are
Exception Meaning
Java exception handling is managed through five keywords. They are 1) try
2)catch 3) throw 4) throws 5) finally. The general format of an exception-handling
block is as:
Syntax: try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exob)
{
// exception handler for exception type1
}
catch (ExceptionType2 exob)
{
// exception handler for exception type2
}
.
.
finally
{
// block of code to be executed before of try block ends
}
Here, ExceptionType is the type of exception that has occurred and exob is the
exception object.
try block: The statements that are produces exception are identified in the program
and the statements are placed with in a try block
Syntax: try
{
// block of code to monitor for errors
}
If an exception occurs within the try block, the appropriate exception handler
(catch block) associated with the try block handles the exception immediately.
catch block: The catch block is used to process the exception raised. The catch
block is placed immediately after the try block.
Syntax: finally
{
// block of code to be executed before of try block ends
}
1. The control enters into the try block and executes the statements. If an
exception is raised, the exception throws and it caught by exception handler catch
block. And the particular catch block statements are executed. The control never
backs again to the try block. If no exceptions raised, catch blocks are not executed the
control directly passed to the finally block.
2. No statements are placed between try block and catch block.
Example 1:
class ex11
{
public static void main(String[] args)
{
try
{
int a=10,b;
b=a/0;
System.out.println("b="+b);
}
catch(ArithmeticException e)
{
System.out.println("Exception raised");
}
System.out.println("Quit");
}
}
Example 2:
class ex12
{
public static void main(String[] args)
{
int x[]=new int[10];
try
{
x[20]=100;
}
Example: / by zero
b) String toString( ): It returns an error message with the class name of the exception
the descriptive string to be stored in the exception.
package
class
string
c) void printStackTrace( ): This is the standard output error stream. It displays the
error message with the class name of the exception the descriptive string to be stored
in the exception along with the line number and name of the program.
Example: java.lang.ArrayIndexOutOfBoundsException
at ex12.main (ex12.java:8)
Example 1:
class ex12
{
public static void main(String[] args)
{
int x[]=new int[10];
Example 2:
class ex12
{
public static void main(String[] args)
{
String s=new String("Java programming language");
try
{
System.out.println(s.substring(45));
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
}
Example 3:
import java.text.DecimalFormat;
class n
{
public static void main(String[] args)
{
try
{
double x=25.6776;
DecimalFormat d=null;
System.out.println(d.format(x));
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());
Multiple catch clauses handle the situation where more than one exception
could be raised by a single piece of code. In such situations specify two or more catch
blocks, each specify different type of exception. Multiple catch statements are
arranged in respective order of exceptions that araised by the try block (optional).
Example:
class cat
{
public static void main(String[] args)
{
try
{
int a=args.length;
System.out.println("a="+a);
int b=42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
}
Note: A subclass must come before their super classes in a series of catch statements.
Exception class is the super class of all exceptions.
Example:
class cat1
{
public static void main(String[] args)
{
A try block is placed inside the block of another try block is termed as Nested
try block statements. If any error statement is in outer try block it goes to the
corresponding outer catch block. If any error statement is in inner try block first go to
the inner catch block. If it is not the corresponding exception next goes to the outer
catch, which is also not corresponding exception then terminated.
Example:
class ntry
{
public static void main(String[] args)
{
try
{
int a=args.length;
int b=42/a;
System.out.println("a="+a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
int c[]={1};
c[42]=99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Exception:"+e);
}
}
Example:
class ntry1
{
public static void main(String[] args)
{
try
{
int a=args.length;
int b=42/a;
System.out.println("b="+b);
}
catch(ArithmeticException e)
{
System.out.println("Arithemetic exception:"+e);
}
finally
{
System.out.println("final block");
}
System.out.println("after try block");
}
}
throw statement
All previous exceptions are catching that are thrown by the java run time
system. It is also possible to create for a program that throws an exception explicitly,
using the “throw” statement. The general format of throw statement is:
Here,
throwable-instance must be an object type of Throwable class or subclass of
Throwable. There are two ways to obtain a Throwable object.
Example:
class t
{
public t()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("caught");
throw e; //rethrow the exception
}
}
}
class ntry2
{
public static void main(String[] args)
{
try
{
t obj=new t();
}
catch(NullPointerException e)
{
System.out.println("Recaught");
}
}
}
O/P: caught
Recaught
RAKESH.C.M Page 129
throws statement
Example:
class t
{
public t()throws NullPointerException
{
System.out.println("caught");
throw new NullPointerException("demo");
}
}
class ntry3
{
public static void main(String[] args)
{
try
{
t obj=new t();
}
catch(NullPointerException e)
{
System.out.println("Recaught");
}
}
}
O/P: caught
Recaught
Example:
class Test1
{
public static void main(String[] args)
{
try
{
int mark=Integer.parseInt(args[0]);
if(mark>100)
{
throw new own("Greater than 100");
}
catch(own e)
{
System.out.println("Exception caught");
System.out.println(e.getMessage());
}
finally
{
System.out.println("completed");
}
}
}
import java.util.*;
class StackEmptyException extends Exception
{
public StackEmptyException()
{
super();
}
public StackEmptyException(String s)
{
super(s);
}
}
class StackFullException extends Exception
{
public StackFullException()
{
super();
}
public StackFullException(String s)
{
super(s);
}
}
interface Stack1
{
public boolean isEmpty();
public int size();
public Object peek()throws StackEmptyException;
public Object pop()throws StackEmptyException;
public void push(Object x)throws StackFullException;
public String toString();
}
class ArrayStack implements Stack1
{
protected Object stk[];
protected int top;
public ArrayStack()
{
top=-1;
stk=new Object[10];
}
public ArrayStack(int cap)
{
if(cap<1)
throw new IllegalArgumentException("Initial capacity must be >1");
top=-1;
stk=new Object[cap];
}
class MArraystack
{
public static void main(String args[])
{
ArrayStack a=new ArrayStack();
Scanner s=new Scanner(System.in);
int ch,k,m;
switch(ch)
{
case 1: if(a.isEmpty())
System.out.println("Stack empty");
else
System.out.println("Stack is not empty");
break;
case 3: try
{
System.out.println("The top element in stack is"+a.peek());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
break;
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Stack elements:"+a);
break;
case 7: System.exit(0);
}
}
}
}
import java.util.*;
import java.io.*;
class StackEmptyException extends Exception
{
public StackEmptyException()
{
super();
}
public StackEmptyException(String s)
{
super(s);
}
}
class Infix
{
public static void main(String[] args) throws IOException
{
Intopost i=new Intopost();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter an infix expression");
String s=dis.readLine();
try
{
i.conversion(s);
}
catch(StackEmptyException e)
{
System.out.println(e);
}
catch(StackFullException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.util.*;
class PostEval
{
public void eval(String in)throws StackEmptyException,StackFullException
{
StringBuffer sb=new StringBuffer(new String(in));
sb.append(")");
StringTokenizer st=new StringTokenizer(new String(sb));
ArrayStack a=new ArrayStack(in.length());
String str;
int x,y,z=0;
char c;
while(!(str=st.nextToken()).equals(")"))
{
c=str.charAt(0);
if((c=='+')||(c=='-')||(c=='*')||(c=='/'))
{
x=(Integer)a.pop();
y=(Integer)a.pop();
switch(c)
{
case '+': z=y+x; break;
case '-' : z=y-x; break;
case '*': z=y*x; break;
case '/' : z=y/x; break;
}
a.push(z);
}
else
a.push(Integer.parseInt(str));
}
class Postfix
{
public static void main(String[] args)
{
PostEval p=new PostEval();
Scanner s=new Scanner(System.in);
System.out.println("Enter the postfix expression");
String str=s.nextLine();
try
{
p.eval(str);
}
catch(StackEmptyException e)
{
System.out.println(e);
}
catch(StackFullException e)
{
System.out.println(e);
}
}
}
a) Priority Scheduling:
P1 10 2
P2 01 4
P3 02 2
P4 01 1
P5 05 3
P2 P5 P1 P3 P4
0 1 6 16 18 19
The priority scheduling follows on Sun Solaris systems. But it doesn’t work
on the present operating systems like windows NT etc., The thread with a piece of
system code is called the thread scheduler. It determines which thread is running
actually in the CPU.
The Solaris java platform runs a thread of given priority to completion or until
a higher priority thread becomes ready at that point preemption occurs.
b) Round-Robin Scheduling:
P1 24
P2 10
P3 03
Time Quantum (or) Time Sliced : 04
P1 P2 P3 P1 P2 P1 P2 P1 P1 P1
0 4 8 11 15 19 23 25 29 33 37
Multiprocessing Multithreading
1. More than one process running simultaneously 1. More than one thread running
simultaneously
2. Its part of a program 2. Its part of a program
3. It’s a heavy wait process 3. It’s a light wait process
4. Process is divided into threads 4. Threads are divided into
sub threads
5. There is no communications between 5. Within the process threads are
processors directly communicated
1. Thread( )
2. Thread(String Threadname)
3. Thread(Runnable obj)
4. Thread(Runnable obj, String name)
5. Thread(ThreadGroup tg, String Threadname)
Methods
When a java program starts up, one thread begins running immediately. This
one is main thread, which is created by virtual machine. It is executed in the program
for the first time. It must be the last thread to finish execution. When the main
thread stops the program terminates.
Even though the main thread is automatically created when the program starts,
it can be controlled through Thread object. For this we obtain a reference to by
calling the method “currentThread( )”.
Example:
class demo
{
public static void main(String[] args)
{
Thread obj=Thread.currentThread();
System.out.println("current="+obj);
obj.setName("india");
System.out.println("after="+obj);
}
}
O/P: current=Thread[main,5,main]
after=Thread[india,5,main]
Example:
class demo
{
public static void main(String[] args)
{
Thread obj=Thread.currentThread();
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
obj.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("exception");
}
}
}
Example:
class new1 implements Runnable
{
Thread t;
public new1()
{
t=new Thread(this,"child thread");
System.out.println("sub thread="+t);
t.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("child="+n);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("child exception");
}
System.out.println("child exit");
}
}
class demo1
{
public static void main(String[] args)
{
new new1();
try
{
for(int n=5;n>0;n--)
{
System.out.println("main="+n);
Thread.sleep(1000);
}
}
2. extending the Thread class: The second way to create a thread is to create a new
class that extends Thread, and then create an instance of that class. The extending
class must override the run( ) method. It must also call start( ) to begin execution of
the new thread.
Example:
Example:
class demo3
{
public static void main(String[] args)
{
a obj=new a();
b obj1=new b();
c obj2=new c();
obj.start();
obj1.start();
obj2.start();
}
}
Example:
Example: Write a java program that creates three threads. First thread
displays"Good Morning" every one second , the second thread displays "Hello:
every two seconds and the third thread displays "Welcome" every three seconds.
import java.lang.*;
class Mythread1 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(1000);
System.out.println("Good Morning");
}
catch(Exception e){}
}
}
}
class Mythread2 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread Priorities
Every thread in Java is assigned a priority value, when more than one thread is
computing for CPU time. Generally highest priority thread is running before the
lowest priority thread. It is also possible to set priority to each thread by the user
using setPriority( ) method. System defined thread priorities are
Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread.NORM_PRIORITY 5
O/P: Thread-1 1
Thread-1 2
Thread-1 3
Thread-3 1
Thread-3 2
Thread-3 3
Thread-2 1
Thread-2 2
Thread-2 3
Synchronization
When two or more threads need access to a shared resource, they need
someway to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called Synchronization. Java uses the concept of
monitor (also called Semaphore) for Synchronization.
A monitor is an object that is used as a mutually exclusive lock, or mutex.
The monitor allows one thread at a time to execute a Synchronized method on the
object.
class Q
{
int n;
boolean valueset=false;
synchronized void get()
{
while(!valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("got"+n);
valueset=false;
notify();
}
synchronized void put(int n)
{
while(valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
this.n=n;
valueset=true;
System.out.println("put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;
class ITC
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("press ^- to exit");
}
}
***
EVENT HANDLING
Events
Event Sources
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one type
of event.
In java1.0 the action() method is used to perform any actions that are provided
with the controls. But the action() method is now deprecated. The new technique in
java1.1 and java2 is the Event Delegation Model.
This method defines a consistent mechanism to generate and process the
events. The process is: a source generates an event and sends it to one or more
listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns.
Event Listeners
Event Classes
Event classes are used to handle Java event handling mechanism. At the root
of the java event class hierarchy is EventObject , which is in java.util package. It is
the superclass for all events. It provides a constructor as:
EventObject(Object x)
MouseEvent Class:
The MouseEvent class defines eight types of mouse events. It defines the
following integer constants that can be used to identify them:
Hierarchy: java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event.ComponetEvent
java.awt.event.InputEvent
java.awt.event.MouseEvent
Methods:
1. int getX(): returns the X coordinate of the mouse when an event occurred
2. int getY():returns the Y coordinate of the mouse when an event occurred
3. Point getPoint(): returns the coordinates of the mouse
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
{
String msg=" ";
int x=0,y=0,w=0,h=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
KeyEvent Class:
A KeyEvent is generated when keyboard input occurs. There are three types
of key events, which are identified by these integer constants:
KEY_PRESSED
KEY_RELEASED
KEY_TYPED
The first two events are generated when any key is pressed or released. The last event
occurs when a character is generated.
Methods:
1. char getKeyChar(): returns the character that was entered
2. int getKeyCode(): returns the character code
Handling KeyEvents:
//Example program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Keydemo.class" width=400 height=350>
</Applet> */
// Example program
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Adapterdemo.class" width=400 height=350>
</Applet> */
INNERCLASSES
The most important type of nested class is the inner class. An inner
class is a non-static nested class. It has access to all of the variables and
methods of its outer class and may refer to them directly in the same way that
other non-static members of the outer class.
import java.applet.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.event.*;
The Abstract Window Toolkit (AWT) contains several classes which are
placed in the java.awt package. It is one of Java’s largest packages. The following
table shows a list of classes.
Class Description
Window Fundamentals
Component
Container
Window Panel
Frame
Frame: Frame is a subclass of Window and has a title bar, menu bar,
borders, and resizing corners.
Frame
Frame()
Frame(String title)
The first form creates a standard window that does not contain a title.
The second form creates a window with the title specified by title.
After a frame window has been created, it will not be visible until to call
setVisible().
When using a frame window, the program must remove that window from the
screen when it is closed, by calling setVisible(false).
import java.awt.*;
The AWT supports all of graphic methods. All graphics are drawn
relative to a window.This can be the main window of an applet,a child window
of an applet,or a stand-alone application window.The origin of each window is
at the top-left corner and is 0,0. Cooridinates are specified in pixels.All output
to a window takes place through a graphics context.A graphics context is
encapsulated by the Graphics class and is obtained in two ways:
1. Drawing Lines:
import java.awt.*;
import java.applet.*;
The drawRect() and fillRect() methods are used to draw and fill rectangles.
The methods are as:
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
import java.awt.*;
import java.applet.*;
To draw an ellipse, use drawOval(). To fill and ellipse, use fillOval(). These
methods are:
import java.awt.*;
import java.applet.*;
Example: Write a Java program that allows the user to draw lines,
rectangles and ovals.
import java.awt.*;
import java.applet.*;
void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
import java.awt.*;
import java.applet.*;
5. Drawing Polygons:
import java.awt.*;
import java.applet.*;
The first constructor takes three integers that specify the color as a mix of red,
green, and blue.
The second color constructor takes a single integer that contains a mix of red,
gree, and blue packed into the integer. The integer is organized with red in bits 16 to
23, green in bits 8 to 15, and blue in bits 0 to 7.
The third constructor takes three float values between 0.0 and 1.0 that specify
the relative mix of red, green, and blue.
These methods are used to obtain the red, green, and blue components
of a color independently.
int getRed()
int getGreen()
int getBlue()
b) getRGB():
int getRGB()
import java.awt.*;
import java.applet.*;
import java.awt.Color;
The AWT supports multiple type fonts. To select a new font, we construct a
Font object. It has a constructor as:
Methods:
Font class provides different methods. Some of the important methods are:
int getSize()
String getName()
int getStyle()
String getFamily()
boolean isBold()
boolean isItalic()
boolean isPlain() etc.,
import java.awt.*;
import java.applet.*;
import java.awt.Color;
Controls are components that allow a user to interact with our application in
various ways. A layout manager automatically positions components with in a
container. The appearance of window is determined by a combination of the controls
that it contains and the layout manger used to position them. The Layout managers
manage manual positions of placing the components.
The AWT supports the following types of controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text editing
Adding Controls: First created an instance of the desired control and then add it to a
window by calling add( ) method, which is defined by Container.
obj is an instance of the control that we want to add. It returns the object of
the control. Once, the control is added, it will automatically be visible whenever its
parent window is displayed.
Removing Controls: We want to remove a control from a window when the control
is no longer needed, call the method remove( ). This method is also defined by
Container.
To remove all the controls from the window used the following syntax as
Labels: Label is a text information that display on the GUI as a stirng. These are
passive controls that do not support any interaction with the user. Label defines the
following constructors:
Label( )
Label(String str)
Label(String str, int how)
Methods:
1. void setText(String str): To change the text specified by the str
argument
2. String getText( ): It returns the text from the label
3. void setAlignment(int how): To set the position of the label specified
by the how constant
4. int getAlignment( ): It returns the alignment
import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(250,450); One Two
setVisible(true);
setLayout(new FlowLayout());
Label L1=new Label("One");
Label L2=new Label("Two");
add(L1);
add(L2);
}
}
class Labeldemo
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}
Buttons: A push button is a component that contains a label and that generates an
event when it is pressed. Push buttons are objects of type Button. Button defines
these two constructors:
Button( )
Button(String str)
Handling Buttons:
Hierachy: java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event.ActionEvent
Methods:
Example: Develop an applet that receives an integer in one text field, and
computes its factorial value and returns it in another text field, when the button
named “Compute” is clicked.
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Lab6b" width=400 height=350> </Applet> */
if(e.getSource()==b1)
{
int x=Integer.parseInt(t1.getText());
int i,f=1;
for(i=1;i<=x;i++)
f=f*i;
t2.setText(" "+f);
}
repaint();
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Divide" width=300 height=300>
</applet>*/
public class Divide extends Applet implements ActionListener,TextListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
int x,y,res=0;
Button b1;
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cb)
The first form creates a check box with empty label and the state is unchecked
The second form creates a check box with the label str and the state is unchecked
The third form creates a check box with the label str and the state is checked () when
the boolean argument on is true
The fourth form creates a check box with the label str and the state is checked ()
when the boolean argument on is true whose group is specified by cb.
Methods:
import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
Checkbox c1=new Checkbox();
Checkbox c2=new Checkbox("DOS");
Checkbox c3=new Checkbox("Window",true);
add(c1);
add(c2);
add(c3);
}
}
Handling Checkboxes:
Hierarchy: java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event.ItemEvent
Methods:
Example: Write a java program that simulates a traffic light. The program
lets the user select one of the three lights , red,yellow, or green. When a radio
button is selected , the light is turned on, and only one light can be on at a time.
No light is on when the program starts.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Color;
import java.awt.*;
class Frame1 extends Frame
{
Checkbox c1,c2,c3;
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
CheckboxGroup cbg=new CheckboxGroup();
c1=new Checkbox("DOS",cbg,true);
c2=new Checkbox("Windows",cbg,false);
c3=new Checkbox("UNIX",cbg,false);
add(c1);
add(c2);
add(c3);
}
}
class Chgroup
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}
Handling CheckboxGroups:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class Checkboxdemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
CheckboxGroup cg;
public void init()
{
cg=new CheckboxGroup();
c1=new Checkbox("RED",cg,false);
c2=new Checkbox("GREEN",cg,false);
}
/* <applet code="Checkboxdemo.class" width=400 height=350></Applet>*/
Choice Control: The Choice class is used to create a pop-up list of items from
which the user may choose. A Choice control is a form of menu. Choice only defines
the default constructor, which defines an empty list.
Choice( )
Methods:
import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
Choice c=new Choice();
add(c);
c.add("Red");
c.add("Green");
c.add("Blue");
}
}
class Choicedemo
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}
Handling ChoiceLists:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
Lists: The List class provides a compact, multiple-choice, scrolling section list. The
list object can be constructed to show any number of choices in the visible window. It
can also be created to allow multiple selections. List provides these constructors.
List()
List(int nrows)
List(int nrows, boolean select)
The first form creates a List control that allows one item to be selected at any
one time.
In the second form, the value of nrows specifies the number of entries in the
list that will always visible.
In the third form, if select is true, then the user may select two or more items
at a time. If its is false, then only one item may be selected.
Here, name is the item that is added to the list. It adds the items at the end of
the list.
The second form adds the item at the index specified by the in argument.
Indexing starts at zero. Specify –1 to add the item to the end of the list.
Handling Lists:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Listdemo.class" width=400 height=350> </Applet> */
msg="Selected OS:";
int id[];
id=ch.getSelectedIndexes();
for(int i=0;i<id.length;i++)
msg=msg+ch.getItem(id[i])+ " ";
g.drawString(msg,50,100);
msg="Current:";
msg+=browser.getSelectedItem();
g.drawString(msg,50,150);
showStatus("List Action Performance");
}
}
Scroll Bars: Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or vertically. A
scroll bar is actually a composite of several individual parts. Each end has an arrow
that you can click to move the current value of the scroll bar one unit in the direction
of the arrow. The current value of the scroll bar relative to its minimum and
maximum values is indicated by the slider box for the scroll bar. The user can drag
the slider box to a new position. The scroll bar will then reflect this value.
Scrollbar defines the following constructors:
Scrollbar()
Scrollbar(int style)
Scrollbar(int style, int ivalue,int ssize, int min,int max)
Methods:
1. void setValues(int ivalue, int ssize, int min, int max): Used to set the parameters
2. int getValue(): returns the current setting value of the scrollbar
3. void setValue(int newvalue): Set with the newvalue
4. int getMinimum(): returns the minimum value of the scrollbar
5. int getMaximum(): return the maximum value of the scrollbar
Methods:
Handling TextFields:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Tdemo.class" width=400 height=350> </Applet> */
TextArea()
TextArea(int nlines, int nchars)
TextArea(String str)
TextArea(String str, int nlines, int nchars)
TextArea(String str, int nlines, int nchars, int sbars)
nlines specifies the height in lines, nchars specifies the width in charactes
str specifies the string filled with TextArea
sbars specifies the scroll bars that are associated with the TextArea. Sbars
must have one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORNIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
1. void append(String str): it appends the string specified by str to the end
of current text
// Example Program:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="TextAreademo.class" width=400 height=350> </Applet> */
LAYOUT MANAGERS
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates a default layout, with five pixels of space between each
component.
The second form specifies how each line is aligned. Valid values for how are
as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
The third constructor allows to specify the horizontal and vertical space
between components in horz and vert, respectively.
import java.awt.*;
import java.applet.*;
BorderLayout has four narrow, fixed-width components at the edges and one
large area in the center. The four sides are referred to as north, south, east and west.
The middle area is called the center. Constructors for BorderLaout is:
BorderLayout()
BorderLayout(int horz, int vert)
The first form creates a default border layout.
The second form allows to specify the horizontal and vertical space between
components in horz and vert, respectively.
When adding components, we use add( ) method, defined by Container.
void add(Component obj, Object region)
The region specified with the constants:
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.WEST
import java.awt.*;
import java.applet.*;
import java.util.*;
/* <applet code="Lay3" width=300 height=300>
</applet> */
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
4. CardLayout:
The CardLayout class is unique among the other layout managers in that it
stores several layouts. It provides constructors as:
CardLayout()
CardLayout(int horz, int vert)
import java.awt.*;
import java.applet.*;
import java.util.*;
5. GridBagLayout:
GridBagLayout()
import java.awt.*;
import java.applet.*;
import java.util.*;
***
APPLET
Applet Programs: Applet programs are small programs that are primarily used in
Internet programming. These programs are either developed in local systems or in
remote systems and are executed by either a java compatible “Web browser” or
“appletviewer”.
An applet developed locally and stored in a local system is known as a Local
Applet. When a Web page is trying to find a local applet, it does not need to use the
Internet and therefore the local system does not require the Internet connection. It
simply searches the directories in the local system and locates and loads the specified
applet.
An applet developed by someone else and stored on a remote computer is
known as Remote Applet. If our system is connected to the Internet, we download the
remote applet onto our system via the Internet and run it. In order to locate the remote
applet, we must know the applet’s address on the Web. This address is known as
Uniform Resource Locator (URL).
Every java applet inherits a set of default behaviors from the Applet class
defined in java.applet package. When an applet is loaded, it undergoes a series of
changes in its states. The important states of the Applet Life Cycle are:
Born or Initialization State
Running State
Idle State
Dead or Destroyed State
Running State: Applet enters the running state when the system calls the start()
method of Applet class. This occurs automatically after the applet is initialized.
Starting can also occurs if the applet is already in “Stopped State”. The start() method
may be called more than once.
Idle or Stopped State: An applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the currently
running applet. This can also done by calling the stop() method explicitly.
Dead State: An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when we quit the browser.
Destroying stage occurs only once in the applet life cycle.
Display State: Display state is useful to display the information on the output screen.
This happens immediately after the applet enters into the running state. The paint() is
called to accomplish this task. Almost every applet will have a paint() method.
start()
stop()
start()
destroy()
Destroyed
Dead
End
Exit of Browser
Note:
1. All the methods are automatically to called when any applet begin
execution.
2. The applet execution follows the above order.
3. In every applet it doesn’t need to place all the methods.
4. class hierarchy of the applet is
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Method 1:
import java.awt.*;
import java.applet.Applet;
public class Apdemo extends Applet
{
String msg=" ";
public void init()
{
msg=msg+"Init";
}
public void start()
{
msg=msg+"Start";
}
public void paint(Graphics g)
{
msg=msg+"Paint";
g.drawString(msg,50,100);
}
}
Method 2:
import java.awt.*;
import java.applet.Applet;
/* <applet code="Apdemo1.class" width=400 height=350>
</Applet> */
Save the file with Apdemo1.java compile and run the program as
C:> javac Apdemo1.java
C:> appletviewer Apdemo1.java
Status Window: Apart to display the information in its window, applet also produce
an applet status window of the browser on which it is running. It can be changed by
calling showStatus() method specified by passing the string as an argument.
repaint(): If the programmer needs to call the paint(), a call is made to the
Component class repaint() method. Method repaint request a call to the component
class update() method. As soon as possible to clear the components background of
any previous status then update calls paints directly. The repaint() method is
frequently called by the programmer to force paint() operation.
Syntax: public void repaint()
public void update(Graphics g)
import java.awt.*;
import java.applet.Applet;
/* <applet code="paramdemo.class" width=400 height=350>
<param name=first value=50>
<param name=second value=160>
</Applet> */
SWINGS
JApplet: Fundamental to Swing is the JApplet class, which extends Applet. JApplet
supports various “Panes” such as the content pane, the glass pane, and the root pane.
When adding a component to an instance of JApplet, call add() method of the
applet. Instead, we need to call add() on the content pane of the JApplet object. The
content pane can be obtained via the method:
Container getContentPane()
The add() method of the Container was then used to add a component to the content
pane.
Ex: Container c=getContentPane();
c.add(comp);
JFrame: JFrame extends the AWT class Frame. It contains additional features that
enable it to support Swing components.
JComponent: Jcomponent class extends the AWT Component and Container classes.
It is the top-level class for all swing components.
Icons: Icons are encapsulated by the ImageIcon class, which paints an icon from an
image. ImageIcon class provides a constructor as:
ImageIcon(String filename)
ImageIcon class implements the Icon interface and provides the methods as:
1. int getIconHeight(): returns the height of the icon in pixels
2. int getIconWidth(): returns the width of the icon in pixels
Swing labels are instances of the JLabel class, which extends Jcomponent. It
displays text and/or an icon. Constructors provided by the JLabel class are:
JLabel(Icon I)
JLabel(String S)
JLabel(String S, Icon I, int Align)
S and I are text and icon used for the label. Align argument is LEFT, RIGHT,
CENTER, LEADING or TRAILING
Methods:
1. Icon getIcon()
2. Sting getText()
3. void setIcon(Icon I)
4. void setText(String s)
// Example program
import javax.swing.*;
import java.awt.*;
/* <applet code="Jl.class" width=200 height=150>
</Applet> */
JTextField
JTextField()
JTextField(int col)
JTextField(String s, int col)
JTextField(String s)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
JButton
1. void setDisabledIcon(Icon d)
2. void setPressedIcon(Icon d)
3. void setSelectedIcon(Icon d)
4. void setRolloverIcon(Icon d)
5. String getText()
6. void setText(String s)
JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/* <applet code="JB.class" width=300 height=250>
</Applet> */
Check Boxes
JCheckBox(String str)
// DEMONSTRATE JCheckBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one
button can be selected at any one time. JRadioButton constructor is as:
JRadioButton(String str)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JComboBox
Swing provides a combo box through the JComboBox class. A combo box
normally displays one entry, but it will also display a drop-down list that allows a user
to select a diffeent entry. The JComboBox class constructor is:
JComboBox(Object [] items)
Here,
items is an array that initialize the combo box.
Methods:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JScrollPane
JScrollPane(Component comp)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JTabbedPane
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/* <applet code="JTab.class" width=300 height=250>
</Applet> */
Trees
A tree is a component that presents a hierarchical view of data. The user has
the ability to expand or collapse individual subtrees in this display. Trees are
implemented in Swing by JTree class. Constructors are:
In the first form, the tree is constructed from the elements in the array obj.
In the second form, the tree form the elements of vector v.
In the third form, the tree whose root nodej is specified by tn specifies the tree.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
jt=new JTree(top);
JTable
JTable is a component that displays rows and columns of data. We can drag
the cursor position on column boundaries to resize columns. Constructor used for
JTable class is:
JTable(Object data[][], Object col[[])
Here,
data is a two-dimensional array of the information to be presented.
col is a one-dimensional array with the colum headings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Example: Suppose that a table named Table.txt is stored in a text file. The
first line in the file is the header, and the remaining lines correspond to rows in
the table. The elements are operated by commas. Write a java program to
display the table using JTable component.
import java.awt.*;
import java.applet.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
***
NETWORKING
Network: More than one computer systems are connected to sent and receive the
information with each other is considered as a Network. Due to the networking there
is a communication between the systems. So, that they are shared data as well as
resources.
Socket Overview: Networks sockets are used for networking the systems. A
Network Socket is like an electrical socket at which various plugs around the network
has a standard way of delivering their payload. For transmission the data, the sockets
are used some protocols.
“Protocol” is a standard set of rules, which is used to transfer the data from
one system to another. Protocols ae classified into two types as:
Internet Protocol (IP) is a low-level routing protocol that breaks data into small
packets and sends them to an address across the network. It is not guarantee to
deliver the packets to destination.
Client/Server: A Server is anything that has some resource that can be shared. It is
permanently available resource. Different types of servers are
Compute servers : which provides computing server
Print Servers : which manages a collection of printers
Disk Servers : which provides a networked disk space
Web servers : which store web pages
RAKESH.C.M Page 218
A Client is an entity that wants to gain access to a particular server.
TCP/IP reserves the lower 1024 ports for specific protocols. Some of the
reserved protocols are:
21 - FTP
23 - Telnet
25 - e-mail
43 - whois
79 - finger
80 - HTTP
119 - netnews
Java supports TCP/IP both by extending the already establish stream I/O
interfaces and by adding the features required to build I/O objects across the network.
Java supports both the TCP and UDP protocols families. TCP is used for reliable
stream-based I/O across the network. UDP supports a faster, point-to-point datagram-
oriented model.
All the network classes are supported by java.net package. Some of the
classes are
InetAddress, DatagramPacket, DaragramSocket etc.,
InetAddress Class: When we form a connection across the Internet, addresses are the
fundamental notations. InetAddress is a class that is used to encapsulate both the
numerical IPAddress and domain name for that address.
import java.net.*;
class netdemo
{
public static void main(String[] args) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
System.out.println("IPAddress:"+ia);
}
}
//O/P: IPAddress:pbrvits210/192.168.1.210
Instance Methods: The InetAddress class also has several other methods, which
can be used on the objects returned by the methods.
1. boolean equals(Object oth): returns true if this object has the same
internet address as other
2. byte[] getAddress(): returns a byte array that represents the object’s
Internet address in network byte order
3. String getHostAddress(): returns a string that represents the host
address associated with the InetAddress object
4. String getHostName(): returns a string that represents the host name
associated with the InetAddress object
5. String toString(): returns a string that lists the host name and the IP
address for convenience
import java.net.*;
class netdemo1
{
public static void main(String[] args) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
String str=ia.getHostName();
System.out.println("Host Name :"+str);
}
}
TCP/IP SOCKETS
Socket: The Socket class is designed to connect to server sockets and initiate
protocol exchanges. The creation of socket object implicitly establishes a connection
between the client and server. Two constructors to create client sockets are:
Socket(String hostname, int port): Creates a socket, connecting the
local host to the name host and port; can throw an UnknownHostException or an
IOException
Socket(InetAddress ia, int port): Creates a socket using a preexisting
Inetaddress object and a port; can throw an IOException.
Methods:
Once the Socket object has been created, it is possible to access the input and output
streams associated with it. For this the following methods are use. They are:
ServerSocket: The ServerSocket class is used to create servers that listen for either
local or remote client programs to connect to them on published ports. When we
create a ServerSocket, it will register itself with the system as having an interest in
client connections. The constructors for ServerSocket reflect the port number that
we wish to accept connections. Constructors provided by the ServerSocket class are:
import java.net.*;
import java.io.*;
import java.util.*;
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(8080);
Socket s=ss.accept();
Scanner c=new Scanner(s.getInputStream());
double r=c.nextDouble();
double a=Math.PI*r*r;
PrintStream p=new PrintStream(s.getOutputStream());
p.println(a);
s.close();
p.close();
}
}
Address Identifiers
When the data is required to transmit or received over the network, first the
server is required to identify the address of the client. More clients have common
system names, but addresses are different. Two types of classes called URI
(Uniform Resource Identifier) and URL (Uniform Resource Locator) identify system
unique addresses.
URL:
first component is the protocol, rest of the locator are separated by colon.
Commonly used protocols are http, ftp, gopher and file etc.,
second component is the hostname or IPAddress of the host, this delimited on
the left by double slashes (//)
third component is the port number, default port number of http protocol is 80
fourth component is the file path
// Example program
import java.net.*;
class url
{
public static void main(String[] args) throws Exception
{
URL obj=new URL("http://www.google.co.in/download");
System.out.println(obj.getProtocol());
System.out.println(obj.getHost());
System.out.println(obj.getFile());
System.out.println(obj.getPort());
System.out.println(obj.toExternalForm());
}
}
//O/P: http
www.google.co.in
/download
-1
http://www.google.co.in/download
URLConnection:
import java.net.*;
import java.util.Date;
class urlconnection
{
public static void main(String[] args) throws Exception
{
URL obj=new URL("http://www.google.co.in/download");
URLConnection uc=obj.openConnection();
System.out.println("Type:"+uc.getContentLength());
long d=uc.getDate();
if(d==0)
System.out.println("Not available");
else
System.out.println("Time:"+new Date(d));
}
}
DATAGRAMS
Methods:
1. void send(DatagramPacket pc) throws IOException
2. void receive(DatagramPacket pc) throws IOException
The first constructor specifies a buffer that will receive data, and the size of the packet
The second form allows to specify an offset into the buffer at which data will be
stored
The third form specifies a target address and port to which packets of data will be sent
The fourth form transmits packets beginning at the specified offset into the data
Methods:
UDP CLIENT
import java.net.*;
import java.io.*;
import java.util.*;
class udpclient
{
public static void main(String args[])
{
try
{
DatagramPacket dp;
String strline,text;
InetAddress ia=InetAddress.getLocalHost();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the string:");
strline=dis.readLine();
byte[] data=new byte[strline.length()];
strline.getBytes(0,strline.length(),data,0);
dp=new DatagramPacket(data,data.length,ia,100);
DatagramSocket ds=new DatagramSocket(101);
ds.send(dp);
System.out.println("data sent");
UDP SERVER
import java.net.*;
import java.io.*;
class udpserver
{
public static byte[] msg=new byte[1024];
public static void main(String args[])
{
String str;
try
{
InetAddress ia=InetAddress.getLocalHost();
DatagramPacket dp=new DatagramPacket(msg,msg.length);
DatagramSocket ds=new DatagramSocket(100);
ds.receive(dp);
str=new String(dp.getData(),0,0,dp.getLength());
System.out.println(str);
byte[] data=new byte[str.length()];
str.getBytes(0,str.length(),data,0);
dp=new DatagramPacket(data,data.length,ia,101);
ds.send(dp);
}
catch(SocketException e)
{
System.out.println(e);
}
ENUMERATIONS
Ap is of the Apple. So, that Ap values can be assigned only with those are
defined by the enumeration.
Ex: Ap = Apple.RedDel;
Note:
enum Days
{
MON, TUE, WED, THU, FRI, SAT, SUN;
}
class EnumDemo
{
public static void main(String[] args)
{
Days d;
d=Days.WED;
System.out.println("Value of d="+d);
d=Days.FRI;
if(d==Days.FRI)
System.out.println("EQUAL");
switch(d)
{
case MON:System.out.println("DAY 1");
break;
case TUE:System.out.println("DAY 2");
break;
case WED:System.out.println("DAY 3");
break;
case THU:System.out.println("DAY 4");
break;
case FRI:System.out.println("DAY 5");
break;
case SAT:System.out.println("DAY 6");
break;
case SUN:System.out.println("DAY 7");
break;
}
}
}
Autoboxing
Auto-unboxing
class AutoBox
{
public static void main(String args[])
{
Integer x = 100; // autobox an int
int i = x; // auto-unbox
System.out.println(x+” “+i);
}
}
// Example
class AutoBox2
{
static int m(Integer v)
{
return v; // auto-unbox to int
}
public static void main(String[] args)
{
Integer iob=m(100); // autobox into Integer
System.out.println(" "+iob);
}
}
GENERICS
class Two<T,V>
{
T ob1;
V ob2;
Two(T x,V y)
{
ob1=x;
ob2=y;
}
t.showTypes();
int p=t.getob1();
System.out.println("Value 1:"+p);
String q=t.getob2();
System.out.println("Value 2:"+q);
}
}
// O/P:
class MethDemo
{
static <T,V extends T>boolean isIn(T x,V[] y)
{
for(int i=0;i<y.length;i++)
if(x.equals(y[i]))
return true;
return false;
}
public static void main(String[] args)
{
Integer nums[]={1,2,3};
if(isIn(2,nums))
System.out.println("EXIST");
class GenDemo
{
private double val;
<T extends Number>GenDemo(T arg)
{
val=arg.doubleValue();
}
void showVal()
{
System.out.println("Value:"+val);
}
}
class GenCons
{
public static void main(String[] args)
{
GenDemo gd1=new GenDemo(100);
GenDemo gd2=new GenDemo(123.5F);
gd1.showVal();
gd2.showVal();
}
}
THE END