Java Notes
Java Notes
UNIT I
Abstraction:-
a) Encapsulation – The mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse. In Java
the basis of encapsulation is the class.
b) Inheritance – The process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical
classification.
c) Polymorphism – The feature that allows one interface to be used for a general
class of actions. The specific action is determined by the exact nature of the
situation. The concept of polymorphism is often expressed by the phrase “one
interface, multiple methods”.
History of JAVA
Java is a general-purpose, concurrent, class-based, object-oriented computer programming
language developed by the Sun Microsystems.
Earlier, C++ was widely used to write object oriented programming languages; however, it was
not a platform independent and needed to be recompiled for each different processor.
Whereas Java applications are typically compiled to byte code (.class file) that can run on any
platform (OS + Processor).
It is intended to let application developers "write once, run anywhere" (WORA), meaning that
code that runs on one platform does not need to be recompiled to run on another.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
The language was initially called Oak after an oak tree that stood outside Gosling's office.
JAVA PROGRAMMING
It went by the name Green later, and was later renamed Java, from Java coffee, said to be
consumed in large quantities by the Java language's creators.
JAVA Versions
Major release versions of Java, along with their release dates:
JDK 1.0 (January 21, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)
JAVA Editions
FEATURES OF JAVA:
Java features are
Simple
Secure
Portable
Object Oriented
Robust
Multithreaded
Architectural Neutral
JAVA PROGRAMMING
Interpreted
High Performance
Distributed
Dynamic
Simple:
Java was designed to be easy for the professional programmer to learn and use
effectively. Programmer to learn and use effectively.
Secure:
Java provided a firewall between a network application and your computer. Java achieves
the protection by confusing a java program to the java execution environment.
Portable:
It can be move from one OS to another OS. Java solution to these two problem is both
elegant and efficient.
Object Oriented:
The object model in java is simple and easy to extend.
Robust:
The multiplatform environment of the web places extraordinary demands on a program,
because the programs must execute reliably in a variety of system. Ability to create robust
program was given high priority is the design of java.
Multithreaded:
Java was designed to meet the real world requirement of creating interactive network
programs. Java support multithreaded programming which allows you to write program to do
many things simultaneously.
Architecture neutral:
A central issue for the java designer was that of code longevity and portability. In java,
we can the write the program once, we can run anywhere, anytime and forever in this java virtual
machine is used to overcome this situation.
Interpreted and high performance:
Java enables the creation of cross-platform program by compiling into an intermediate
representation `called JAVA BYTE CODE. This code can be interpreted on any system that
provides a JVM.
Distributed:
Java is designed for the distributed environment of the internet because it handles TCP/IP
protocol. Accessing a resource using a URL is not much different from accessing a file. Original
version of java included features for intra address spacing message.
It allowed object on two different computers to execute procedures remotely. Java
revived these interfaces is a package called REMOTE METHOD INVOCATION (RMI). Its
feature bring an unparallel level of abstraction to client/server programming.
Dynamic:
Java programs carry with them substantial amount of run time type information. It is used
to resolve accesses to object at runtime. It is possible to dynamically link code in a safe manner.
machine code.
system and converts the byte code instructions in an understandable format for the
particular processor and operating system.
a. Documentation section: A set of comment lines like: name of the program, author name, date
of creation, etc.
b. Package statement: This is the first statement allowed in Java file, this statement declares a
package names.
c. Import statement: This statement imports the packages that the classes and methods of
articular package can be used in the current program.
d. Interface statement: An interface is like a class but includes group of methods declaration.
Inter face is used to implement the multiple inheritance in the program.
e. Class definition/statements: A Java program may contains one more class definitions.
f. Main method class: Every Java standalone program requires a main method, as it begins
the execution, this is essential part of Java program
{
public static void main (String args[])
{
System.out.println (“welcome to Java Program”);
}
}
public: It is access specifier and this method can be called from outside also.
static: This main method must always declared as static because the whole program has only one
main method and without using object the main method can be executed by using the class name.
void: The main method does not return anything.
main: - The main method similar to main function in c and c++. This main method call first
(execute first) by the interpreter to run the java program.
String: It is built-in class under language package.
args []: This is an array of type string. a command line arguments holds the argument in this
array.
System.out.println:
System: It is a class which contains several useful methods.
out: It is an object for a system class to execute the method.
println: This is a method to print string which can be given within the double coats. After
printed the contents the cursor should be positioned at beginning of next line
print: after printed the content the cursor should be positioned next to the printed content
\Program Files\Java\jdk1.6\bin>
javac is used to compile the source code
C:\program Files\java\jdk1.6\bin>java Welcom.java
It successfully compiled with no-errors, Java compiler converts source code [welcome.java] to
byte code [welcome. class] into particular machine instruction to run java program
\folder path
\>set path=c:\program files\java\jdk1.6\bin
\>javac Welcome.java
JAVA TOKENS:
Tokens are the basic building-blocks of the java language.
There exist 6 types of tokens in JAVA.
1. Keywords
2. Identifier
3. Literals
4. Separators
JAVA PROGRAMMING
5. Operators
6. Comments
1) Keywords: The Java programming language has total of 50 reserved keywords which have
special meaning for the compiler and cannot be used as variable names. Following is a list of
Java keywords in alphabetical order, click on an individual keyword to see its description and
usage example.
2) Identifier: Identifier is case sensitive names given to variable, methods, class, object,
packages etc
Rules for identifiers:
1) May consists of letters, digits, underscore and a dollar symbol.
2) Must begin with a letter (A to Z or a to z), dollar ($) or an underscore (_).
3) A key word cannot be used as an identifier.
4) They are case sensitive.
5) Whitespaces are not allowed.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
4)Separators: They are character used to group and arrange Java source code into segments.
Java uses 6 types of separators:
Comments:
A comment is a non executable portion of a program that is used to document the program.
There are 3 types of comments in java:
1) Single line comment: //
2) Multiline comment: /* */
3) Documentation comment: /** */
Data types:
Java is strongly typed language. Data type specifies the type of value that can be stored in a
variable.
JAVA PROGRAMMING
OPERATORS IN JAVA.
An OPERATOR is a symbol which represents some operation that can be performed on
data. There are eight operators available in java to carry out the operations. They are
Arithmetic operators
Relational operators
Logical operators
Short hand assignment operators
Increment and Decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic operators :
Arithmetic operators are used to do arithmetic calculations. There are two types
- Binary operators => They need two operands for operations. They are +,-,*,%, /
- Unary operators => They need only one operand for operation. They are ++, - -, -
Relational operators:
Relational operators are used to find out the relationship between two operands. They are
>,<,>=,<=,++,!=
Logical operators:
Logical operators are used to find out the relationship between two or more relational
expressions. They are &&,||,!
Conditional operators:-
JAVA PROGRAMMING
The conditional operators? and : are used to build simple conditional expression. It has
three operands. So it is called ternary operator. The general form is
Bitwise operators:-
It is used to do bit by bit operation. It perform bitwise AND, OR, XOR, Shift left, Shift
Right, NOT such operators are &,|,^,>>,<<,~.
Special operators:-
There are two important special operators. They are i) instanceof operator ii) dot operator ()
Instanceof operator is used to find out whether the given object belongs to a particular
class or not. The general form is
Objectname instanceof classname
Dot operator(.) is used to access the variables and methods of class objects. The general
form is objectname.variable (or) method
Example:
Ramu.group;
Ramu.add()
Control Statements
The control statements are used to control the flow of execution of the program.
Java contains the following types of control statements:
1) Selection Statements / Decision making statements: if, if-else, switch.
2) Repetition Statements / Looping Statements: while, do-while, for.
3) Branching Statements / Jumping Statements: break, continue, and return.
}
if-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if'
statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional expression){
<statements>;
}
else{
<statements>;
}
Ex: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not
equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number");
}
switch Statement:
The keyword "switch" is followed by an expression that should evaluates to byte, short, char or
int primitive data types ,only. In a switch block there can be one or more labeled cases. The
switch expression is matched with each case label. Only the matched case is executed, if no case
matches then the default statement (if present) is executed.
Syntax:
switch(expression){
case expression 1:<statement>;break;
case expression 2:<statement>;break;
...
case expression n: <statement>;break;
default:<statement>;
}//end switch
Ex: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled
"5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday");break;
case 4: System.out.println("Thrusday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday");break;
case 7: System.out.println("Sunday");break;
default: System.out.println("Invalid entry");
}
JAVA PROGRAMMING
For loop:-
For statement is used to execute a statement or group of statements repeatedly for a
known number of times.
The general form is
BRANCHING STATEMENTS:
1)Break statements:
The break statement is used for breaking the execution of a loop (while, do-while and for). It also
terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Ex: When if statement evaluates to true it prints "data is found" and comes out of the loop and
executes the statements just following the loop
JAVA PROGRAMMING
2)Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to
skip the current iteration of the loop and resume the next iteration .
Syntax: continue;
Ex:
return statements:
It is a special branching statement that transfers the control to the caller of the method. This
statement is used to return a value to the caller method and terminates execution of method.
Syntax: return;
return values;
return; //This returns nothing. So this can be used when method is declared with void return
type.
3)Return expression; //It returns the value evaluated from the expression.
Ex: Here Welcome () function is called within println() function which returns a String value
"Welcome to roseIndia.net". This is printed to the screen.
JAVA PROGRAMMING
}
}
CLASSES AND OBJECTS:
Class:
A class is a user defined data type. It contains data and its related methods.
The general form is
class classname
{
Datatype field1; // variable declaration
……….
Datatype field n;
Objects:
Objects are treated from the defined class
Using class we can create any number of objects
All created objects can use the instance variable
Memory space for the instance variable will be allocated only during object creation
Objects in java are created using the new operator
The new operator create an object for specified class and return a reference to that object
Array of Objects:
We can create more than one object for a class can be defined by a single name. this is
called ARRAY OF OBJECTS.
Syntax: classname object[ ] = new classname[size];
Example: Student s[ ]= new Student[5];
Example Program:-
Class student
{
int regno,total; // variable declaration
void readdata(int rn,int tot) // method declaration
{
regno = rn;
total=tot;
}
void display() // method declaration
{
System.out.println(“REGISTER NO.=”+regno);
System.out.println(“TOTAL=”+total);
}
}
Class college
{
Public static void main(String args[])
{
Student s = new Student(); // object creation
s.readdata(101,459); // calling function
s.display();
}
}
OUTPUT:
REGISTER NO.=101
TOTAL=459
In this above program Student is a class and s is object. Student class has two variables
such as regno, total and methods are readdata() and display(). Using objects we call class
member function.
When you save the file name as college.java. Compile and execute the java program then
output is display as 101 and 459.
JAVA PROGRAMMING
STATIC MEMBERS.
The members of the classes can be defined as static by adding the keyword static in front
of the members. The static can be declared as
i) member variable or Field
ii) member function or methods
Static members can be accessed without using object. Static variable behave like global
variables and can be accessed by all created object. Static method can be called from outside the
class using the class name.
{ }
Example:
Class demo
{
Static int age = 39;
Static void display()
{
System.out.println(“Age=”+age);
}
Public static void main(String args[])
{
Display();
}
}
Output: Age=39
Final methods:-
FINAL is a modifier used to prevent variables and methods from overriding. Final
keyword is added in front of any variable or method this cannot be overrided in the subclasses.
The value cannot be changed.
JAVA PROGRAMMING
Class first
{
Final int a;
Final void display()
{
System.out.println(“Welcome to RAAK College”);
}
}
Class second extends first
{
Int a;
Void display()
{
System.out.println(“Welcome To RAAK Institutions”);
}
}
Abstract methods:-
Abstract methods must be override in the subclass. It must be declared in super
class and it has no body definition. This make compulsory to override the abstract method in
subclass. By using the keyword abstract.
Syntax: abstract returntype methodname()
Example: abstract int area()
b=y;
}
Void print(String msg)
{
System.out.println(msg);
}
System.out.println(“b=”+b);
}
}
Class overdemo
{
Public static void main(String args[])
{
Second s = new second(10,20);
s.print(“The given number is”);
s.print();
}
}
Output: The given number is 20
In the above example program the super class print() function is hidden and the sub class
function is activate the print() function by using Overriding methods. Thus the output is 20.
Constructors:
They are used to initialize the object, constructor having the same name as the class name and
executes automatically when the object is created.
Ex: class XYZ
{
int x;
XYZ() //constructor
{
x=10;
}
}
Types of constructor :
Constructors are three types:
1. Default constructor (Non-parameterized constructor)
2. Parameterized constructor
3. Constructor overloading
1. Default constructor:-
Default constructor having no parameters & Executed automatically when the object is created.
If we doesn’t give the default constructor in the class, java automatically provides default
constructors that initializes the variables as ‘0’ or ‘NULL’.
Ex: class XYZ
{
JAVA PROGRAMMING
int a,b;
XYZ() //default constructor or non-parameterised constructor
{
a=10;
b=20;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ();
}
}
2. Parameterized constructor :-
The constructor having one or more parameters that is used to initialize the variable is called
parameterized constructor.
Ex: class XYZ
{
int a,b;
XYZ(int x, int y) //parameterised constructor
{
a=x;
b=y;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ(10,20);
}
}
3. Overloaded constructor:
Two or more constructors having different parameters is called overloaded constructor.
Ex:
class XYZ
{
int a,b,c;
XYZ()
{
a=1;
b=2;
c=3;
}
JAVA PROGRAMMING
XYZ(int x, int y)
{
a=x;
b=y;
c=20;
}
XYZ(int x, int y, int z)
{
a=x;
b=y;
c=z;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj1=new XYZ();
XYZ obj2=new XYZ(10,20);
XYZ obj3=new XYZ(10,20,30);
}
}
Method overloading:
Method names are same but parameters are different is called as method overloading.
Ex: class Ex
{
void add()
{
…………..
}
void add(int x,int y)
{
……………
}
void add(int x,int y,int z)
{
……………
}
}
Note: method overloading is one of the way to implement polymorphism in Java.
‘this’ Keyword
"this keyword refers to the current object”. It always points object that is currently executing.
Ex: class Xyz
{
JAVA PROGRAMMING
int x,y;
{
this.x=a;
this.y=b;
}
void display()
{
System.out.println(“X=”+x);
System.out.println(“Y=”+y);
}
}
public class Ex
{
public static void main(String args[])
{
Xyz obj1=new Xyz(10,20);
Xyz obj2=new Xyz(100,200);
obj1.display();
obj2.display();
}
}
UNIT III
Arrays
“An array is a collection of elements of the same data type”.
One-dimensional array:
Declaration: In JAVA an array declaration is a two step process:
First,you should declare a variable by specifying its datatype
Syntax: datatype[] variable_name;
Second,you should allocate the memory for an array using new and assign it to the array
variable
Syntax: variable_name =new datatype[size];
The elements in the array allocated by new will automatically be initialized to zero.
Ex: 1) int a[];
2)a=new int[10];
The two steps can be combined into a single line as:
int a[]=new int[10];
Ex 1:
class ArrayDemo
{
public static void main(String args[])
{
JAVA PROGRAMMING
Strings
A combination or collection of characters is called as string.
The strings are objects in java of the class ‘String’.
System.out.println(“Welcome to java”);
The string “welcome to java” is automatically converted into a string object by java.
A string in java is not a character array and it is not terminated with “NULL”.
String are declared and created:-
Using character strings
String str1=new String(“vvfgc”);
String str2=new String(str1);
String str3=”Tumkur”
We can also create string object by assigning value directly.
String object also create by using either new operator or enclosing of characters in double
codes.
Java string can be con-catenation using the plus operator (+).
String name1=”vvfgc”;
String name2=”college”;
String str1=name1+name2;
String str2=”Narasimha”+”murthy”;
String str3=name1+”murthy”;
String str4=”Narasimha”+name2;
Methods of string classes :-
1. Length:
public int length();
It will give the length of a string.
Ex: String str=”murthy”
int n=str.length();
Here the length function returns the value seven.
System.out.prntln(str.length)//it is also returns the value 7
2. concat:
public String concat(String str);
JAVA PROGRAMMING
This method is also replace the old string to the new string.
String str1=”JAVA”
String str2=str1.replace(‘JAVA’, ‘KAVA’);
8. charAt:-syntax: public String charAt(int index);
This method returns a single character located at the specified index position with a string
object.
Ex: String str1=”JAVA”
Char c=str1.charAt(2); //output V
9. subString:-syntax: public String substring(int begin);
JAVA PROGRAMMING
This method returns a string which is derived from the main string with the mentioned
position.
This will returns the substring from the specified begin to end of the string.
Ex: String str1=”welcome to java programing”
String str2=str1.SubString(3);//output: come to java programing
Syntax2: String SubString(int begin, int end);
This will returns the specified begin to the specified end
Ex: String str1=”welcome t_o java programing”
String str2=str1.SubString(3,10);//output: come t_
10. trim:-syntax: public String trim();
This method is used to remove the beginning and ending of the wide space in a given string.
Ex: String str1=” JAVA PROGRAMING ”
String str2=str1.trim();
Write a program to perform all the string operation
import java.lang.String;
import java.lang.*;
public class lab7
{
public static void main(String args[])
{
String s1="java";
String s2="PROGRAM ing";
String s3;
System.out.println("string1 length="+s1.length());
System.out.println("string1 length="+s2.length());
System.out.println("strings Concatination="+s1.concat(s2));
if (s1.equals (s2))
}
}
String Buffer class
It creates string of flexible length that can be modifying in terms of both length and content.
Stringbuffer class object as the rights to access all the methods of string classes but the object of
string class has no rights to access the methods of string buffer class.
String buffer created as:
StringBuffer sb=new StringBuffer(“murthy”)
JAVA PROGRAMMING
s2.setcharAt(0,’k’);//kava
5.reverse(): This method is used to reverse the character with in an object of the string
buffer class.
Syntax: s1.reverse();
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
s1.reverse();
Write a program to perform all the string buffer method
public class Ex
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“college”);
System.out.println(“String str1=”+s1);
System.out.println(“String str2=”+s2);
System.out.println(“Append=”+s1.append(s2));
System.out.println(“Insertd string=”+ S1.insert(3,s2));
System.out.println(“Set length of string2=”+ S2.setLength(3));
System.out.println(“Character at string s2=”+ S2.SetcharAt(3,m));
System.out.println(“revers string s2=”+ s2.reverse());
}
}
Vector:
“A vector is a class that provides the capability to implement a growable array of object”.
Vector class is constructed under the java.util.package.
Vectors are array list with extended properties which follow the dynamic and automatic addition
of data at runtime.
Vector can be created as:
1. Vector v = new Vector();
JAVA PROGRAMMING
This constructor creates a default vector containing no elements. The default capacity(size) is 10.
2. Vector v = new Vector(20);
This constructor creates the initial capacity of 20.
3. Vector v = new Vector(20,5);
This vector has a initial capacity of 20 and will grow in increment of 5 elements.
Methods of vector class:-
add():
void add(int);
void add(int pos, int ele);
This method inserts the elements into the vector.
capacity():
int capacity();
It returns the current capacity of this vector.
remove():
remove(int pos);
It removes the element at specified position in this vector.
size():
int size();
It returns the no. of elements in this vector.
clear():
void clear();
It removes all the elements from this vector.
Ex:
public class Ex
{
public static void main(String args[])
{
Vector v = new Vector();
for(int i=1;i<=10;i++)
v.add(i);
v.add(4,100);
System.out.println(“vector elements : “+v);
v.remove(3);
}
}
Wrapper classes:
“Wrapper classes are used to represent primitive values when all object is required, the wrapper
class encapsulate a single value for the primitive data type”.
Before we can instantiate a wrapper class, we need to know it’s name and arguments it’s
constructor accepts. The name of the wrapper class corresponding to each primitive data type
along with the args it’s constructor accepts.
Primitive data type wrapper class constructor args.
Java class not support multiple inheritance (two or more base class derives one derived class)
(Class D extends A, B, C is invalid)
(Class D extends, extends A, extends B, extends C is invalid)
For the above disadvantages java implements new concepts call it as interface.
“An interface is an alternate approach to support the concepts of multiple inheritance and
contains final variable & abstract methods”.
Syntax:
interface <interface_name>
{
final fields
abstract methods
}
JAVA PROGRAMMING
All the methods in an interface are an implicitly extract and public variable declared implicitly
Final.Interface is defined just like a class. INTERFACE contains abstract method and final
instance variable.
Creating Interface:-
Syntax:
interface interfacename
--------------------------
Returntype method1(parameterlist1
Returntype method2(parameterlist2)
Extending Interface:-
Deriving new interface from the existing interface is called EXTENDING INTERFACE.
Using the keyword extends.
Length = l;
Breadth = b;
}
Void area()
{
Area1= length * breadth;
}
Void print()
{
System.out.println(“The area of rectangle is :”+area);
}
}
Class example
{
Public static void main(String args[])
{
Rectangle r = new rectangle (5.7,12.7);
r.area();
r.print();
}
}
Implementing Interface:-
JAVA PROGRAMMING
Implementing is a process of using the already defined interface in a class. All the
variable and methods inherits from the interface to class. Any number of interfaces can be
implemented in a class separated by comma(,).
Example Program:-
Import java.io.*;
Interface demo // creating interface demo
{
void area();
void printf();
}
JAVA PROGRAMMING
PACKAGES
Packages are container for classes. It is like a header file in C++ and it is stored in a
hierarchical manner.
JAVA PROGRAMMING
Types of packages:
Java packages are classified into two catagerious
java API packages.
user defined packages (built in packages).
Java API packages contain the built in class provided by the java. Packages are organised in a
hierarchical structure. A packages name should be unique for class & interfaces.
Crating a package:-
Java has a facility to create our own package. Create a sub directory with the same name
of the package. This gives one package. We can also create another package within this director.
Defining a package:-
Each package contains number of related classes. We access this class in our application.
There are two methods to access a package
JAVA PROGRAMMING
We can access a package by specifying the classpath at time of declaration of our object.
Example: bb.aa.sample.obj;
Let a class sample belong to a package “aa”, this package is inside another package “b”.
If we want to use the class sample in our application. We have to do the declaration.
By using statement we can either use all classes of a package in our application or a
specific class.
This statement allows us to use the sample class of package as in our application.
Syntax: -
import package_name.*;
Or
import package_name.class_name;
Or
import pack1.pack2.pack3.pack4.*;
Or
import pack1.pack2.pack3.pack4.class_name:
Here pack1 is the name of the top level package,
pack2 is the name of next level package,
pack3 is the name of the next level of package. So on
The statement must terminate with a (;) semicouln
The import java.io.*; appear before class definition in program.
Ex:
package pack1;
import java.io.*;
public class EX
{
public void display ()
{
System.out.println (“this is a pack1.package”);
}
}
Save the file in pack1 folder as Ex.java
Compile Ex.java file successfully then it will creates EX. class file
Ex: - import pack1.EX;
import java.io.*;
public class xyz
{
public static void main (Strings args[])
{
Ex obj=new Ex();
obj.display
}
}
Save this file as xyz.java in outside the pack1 folder & executes this file
C:\>d:
D:\>cd pack1
D:\>pack1>set path=c:\programfiles\java\jdk1.6\bin
D:\pack1>javac Ex.java
D:\pack1>cd….
JAVA PROGRAMMING
D:\>javac xyz.java
D:\>java xyz
This is pack1 package
Multithreaded Programming
*A multithreaded program contains two or more tasks can run simultaneously.
*Performing two or more task at same time is known as multi tasking
Two type of multi-tasking
Process based multitasking (PBM):-
Two or more program (processes) can run simultaneously is called PBM
Ex: - Running VLC, Scanning for virus, working with internet etc…..
Thread based multitasking (TBM)
Single program performing more than one task at the same time is known as thread based
multitasking.
Ex: - An MS word program can check the spelling of word while we type the document.
Java program make use of both process based and thread based multitasking.
Thread=>”A single line of execution”
Multithreaded=>”Multiple line of execution”
Type of threads
Daemon threads
User threads
MULTITHREADING
MULTITHREADING is a program control. A multithreaded program contains two or more
parts that can run concurrently. Each parts of such a program is called a THREAD. The OS is
responsible for scheduling and allocating resource for thread.
Thread class:-
Thread is a class and it contains constructors and methods needed for creating threads.
This class is present in java.lang.package.
Advantages of thread:-
Thread Methods:-
UNIT IV
Graphic Class:-
The graphic class is available in the package “Java.awt”. This class is a must while
building an applet. This method is used to display graphical applet output with the help of the
method drawString() in the graphical class.
Example:
Import java.awt.*;
Import java.applet.*;
Public class Sample extends Applet
{
String msg;
Public void paint(Graphics g)
{
Msg=”Raak College”;
g.drawString(msg,40,30);
}
}
Drawing Lines:-
The drawLine() method is used to draw lines. This method is available in the graphics.
Syntax: void drawLine(int x1, int y1, int x2,int y2)
Where(x1,y1) – starting point of line
(x2,y2)-Ending point of line
Example: Graphics g;
g.drawLine(5,10,50,150);
Drawing Rectangles:-
We can draw the following types of rectangle using the method available in graphic class.
They are
a) Sharp Corner Rectangle
b) Round Corner Rectangle
c) 3D Rectangle
FlowLayout:-
JAVA PROGRAMMING
It is the default layout manager. This used to place the GUI from left to right in the order
they can added in the container.
Constructor:
BorderLayout:-
It is used to arrange the GUI components into five regions namely north, south, east, west
and centre of the container.
Constructor:
Method:
Where component object – created object of the controls such as button, textfield etc
BorderLayout.CENTER
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
GridLayout:-
It is used to divide the window into a grid so that component can be placed in rows and
columns.
Constructor:
EXCEPTION are errors occurring at runtime of the program. It occurs during runtime.
EXCEPTION HANDLING is a technique to deal with exception. It is done with the help of
exception object. The exception object identify the exception and report it for proper action.
Exception Types:-
There are different type of exception classes for handling various errors. All these classes
are derived from the super class throwable.
Types:
ArithmeticException – It is used to find the arithmetic error such as divide by zero
ArrayIndexOutOfBoundException – It is used to find the array index which
exceeds the index limit
OutOfMemoryException – It is used to find out of memory
ClassNotFoundException- It is used to find whether the class is defined or not
IOException – it is used to find the I/O failure such as inability to read from a file
EOFException – This is used to find the end of file
Basics of Exception Handling:-
The structure given below the general form of exception handling
Try
{
Statement for checking the error
}
Catch(Exception obj1)
{
Statement for handling the error
}
Catch(Exception obj2)
{
Statement for handling the error
}
Finally()
{
Statement to be executed before exit
}
Where try, catch, finally are keywords.
a) Try block:
Try block is used to test the program statement or even a single statement for runtime error.
If an error is found, the try block throw the error and is caught by catch block. In the program
there can be any number of try block.
Syntax:
Try
{
Statement for checking the error
JAVA PROGRAMMING
}
b) Catching an Exception :
Catching an exception means catching the thrown exception object from try block by the
corresponding catch block. This block should be written immediately after try block. It can be
more than one catch block.
Syntax:
Catch(Exception obj1)
{
Statement for handling the error
}
When an exception is caught by the corresponding catch block it executes the statement
within it for handling the errors.
c) Finally block:
The final block statement will be executed before exiting the exception handler.
Syntax:
Finally()
{
Statement to be executed before exit
}
Example:
import java.lang.*;
public class expdemo
{
public static void main(String args[])
{
Int a=5,b=0,c;
Try // try block
{
c= a/b;
}
catch(ArithmeticException e) // catch block
{
System.out.println(“Divide by Zero”);
}
}
}
This program demonstrates ArithemticException will be raised.
a) Newborn state
At once the thread object is created for the defined thread the new thread is born. This
state of the thread is called NEW BORN state. From this state the newborn thread can go at any
one of the following state
1) Runnable state 2) Dead state
If start() is called it goes to runnable state, if stop() is called it goes to dead state. The
graph given below shows the flow of new born thread.
b) Runnable state
If a thread is ready for execution, then state of the thread is called RUNNABLE state.
From this state the thread can go to running state if the processor is available for the thread. If it
requires more processor time than the allotted time, it again comes to the runmode state with the
help of the method yield().
c) Running state
If a thread is in execution then this state is called RUNNING state. This state continues
until any one of the following happens.
After the completion of the execution
When yield() is called
When sleep() is called
When wait() is called
When Suspend() is called
d) Blocked state
A thread becomes blocked state if any one of the following method is called while
thread is running.
Sleep()
Wait()
Suspend()
From blocked state it comes to runmodes state if the yield() method is called.
e) Dead state
A thread is said to be in dead state if any one of the following happens.
If it completes it execution – natural death
If it is called by the method stop() - kill
Example Program:-
Class threaddemo
{
Public static void main(String args[])
JAVA PROGRAMMING
{
Thread t = Thread.currentThread();
System.out.println(“Current thread:” + t);
t.setName(“My Thread”);
try
{
For(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
Catch(InterruptedException e)
{
System.out.println(“MainThread interrupted”);
}
}
}
Output:
Current thread: Thread[main,5,main]
After the name change: Thread[My thread,5,main]
5
4
3
2
1
APPLET PROGRAMMING
Definition:
import java.awt.*;
JAVA PROGRAMMING
import java.applet.*;
g.drawString(“WELCOME”,10,10);
3. Before executing the Applet we have to create an HTML file, one the file window and
write the following code.
Example:
<html>
<body>
</applet>
</body>
</html>
Output:
JAVA PROGRAMMING
1. The first import statement import java.awt.*; imports abstract window toolkit (AWT)
classes content window based graphics interface.
2. The second import statement (import.java.applet.*;) imports the applet package which
contains the class Applet.
3. The third statement of the program as public class appletdemo extends Applet deriving
the class Appletdemo from the class Applet
4. The fourth statement as public void paint(Graphics g). The paint() method draws the
applet. This method takes the object g by the class Graphics.
5. The fifth statement as g.drawString(“WELCOME”,10,10). The drawString() is an Abstract
method of the class Graphics. It takes 3 arguments.
The general form is
drawstring(message, int x, int y);
where
message – message to be output
x – integer value which specifies x co-ordinates
y – integer value which specifies y co-ordinates\
The class Applet has 4 methods which consists of the applet life cycle. They are defined by the
Java Applet class.
They are
init() - This method is called only when the applet being execution.
start() - This method is executing after the init() method complete execution. This method is
called by the appletviewer of web browser to resume execution of an applet.
stop() - This method is called by the appletviewer or web browser to suspend the execution by
applet.
destroy() – This method is called by the applet viewer or web browsers before the applet is
terminated.
paint() - This method is inherited by the applet class from the component class.
Example:
import java.awt.*;
import java.applet.*;
String str=” “;
str+=”Intialization”;
str+=”Start”;
JAVA PROGRAMMING
str+=”Stop”;
System.out.println(“DESTROY”);
g.drawString(“WELCOME”,10,10);
</applet>
Output:
JAVA PROGRAMMING
<APPLET
CODE=appletname.class
WIDTH = pixels
HEIGHT = pixels
ALIGN = value
HSPACE = value
</APPLET>
Attributes:
ALIGN – align the output of the applet. Commonly used values are LEFT, RIGHT, MIDDLE, TOP
and BOTTOM