Java Notes PDF
Java Notes PDF
java.
In the late 1990‟s, Sun revised middle-tier capabilities for java to ensure
for java to generate dynamic HTML web pages. Sun also defined
program that can work on the internet. It‟s primary features are that
Machintosh, Linux, and so on. Java is not only used for stand-alone
Implementation
o By using above specifications we can implement
Runtime Instance
o When JVM is running it is known as runtime instance…
JVM Functionalities:-
JVM will be loaded into the memory.
JVM has a class loader which loads the class in memory.
It searches for the main method.
JVM has an execution engine and calls the main method().
JVM is also an instance (i.e. from JVM software).
We can create any number of JVM instances.
The life time of the JVM is the life time of the application.
Java programs never run on the operating system.
It loads the executable code into the RAM.
Executes this code through local Operating System.
Deletes the executable code from RAM.
Java gets a smaller tight code because of byte code, .class file and increase network
mobility which cut shorts the amount transferred.
Security for java:-
Sandbox model is security for java. Security is implemented at 3 different levels.
Class loader
Byte code verifier
Security manager
1. Different systems have different .class files, class loader will check
whether valid .class or not.
2. After loading it checks whether the byte code is downloaded from
authorized .class file (byte code) or not, by byte code verifier.
3. When it goes to run and execute the program it is again checked by
security manager. This entire model is known as sandbox model…
To write a java program we need JDK (java development kit) and we can
download it from java.sun.com
Program Loading:
i. Static Loading
ii. Dynamic Loading
i.Static Loading:
A block of code would be loaded into RAM before it is executed
(i.e. after being loaded into the RAM, it may not execute).
ii.Dynamic Loading:
A block of code loaded into the RAM only when it is required to
be executed.
JVM Follows Dynamic Loading:
JVM would Convert all the statements of the class files into its
executable code at runtime.
Once the control comes out from the method, then it is deleted
from the RAM and another method of .exe type will be loaded as
required.
Once the control comes out from main(), the main method would
also be deleted from the RAM. This is only we are not able to
view the .exe contents of of a .class files.
The JDK contains the software and tools needed to compile, debug
and execute applets and applications written java language. It is
basically a set of command-line tools.
Utilities Offered by JDK:
i. Javac :
This is compiler which converts java source code into byte
code.
ii. Java :
This is java interpreter is used to execute java byte codes.
(Invoke the jvm)
iii. Appletviewer :
This tool is used to view and test applets
iv. Jdb :
Java debugger, which helps us to find errors in our programs
v. Javadoc :
The documentation generator, which is automatically
generates documentation from source code comments.
vi. Javah :
Produces header files for use with native methods
vii. Javap :
Java disassemble, which enables us to convert byte code files
into a program description.
Java Classifications:
Java has three types of Editions
Versions:
JDK 1.0
JDK 1.1
JDK 1.2
JDK 1.3
JDK 1.4
JDK 1.5
JDK 1.6
JDK 1.7
JDK 1.8
Applets:
Applets are java programs that are created specially to work on the
internet. It must be contained or embedded within a web page.
Java Features:
1. Simple
2. Strictly Object Oriented
3. Distributed
4. Multi Threaded
5. Robust
6. Self Documented
7. Secure
8. Platform Independent or Architecture Neutral
1. Simple
There are various features that make the java as a simple language. Programs are
easy to write and debug because java does not use the pointers explicitly & is high
level. It has a very few keyword – 49 in number. It also has the automatic memory
allocation and deallocation system.
4. Multi Threaded
Multithreading means a single program having different threads executing
independently at the same time. Multiple threads execute instructions according to the
program code in a process or a program. Every java program is itself a thread in the
JVM.
5. Robust
Java has the strong memory allocation and automatic garbage collection
mechanism. It provides the powerful exception handling and type checking
mechanism as compare to other programming languages. Compiler checks the
program whether there any error and interpreter checks any run time error and makes
the system secure from crash. All of the above features make the java language
robust.
6. Self Documented
Java generates the documentation of its application using the special comments
available with the java source file. This reduces the time and work burden from the
programmers end.
7. Secure
Java does not have support to concepts like pointers or any such memory accessing
concept. This will not allow the programmer to handle memory locations. Moreover,
all java programs are executed on a closed memory location called the sandbox. These
are not allowed to use or access any location outside this sandbox. All this adds to the
security provided by the java programs.
//
Wrapper class:-
A wrapper class is a special class which wraps around the behavior of a
primitive converting it into an object.
Wrapper class Primitive data types
Byte byte
Short short
Integer int
Long long
Float float
Double double
Character char
Boolean bool
Every wrapper class comes with a number of utility methods which
allows us to convert values from one data type to another data
type.
The parse xxxxx method is used for converting a string into the
corresponding primitive type.
If an invalid string is passed to the parse xxxxx method then it
generates an exception called Number format exception.
Scanner class:
It allows us to scan the values from any input device. It works from
above 1.5 versions.
Arrays:
Array creation in java is a two step process. In the first step, we
create an array variable with the below syntax.
o Datatype arrvar[];
Or
o Datatype[] arrvar;
Array variables are allocated memory on the stack.
In the second step we create the memory for the array elements
with the new keyword using the below syntax:
o Arrvar=new datatype[width];
Ex:- a=new int[10];
o In java, we don‟t have pointers as the memory allocated to
array will not refer to large extent.
The array elements are themselves allocated memory on the heap.
Unlike in c++, arrays in java are internally treated as objects.
Reading past the boundaries of an array generates an exception
called ArrayIndexOutOfBoundsException
Because arrays are internally treated as objects they have given a
built in property called length which returns the number of
elements in the array
The array elements are implicitly assigned default values zeroes in
case of numbers, false in case of Booleans, null in case of
characters and other objects.
Types of Arrays:
1. Single Dimensional Array
2. Multi Dimensional Array
Multi-Dimensional Array:-
Consider a scenario where we need to store the roll numbers
of 50 students and their marks in three exams.
Using a single-dimensional array, we require two separate arrays
for storing roll numbers and marks. However, using a multi-
dimensional array, we just need one array to store both, roll
numbers as well as marks.
1. Rectangular Arrays:
A rectangular array is multi-dimensional array where all the specified
dimensions have constant values. A rectangular array will always have
the same number of columns for each row.
Example of Rectangular Array:
class Arr5
{
public static void main(String arg[])
{
int dimension[][]=new int[4][5];
int numone=0;
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
dimension[row][col]=numone;
numone ++;
}
}
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
System.out.print(dimension[row][col]+"\t");
}
System.out.println();
}
}
}
Jagged Array:
A jagged array is a multidimensional array where one of the
specified dimensions can have varying sizes. Jagged arrays can have
unequal number of columns for each row.
Example of Jagged Array
class Arr6
{
public static void main(String arg[])
{
String[][] companies=new String[3][];
companies[0]=new String[]{"Intel","AMD"};
companies[1]=new String[]{"IBM","Microsoft","Sun"};
companies[2]=new String[]{"HP","Canon","Lexmark","Epson"};
for(int row=0;row<companies.length;row++)
{
System.out.print("List of companies in group "+(row+1) + ":\t");
for(int col=0;col<companies[row].length;col++)
{
System.out.print(companies[row][col] + " ");
}
System.out.println();
}
}
}
OBJECT ORIENTED PROGRAMMING SYSTEM
Class:-
In a JAVA program the "class" keyword denotes that the JAVA
program follows this standard of class structure.
(or)
Class is nothing but collection of data and functions.
(or)
Collection of data members and member functions.
2.Objective:-
It is a invisible and it is the end result of an application which can
be achieved using data members and member functions. Objective
means end result of the program.
3.Data Members:-
Data members are the elements which can be participated in a prog
to achieve the objective of an application.
4.Member Function:-
It is a process of a technic in a program which can take a parameter
and returns a value. Member function can be called methods in OOPS
Programming.
5.Object:-
It is a instance of a class which can be gives the reference to its.
The data member and the member functions which can be used outside
of the class.
(or)
Object is nothing but instance of a class.
Datatypes:-
Datatypes which are denotes what type of data that your processing
to our program.
Variables:-
It is a location memory where we can store the values into the
memory those values in the memory called "constants".
1.Data Encapsulation:-
The union of data and functions into objects is known as Data
Encapsulation.
(or)
Details of what a class contains need not be visible to other classes and
objects that use it. Instead, only specific information can be made
visible and the others can be hidden. This is achieved through
encapsulation, also called data hiding. Both abstraction and
encapsulation are complementary to each other.
2.Data Abstraction:-
We can give restricting the data, to set a number of functions.
(or)
It gives security.
(or)
3.Polymorphism:-
It is ability to take more than one form.
(or)
Use of something for different purposes.
(or)
Polymorphism is the ability to behave differently in different
situations. It is basically seen in programs where you have multiple
method declared with the same name but with diferent parameters and
different behavior.
4.Inheritance:-
Relation between two classes.
(or)
Object of one class can acquire the properties of object of another
class.
(or)
Inheritance is the process of creating a new class based on the
attributes and methods of an existing class. The existing class is called
the base class whereas the new calss created is called the derived class.
This is very important concept of objet-oriented programming as it helps
to reuse the inherited attributes and methods.
Super Class:-
It is a old class or parent class
Sub Class:-
It is a new class or child class which can acquire the properties
from base class.
class Demo
{
public void display()
{
System.out.println("This is the First method in Class..");
}
public void disp()
{
System.out.print("This is Second method in Class..");
}
}
class A7
{
public static void main(String args[])
{
Demo d=new Demo();
d.display();
d.disp();
}
}
Constructor:-
Constructors are special member function whose name is same as a class
name constructors are need not require to be called because it is invoked
automatically in the objects are created. Constructor may have an argument or
may not have an argument. Constructors have no return type.
Normal Method:-
A normal method may have any name associated with it. Normal methods
may or may not return values. Normal methods may be invoked any time
anywhere once an object is created.
Method Overloading:-
No class is allowed to contain two methods with the same name and same
signature. However, it is possible for a class to have two methods having the same
name but different signatures. The concept of declaring more than one method
with the same method name but different signatures is called method overloading.
Constructor Overloading:
The concept of declaring more than one constructor in a class is called
constructor overloading. The process of overloading constructor is similar to
overloading methods. Every constructor has a signature similar to that of a
method. You can declare multiple constructors in a class wherein each constructor
will have different signatures. Constructors reduce the task of assigning different
values to member variables each time when needed by different objects of the
class.
iv. A formal parameter and an instance variable may have the same name but
in such a case it is the formal parameter that is given precedence over the
instance variable within the method. To differentiate the two, we precede
the instance variable with the this keyword.
v. We can also use keyword this for different names of instance variables and
formal parameters. Example: this.length= l
vi. this method can be used only within a constructor. this can be used in two
ways: 1) Keyword 2)Method
class Demo
int x,y;
this.x=x;
this.y=y;
class C14
d.Show(10,20);
d.Display();
Polymorphism:
Polymorphism is derived from two Greek words, namely Poly and Morphos.
Poly means many and Morphos means forms. Polymorphism means existing in
multiple forms. Polymorphism is the ability of an entity to behave differently in
different situations. The two methods in class having the same name but different
signatures performing the same basic operation but in different ways.
Example on Polymorphism:
class demo
{
return x+y;
return x+y;
return x+y;
return x+y+z;
class Poly
------------------------------------------------------
Compile-time Polymorphism:-
* It is implemented through method overloading.
Run-time Polymorphism:
* It is implemented through method overriding.
* It is executed at run-time since the compiler does not know the method to
be executed, whether it is the base class method that will be called or the derived
class method.
As a keyword:-
If used as a keyword it lets you access the immediate super class members
As a method:-
A subclass and a super class may have the variables with the same name.
However, in such a case it becomes mandatory to precede the super classes‟
members with the super keyword.
Class A
int x;
int y;
Class B extends A
int x;
int y;
class base
int a = 100;
int a = 200;
void show()
System.out.println(super.a);
System.out.println(a);
class A18
new sup1().show();
//s.show();
}
Example of Super Method:
class Demo1
super.display();
class A19
d.display();
}
Class variables: -
i. Class variables are variables that belong to the entire class and not to a
specific instance of a class.
ii. Instance variables on the contrary are variables belongs to specific instance
of the class.
iv. Class variables are allocated memory only once which can then be
commonly accessed by all the instances of the class.
v. Static variables are allocated memory on the static pool. They are allocated
memory only once that to when a class is loaded into the memory for the
first time.
vi. Since memory for a class variable is allocated at the time of loading the class
itself. We can access this static variable directly with the class name itself
without having to wait for the instantiation of the class.
vii. Static variables are given default values (zeroes in case of numbers, false
in case of Booleans, null incase of characters and other objects)
Static Block:-
i. A static block is a block of statements preceded by a static keyword.
ii. The main purpose of a static block is to initialize static members to non-zero
values.
iii. We can have any number of static blocks defined in a java program.
iv. If there is more than one static block in a java program, the block are
executed in a top-down approach
v. Static blocks are executed only once, when the class is loaded into memory
for the very first time.
vi. Static blocks have a higher precedence than constructors and even the main
method.
ii. They cannot make use of this and super keywords as this and super are used
when an object is created
Not only variables if required , methods may also be declared as static the
advantage of declaring methods as static is one gets to execute the static methods
directly with the class more itself rather than creating an instance of the class.
class StaticVar
System.out.println("Employee ID is "+eno);
}
Example of Static Block:
class A
static
static int x;
static
x=20;
class A22
static
System.out.println("In main");
System.out.println("A.x....."+A.x);
static
Overriding:
Overriding can take place only in a sub class, super class hierarchy.
The two overridden methods must have the same number of parameters.
The two overridden methods must have the same data types for the
parameters.
The return types must be the same…
Dynamic Method Dispatch:-
Dynamic method dispatch is a concept wherein we assign a subclass object
to the super class object reference.
The main advantage of dynamic method dispatch is Run Time
Polymorphism
class vehicle
{
public void brake()
{
System.out.println("Vehicle's brakes applied....");
}
}
class Car extends vehicle
{
public void brake()
{
System.out.println("car's brakes applied....");
}
}
class Bike extends vehicle
{
public void brake()
{
System.out.println("bike's brakes applied....");
}
}
class A20
{
public static void main(String args[])
{
int ch=Integer.parseInt(args[0]);
vehicle V;
if(ch==1)
{
V=new Car();
V.brake();
}
else if(ch==2)
{
V=new vehicle();
V.brake();
}
else if(ch==3)
{
V=new Bike();
V.brake();
}
else
{
System.out.println("Invalid Method..");
}
}
}
class Testfinalvar
max = 10;
for(int i=0;i<=max;i++)
System.out.println("value at i :"+i);
class Proposal
*/
p.finalMemo();
{
System.out.println("Hello World");
class FinalClass
supobj.sayHello();
subobj.sayHello();
subobj.sayHelloAgain();
}
Abstract Classes:
A class that is defined using the abstract keyword and that contains at least
one method which is not implemented in the class itself is referred to as
abstract class. Means the abstract class contains at least one method without
a body, the class cannot be instantiated using the new keyword. While
declaring an abstract class or abstract method the keyword 'abstract' should
be used. The abstract keyword is thus an indicative of incompleteness. As
an abstract class is considered to be an incomplete class the JVM does not
permit the creation of objects of abstract classes. The JVM allows objects for
concrete classes only.
System.out.println("Drawing a circle");
}
System.out.println("Drawing a rectangle");
class A26
s.draw();
s.display();
s1.draw();
s1.display();
}
Interfaces:
An interface contains only abstract members. Unlike an abstract class, an interface
cannot implement any method. But similar to an abstract class, an interface cannot
be instantiated. An interface can only be inherited by classes or other interfaces.
An interface is declared using the keyword interface Interfaces does not allow the
normal methods. To inherit the interface “implements “ keyword should be used.
Example of Interface:
interface A
interface B
System.out.println("a Method");
{
System.out.println("b Method");
class A27
C ob=new C();
ob.aMeth();
ob.bMeth();
class A
interface B
{
public void Meth();
class A28
C ob=new C();
ob.Method();
ob.Meth();
Implicit Typecasting:-
Implicit typecasting refers to automatic conversion of datatypes. Implicit
typecasting is done only when the destination and source data types belongs to
same hierarchy. In destination data type must hold a larger range of values than
the source data type. So Implicit typecasting prevents the loss of data. If you have
int type value to, you can assign long type of variable.
//Implicit Conversion
class A29
int b = 7;
result = a + b;
Explicit Typecasting:-
Explicit typecasting refers to changing a data type of higher precision into a data
type of lower precision. For example, using explicit typecasting, you can
manually convert the value of float type into int type. This typecasting might
result in loss of data, the digits after the decimal point are lost.
float----->Explicit Conversion----->int
Example of Explicit Conversion:
//Explicit Conversion
class A30
int subject = 6;
System.out.println("average is :"+avg );
Packages:-
1. Packages offer different namespaces allowing two or more programmers to
make use of the same class name but with different implementations without any
problem.
3. Packages are implemented by the JVM using the underlined operating systems
file structure mechanisms.
4. Working with packages is a two step process, in the first step , we intimate the
JVM about the placement of a class in a package by using the package statement.
5. Syntax :
package packagename;
6. The package statement must be the first statement in the program. There is only
one package statement per program.
7. If we din‟t place a class explicitly in a package the program the class will be
placed implicitly in the default package…..
9. The default package relates to the current working directory. When we place a
class in a package we have to ensure that the .class file corresponding to the class
is placed in a directory. Which has the same name as that of a package.
10. This can be done in two ways : Either manually or by using -d option of the
java utility.
11. -d option if used will implicitly ensure that the respective directories structures
are created if requires and ensure that the .class files are placed in them
respectively.
13. To execute a class that has been placed in a package we give the following
command from the parent directory containing the package directory.
Java Packagename.classname
14. One must compulsorily declare a class placed in a package public to be able to
create its objects in other classes belonging to other packages.
15. To use a class placed in a package in another class we can follow one of the
below procedures.
16. Use a fully qualified class name as and when required.
Use the import statement to make the classes or interfaces available to the current
program.
17. The import if used can be used in one of the following ways
Import packagename.*
18. Makes all the classes and interfaces placed directly under the package available
to the current program, irrespective of whether they are used or not. This may
increase the compilation time however.
Imports only the specified class name into the current program
To use a class placed in a package from a directory different from the parent
directory containing the package directory, we have to set the classpath
“environment variable” appropriately.
20. The order in which package , import and class statements have to be used is
1)package,2) import,3) class
Syntax:
Java packagename.subpackagename.classname
4. Import packagename.* imports only the classes and interface placed directly in
the package. To import classes and interfaces belonging to sub-packages
Import packagename.subpackagename.*
Import packagename.subpackagename.classname
How to execute Packages Manully:-
===========================
D:\pack1>java EmpDetails.Employee
->Compiling:
D:>pack2>javac -d . Employee.java
Executing:-
->java EmpDetails.Employee
Package Executing From Different Floders:-
->create pack3 folder in D drive
->D:>pack3>java EmpDetails.Employee
->D:>pack4>java EmpDetails.Employee
->C:>Pack7>set classpath=.;D:\Pack5;D:\Pack6;
->javac EmpDemo.java
->java EmpDemo
Example on Packages(Employee.java)
package EmpDetails;
public class Employee
{
int Empno;
String Ename;
double sal;
public Employee(int Empno,String Ename,double sal)
{
this.Empno=Empno;
this.Ename=Ename;
this.sal=sal;
}
public void PrintDetails()
{
System.out.println("Empno.."+this.Empno);
System.out.println("Ename.."+this.Ename);
System.out.println("Sal.."+this.sal);
}
public static void main(String args[])
{
Employee emp=new Employee(100,"ABC",20000);
emp.PrintDetails();
}
}
emp.PrintDetails();
emp1.PrintDetails();
}
}
Exceptional Handling
Exception, that means exceptional errors. Actually exceptions are used for
handling errors in programs that occurs during the program execution. During the
program execution if any error occurs and you want to print your own message or
the system message about the error then you write the part of the program which
generate the error in the try{} block and catch the errors using catch() block.
Exception turns the direction of normal flow of the program control and send to the
related catch() block. Error that occurs during the program execution generate a
specific object which has the information about the errors occurred in the program
•A network connection has been lost in the middle of communications, or the JVM
has run out of memory.
Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the
three categories of exceptions:
Checked Exceptions:
A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the exception class
there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions
normally happen in case of severe failures, which are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
Throwable
Error Exception
Exceptions Methods:
Using a finally block allows you to run any cleanup-type statements that you
ant to execute, no matter what happens in the protected code
w
Example 1:
class A32
int x,y;
x=10;
y=0;
try {
int z=x/y;
} catch(Exception e) {
}
Example 2:
class DepartmentException extends Exception
DepartmentException()
class A33
protected A33(){ }
int empid,deptid;
String empname;
try {
empid=Integer.parseInt(args[0]);
empname = args[1];
deptid = Integer.parseInt(args[2]);
if(deptid>5){
} else {
System.out.println("Employe Id is :"+empid);
System.out.println("Detapartment Id is:"+deptid);
} catch(DepartmentException ed) {
System.out.println("Invalid Data");
} catch(NumberFormatException ne) {
System.out.println("Incorrect Data..");
} catch(ArrayIndexOutOfBoundsException ae) {
System.out.println("Incomplete Data");
/* java EemployeeDetails
Incomplete data
incorrect data
Employee id is : 1
Invalid Data..!
*/
Example 3:
class NumberException
try
catch(ArrayIndexOutOfBoundsException ne)
catch(NumberFormatException nb)
{
System.out.println("Not a Number!");
class A34
obj.test(args);
/*Output:
java A34
No arguament given!
java A34 dd
Not a Number!
java A34 4
The square is 16
*/
Example 4:
class NestedException
try
try
/*Typecasting*/
} catch(NumberFormatException nb) {
System.out.println("Not a Number!");
}catch(ArrayIndexOutOfBoundsException ne){
}
}
class A35
obj.test(args);
Example 5:
class A36
try
int a=10;
int b=0;
int c=a/b;
System.out.println("C..."+c);
}
catch(Exception e)
System.out.println("Some Error..");
finally
System.out.println("Infinally..");
Multithreading:
Java supports concurrent programming through its built-in support for
thread programming. A thread is defined as sequential path of execution.
Running : the thread enters the running state when it start executing. It starts
running as soon as it gets the CPU time
Sleeping : the execution of the thread can be halted temporarily for a period of time
with the help of seep() method. The thread becomes ready after the sleep time
expires. Sleeping thread do not use the processor
Waiting : when two or more thread run concurrently and only one thread takes
hold of the resources all the time it will lead to starvation for the other threads. To
avoid this, a technique is required that will make a thread wait till the other thread
notify it to continue. Java provides a wait-notify mechanism to take care of this
problem. More about this will be learnt in the next session. Thus a thread is in
waiting is in waiting stare if the wait() method has been invoked.
Blocked : The thread enters a blocked stare when it waits for an event such as
input/output operations.
Dead : The thread enters a dead state after the run() method has finished execution.
The thread should end on its own by having a run() method that terminates
naturally.
Example I:
for(int i=10;i<=20;i++)
T1 t=new T1();
t.create();
for(int i=1;i<=10;i++)
{
Example 2
thread.start();
for(int i=10;i<=20;i++)
{
T1 t=new T1();
t.create();
for(int i=1;i<=10;i++)
Example 3:
thread.start();
for(int i=10;i<=20;i++)
}
}
T2 t=new T2();
t.create();
for(int i=1;i<=10;i++)
Example 4:
class ThreadFirst
System.out.println("hai :"+thread);
System.out.println(thread.getName());
thread.setName("Uma");
System.out.println("hai :"+thread);
System.out.println(thread.getName());
System.out.println(thread.getPriority());
thread.setPriority(8);
System.out.println(thread.getPriority());
System.out.println(thread.currentThread());
Example 5
throws Exception
th.create();
for(int ctr=0;ctr<=10;ctr=ctr+2)
sleep(1000);
System.out.println(ctr);
{
Thread th=new Thread(this);
th.start();
try
for(int i=1;i<=5;i++)
sleep(1000);
System.out.println(i);
catch(InterruptedException e){ }
Example 6
class sleepdemo
throws Exception
{
for(int i=1;i<=5;i++)
Thread.sleep(1000);
System.out.println(i);
/*for(int i=5;i>=1;i--)
Thread.sleep(1000);
System.out.println(i);
}*/
Example 7
objx.create();
}
public void create()
objth.start();
for(int i=0;i<=5;i++)
try
Thread.sleep(500);
catch(InterruptedException e){ }
}
Java Foundation Classes: -
VB or .Net provide drag and drop approach for creating GUI, whereas C++
requires a programmer to write the entire code towards building a GUI.
1. Create the element. For instance, checkbox or label or listbox and so on.
The Abstract Window Toolkit (AWT) is a set of Java classes that allow the
programmer to create a Graphical User Interface(GUI) and accept user input
through the keyboard and the mouse. It is a part of Java Foundation Classes(JFC).
The Java.awt package contains all classes for creating user interfaces and for
painting graphics and images.
Containers:
A container object is a component that can contain other AWT components.
Components:
A component is an object that has graphical representation and can be
displayed n the screen. It allows user interaction.
Layout Managers:
A Layout manager defines the location and size of the Graphical User
Interface components.
Fonts:
To select a new font, a Font object has to be constructed that will describe
the font.
Events:
An event is an object that describes a state change in a source. It can be
generated as a consequence of an action interacting with the elements in a
Graphical User Interface.
The classes which we are about to learn is known as Java Foundation
Classes. It consists of 4 API
AWT
Swing
Graphics 2D API
Accessibility API
List box
Event:-
Interaction between user and system, even any movement like mouse
movement is mouse event
Listeners Component are components that listen for a particular event, and when
the event takes place it generates a response(set of statements means behaviors)
listeners are basically interfaces.
Layout:-
Its responsibility is to manage the layout of the container… Every Container
comes with built-in layouts
Frame
Dialog box:-
It is a special window which is poped – up as a result of user-interaction with
existing component.
We will get a dialog box and that dialog box until it is interacted and disposed off
it will not allow any other component to interact…
import java.awt.*;
f.setSize(200,200);
f.setVisible(true);
Example II
import java.awt.*;
f.setSize(200,200);
f.setVisible(true);
f.add(btn);
//f.add(txt);
Example III
import java.awt.*;
class A45
f.setSize(300,100);
f.setVisible(true);
t.setEchoChar('@');
//t.setText("aptech");
//System.out.println(t.getText());
//System.out.println(t.getEchoChar());
//b.setLabel("Username");
//System.out.println(b.getLabel());
t.setForeground(Color.green);
t.setBackground(Color.red);
f.add(p);
p.add(l);
p.add(t);
p.add(b);
Example IV:
import java.awt.*;
import java.awt.event.*;
TestFrame(String Title)
super(Title);
setBackground(Color.black);
setForeground(new Color(0,255,0));
setSize(400,100);
setVisible(true);
g.drawString("APTECH",70,70);
class A46
new TestFrame("SampleWIndow");
Example V
import java.awt.*;
g.setFont(f);
g.drawString("This is my Frame",75,100);
f.setSize(300,250);
f.setVisible(true);
Example VI
//ListBox Demo
import java.awt.*;
A48(String name)
super(name);
//c.setMultipleSelections(true);
c.add("Item1");
c.add("Item2");
c.add("Item3");
add("North",b);
add("South",c);
setVisible(true);
setSize(200,200);
}
Event Handling in Java
The user performs an action, such as, moving the mouse, pressing a key, releasing
the key and so on. All these operations generate an event.
Some of these events are handled by Abstract Window Toolkit (AWT) by the
environement in which these applications are executed, such as a browser. JDK1.2
followsthe "Delegation Model". This is a process that allows to register handlers
called "listeners", with the objects. These handlers are automatically called when
an even takes place.
This calls the methods that handle the event, called the "event handler". Each
event listener provides methods that handle these events.
Syntax:
eg: btnClose.addActionListener(this);
Events and their Description:
Event Class Description
ActionEvent When a button is pressed, a list item is double clicked or a
menu is selected.
ActionListener
AdjustmentListener
ComponentListener
FocusListener
ItemListener
WindowListener
TextListener
MouseListener
MouseMotionListener
KeyListener
Example VII
import java.awt.*;
import java.awt.event.*;
TextField UserName,Email;
Checkbox UseEmail;
TextField Password;
TestFrame()
super("Sample Window");
setLayout(new FlowLayout());
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
Password.setEchoChar('*');
UseEmail.addItemListener(this);
add(new Label("UserName"));
add(UserName);
add(UseEmail);
add(Email);
add(new Label("Password"));
add(Password);
setSize(400,100);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
if(UseEmail.getState()==true)
UserName.setEnabled(false);
UserName.setBackground(Color.LIGHT_GRAY);
Email.setBackground(Color.WHITE);
Email.setEnabled(true);
Email.requestFocus();
else
UserName.setEnabled(true);
UserName.setBackground(Color.WHITE);
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
UserName.requestFocus();
class A49
{
public static void main(String args[])
new TestFrame();
Example VIII
import java.awt.*;
import java.awt.event.*;
ButtonEventDemo()
btn.addActionListener(this);
frm.add(pnl);
pnl.add(btn);
frm.setVisible(true);
frm.setSize(300,200);
}
class A50
Example IX
import java.awt.*;
import java.awt.event.*;
TextField UserName,Email;
Checkbox UseEmail;
TextField Password;
TestFrame()
super("Sample Window");
setLayout(new FlowLayout());
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
Password.setEchoChar('*');
UseEmail.addItemListener(this);
add(new Label("UserName"));
add(UserName);
add(UseEmail);
add(Email);
add(new Label("Password"));
add(Password);
setSize(400,200);
setVisible(true);
if(UseEmail.getState()==true)
UserName.setEnabled(false);
UserName.setBackground(Color.LIGHT_GRAY);
Email.setBackground(Color.WHITE);
Email.setEnabled(true);
Email.requestFocus();
else
UserName.setEnabled(true);
UserName.setBackground(Color.WHITE);
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
UserName.requestFocus();
}
class A51
new TestFrame();
Example X
import java.awt.*;
import java.awt.event.*;
TextField UserName,Email;
Checkbox UseEmail;
TextField Password;
TestFrame()
super("Sample Window");
setLayout(new FlowLayout());
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
Password.setEchoChar('*');
UseEmail.addItemListener(this);
add(new Label("UserName"));
add(UserName);
add(UseEmail);
add(Email);
add(new Label("Password"));
add(Password);
setSize(400,200);
setVisible(true);
if(UseEmail.getState()==true)
UserName.setEnabled(false);
UserName.setBackground(Color.LIGHT_GRAY);
Email.setBackground(Color.WHITE);
Email.setEnabled(true);
Email.requestFocus();
else
UserName.setEnabled(true);
UserName.setBackground(Color.WHITE);
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
UserName.requestFocus();
class A51
new TestFrame();
}
Example :
import java.awt.*;
import java.awt.event.*;
MouseDemo()
setSize(400,400);
setVisible(true);
addMouseListener(this);
addWindowListener(a);
System.out.println("Mouse clicked");
System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent m3)
System.out.println("Mouse Exited");
System.out.println("MousePressed");
System.out.println("MouseReleased");
System.exit(0);
class A52
{
public static void main(String args[])
new MouseDemo();
Example XI
import java.awt.*;
import java.awt.event.*;
MousemotionDemo()
setVisible(true);
setTitle("MousemotionExample");
addMouseMotionListener(this);
setSize(200,200);
}
public void mouseMoved(MouseEvent me)
class A54
new MousemotionDemo();
FlowLayout:
import java.awt.*;
fa.setLayout(new FlowLayout());
fa.setSize(400,300);
fa.setVisible(true);
FlowAp()
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
add(new Button("Six"));
add(new Button("Seven"));
add(new Button("Eight"));
add(new Button("Nine"));
add(new Button("Ten"));
}//End of constructor
}//End of Application
import java.awt.*;
fa.setLayout(new FlowLayout());
fa.setSize(400,300);
fa.setVisible(true);
FlowAp()
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
add(new Button("Six"));
add(new Button("Seven"));
add(new Button("Eight"));
add(new Button("Nine"));
add(new Button("Ten"));
}//End of constructor
}//End of Application
import java.awt.*;
import java.awt.event.*;
class TestFrame extends Frame
Panel DisplayPanel;
Panel ButtonsPanel,MoveButtonsPanel,DMLButtonsPanel;
TextField txtDeptno,txtDname,txtLoc;
Button First,Last,Next,Previous;
Button Insert,Update,Delete,Exit;
TestFrame()
DisplayPanel.setLayout(new GridLayout(3,2));
DisplayPanel.add(new Label("DeptNo"));
DisplayPanel.add(txtDeptno);
DisplayPanel.add(new Label("Dname"));
DisplayPanel.add(txtDname);
DisplayPanel.add(new Label("Loc"));
DisplayPanel.add(txtLoc);
ButtonsPanel.setLayout(new GridLayout(2,1));
MoveButtonsPanel = new Panel();
MoveButtonsPanel.add(First);
MoveButtonsPanel.add(Previous);
MoveButtonsPanel.add(Next);
MoveButtonsPanel.add(Last);
DMLButtonsPanel.add(Insert);
DMLButtonsPanel.add(Update);
DMLButtonsPanel.add(Delete);
DMLButtonsPanel.add(Exit);
ButtonsPanel.add(MoveButtonsPanel);
ButtonsPanel.add(DMLButtonsPanel);
add(DisplayPanel);
add(ButtonsPanel,BorderLayout.SOUTH);
pack();
setVisible(true);
class Demo
new TestFrame();
Applet:
An applet is a Java program that can be embedded in a HTML page and
executed on Java enabled web browser. An applet is like a small executable code
that needs a full application to contain it or execute it. An applet is created by
subclassing the java.applet.Applet class.
Applications run using the java interpreter, while applets run on any
browser( which supports java) or used the appletviewer tool, which is
included in the JDK.
Execution of application begins with the main() method, while the execution of an
applet begins with the init() method.
An applet must contain at least one public class, failing which the compiler reports
an error. It is not mandatory to declare a main() method for an applet.
init():
The method called during initiasation is known as the init() method.
start():
Once the initialisation is process is complete, the applet is started. The start()
method is called, when the applet is started. This method is used to restart the
applet after it has stopped.
stop():
The stop() method comes into the picture when the execution of an applet has to be
paused. An applet should be stopped before it is destroyed.
destroy():
An applet is destroyed using the destroy() method. The memory processor time
and swap disk space are returned to the system when the applet is destroyed.
Apart from these fundamental methods, there are methods called paint(), repaint()
paint():
The paint() method is used to display a line, text or an image on the screen. It
takes an argument of the class "Graphics".
Example I:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=ap1 width=200 height=100 >
</applet>*/
public class ap1 extends Applet implements ActionListener
{
Label lab;
TextField tf1,tf2;
Button btnresult;
public void init()
{
lab=new Label("Enter a number: ");
tf1=new TextField(5);
tf2=new TextField(5);
btnresult=new Button("Double is ");
btnresult.addActionListener(this);
add(lab);
add(tf1);
add(btnresult);
add(tf2);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println("Hai.. ");
}
}
/* Executing: javac ap1.java
appletviewer ap1.java
appletviewer ap1.html */
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = AddButAppExp width=400 height=300>
</applet>
*/
public class AddButAppExp extends Applet
implements ActionListener
{
Button b1,b2;
String s;
public void init()
{
s = "Click a button";
b1 = new Button("This is the First Button");
b2 = new Button("A Smal Button");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
public void paint(Graphics g)
{
g.drawString(s,10,50);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == b1)
s = "First Button is clicked";
else
s = "Second small Button is clicked";
repaint();
}
}
Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=FirstAppExp
width=400 height=400>
</applet>
*/
public class FirstAppExp extends Applet
{
String s;
public void init()
{
s = "Hello! Welcome to Applet Programming";
setBackground(Color.YELLOW);
}
public void paint(Graphics g)
{
g.drawString(s,100,200);
}
}
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=ButChAppExp
width=500 height=500>
</applet>
*/
public class ButChAppExp extends Applet
implements ActionListener,ItemListener
{
Label lob,lcol;
Choice chob,chcol;
Button b;
int obind;
Color col;
public void init()
{
chob = new Choice();
chcol= new Choice();
b = new Button("All Clear");
lob = new Label("Select Object: ");
lcol = new Label("Select Color: ");
chob.add("Rectangle");
chob.add("RoundedRectangle");
chob.add("Square");
chob.add("Circle");
chob.add("Oval");
chob.add("Arc");
chcol.add("Blue");
chcol.add("Red");
chcol.add("Green");
chcol.add("Gray");
chcol.add("Magenta");
chob.select(1);
// obind = 2;
chcol.select("Green");
col = Color.GREEN;
chob.addItemListener(this);
chcol.addItemListener(this);
b.addActionListener(this);
add(lob);
add(chob);
add(lcol);
add(chcol);
add(b);
}
public void paint(Graphics g)
{
g.setColor(col);
switch(obind)
{
case 0: g.drawRect(5,120,120,50);
g.fillRect(5,180,120,50);
break;
case 1: g.drawRoundRect(5,120,120,50,10,10);
g.fillRoundRect(5,180,120,50,10,10);
break;
case 2: g.drawRect(5,120,50,50);
g.fillRect(5,180,50,50);
break;
case 3: g.drawOval(5,120,50,50);
g.fillOval(5,180,50,50);
break;
case 4: g.drawOval(5,120,120,50);
g.fillOval(5,180,120,50);
break;
case 5: g.drawArc(5,120,50,50,0,180);
g.fillArc(5,180,120,50,0,180);
break;
}
}
public void actionPerformed(ActionEvent ae)
{
obind = -1;
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == chob)
{
obind = chob.getSelectedIndex();
}
else
{
switch(chcol.getSelectedIndex()) {
case 0: col = Color.BLUE; break;
case 1: col = Color.RED; break;
case 2: col = Color.GREEN; break;
case 3: col = Color.GRAY; break;
case 4: col = Color.MAGENTA; break;
}
}
repaint();
}
}
Example
import java.awt.*;
import java.applet.*;
/*
<applet code = FaceAppExp width=450
height =450>
</applet>
*/
public class FaceAppExp extends Applet
{
public void paint(Graphics g)
{
/*---laugh face stright angle---------*/
g.setColor(Color.GREEN);
g.fillOval(0,0,200,200); //face
g.setColor(Color.BLACK);
g.drawLine(100,60,100,120); //nose
g.setColor(Color.RED);
g.fillOval(40,50,40,40);
g.fillOval(120,50,40,40); //eyes
g.setColor(Color.BLACK);
g.drawArc(35,80,130,80,0,-180); //mouth
/*---laugh face side angle---------*/
g.setColor(Color.GREEN);
g.fillOval(250,0,200,200);
g.setColor(Color.BLACK);
g.drawLine(300,60,280,120);
g.drawLine(280,120,300,120);
g.setColor(Color.RED);
g.fillOval(270,50,40,40);
g.fillOval(290,50,40,40);
g.setColor(Color.BLACK);
g.drawArc(275,80,50,80,0,-180);
/*---cry face stright angle---------*/
g.setColor(Color.GREEN);
g.fillOval(0,250,200,200);
g.setColor(Color.BLACK);
g.drawLine(100,310,100,370);
g.setColor(Color.RED);
g.fillOval(40,300,40,40);
g.fillOval(120,300,40,40);
g.setColor(Color.BLACK);
g.drawArc(35,370,130,80,0,180);
/*---cry face side angle---------*/
g.setColor(Color.GREEN);
g.fillOval(250,250,200,200);
g.setColor(Color.BLACK);
g.drawLine(300,310,280,370);
g.drawLine(280,370,300,370);
g.setColor(Color.RED);
g.fillOval(270,300,40,40);
g.fillOval(290,300,40,40);
g.setColor(Color.BLACK);
g.drawArc(275,370,50,80,0,180);
}
}
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code =LabelAppExp
width=500 height=300>
</applet>
*/
public class LabelAppExp extends Applet implements ActionListener
{
Label l;
TextField t;
public void init()
{
l = new Label("Hello Friends",Label.CENTER);
t = new TextField("Hello Friends",35);
t.addActionListener(this);
add(l);
add(t);
}
public void actionPerformed(ActionEvent ae)
{
l.setText(t.getText());
}
}
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet
code=ListFontAppExp
width=600 height=600>
</applet>
*/
public class ListFontAppExp extends Applet
implements ItemListener, AdjustmentListener
{
String fn[];
List lb;
Scrollbar s;
GraphicsEnvironment ge;
String fontname;
int fontsize;
public void init()
{
ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
fn = ge.getAvailableFontFamilyNames();
lb = new List(10);
s = new Scrollbar();
s.setOrientation(Scrollbar.HORIZONTAL);
s.setMaximum(500);
s.setMinimum(5);
s.setValue(20);
fontsize = 20;
for(int i=0;i<fn.length;i++)
lb.add(fn[i]);
lb.select(0);
fontname = fn[0];
s.addAdjustmentListener(this);
lb.addItemListener(this);
add(s);
add(lb);
} public void itemStateChanged(ItemEvent ae){
fontname = lb.getSelectedItem();
repaint();
}
public void adjustmentValueChanged
(AdjustmentEvent ae)
{
fontsize = s.getValue();
repaint();
}
public void paint(Graphics g)
{
g.setFont(new Font
(fontname,Font.PLAIN,fontsize));
g.drawString("Selected Font: "+fontname,5,300);
}
}
Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=SecAppExp width=600 height=600>
</applet>
*/
public class SecAppExp extends Applet
{
String s;
int x,y;
public void init()
{
s = "Graphiscs Methods Demo";
}
public void paint(Graphics g)
{
x=y=10;
g.setColor(Color.RED);
g.drawString(s,x,y); y+=5;
g.drawLine(x,y,x+150,y); y+=5;
g.setColor(Color.GRAY);
g.drawOval(x,y,50,50);
x+=55;
g.drawOval(x,y,150,50);
x=10; y+=55;
g.fillOval(x,y,50,50);
x+=55;
g.fillOval(x,y,150,50);
x=10; y+=55;
g.setColor(Color.MAGENTA);
g.drawRect(x,y,50,50);
x+=55;
g.drawRect(x,y,150,50);
x=10; y+=55;
g.fillRect(x,y,50,50);
x+=55;
g.fillRect(x,y,120,50);
x=10; y+=55;
g.setColor(Color.magenta);
g.drawArc(x,y,50,50,0,180);
x+=55;
g.fillArc(x,y,150,50,0,180);
x=10; y+=55;
g.setColor(Color.GREEN);
g.drawRoundRect(x,y,50,50,15,15);
x+=55;
g.fillRoundRect(x,y,150,50,15,15);
setBackground(Color.cyan);
}
}
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=TextAreaAppExp
width=360 height=400>
</applet>
*/
public class TextAreaAppExp
extends Applet
implements ActionListener, ItemListener
{
Font f;
TextArea ta;
TextField tf;
Button b;
Checkbox cb,cb1,cb2;
CheckboxGroup cbg;
public void init()
{
ta = new TextArea(10,40);
tf = new TextField(35);
b = new Button("Clear");
cb = new Checkbox("Allow Edit",false);
cbg = new CheckboxGroup();
cb1 = new Checkbox("Bold",true,cbg);
cb2 = new Checkbox("Italic",false,cbg);
tf.addActionListener(this);
b.addActionListener(this);
cb.addItemListener(this);
cb1.addItemListener(this);
cb2.addItemListener(this);
add(tf);
add(b);
add(ta);
add(cb);
add(cb1);
add(cb2);
f = ta.getFont();
ta.setFont(new Font(
f.getName(),
Font.BOLD,
f.getSize()
)
);
ta.setEditable(false);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
tf.setText("");
ta.setText("");
}
else
{
ta.append(tf.getText()+"\n");
tf.setText("");
}
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == cb)
ta.setEditable(cb.getState());
else if(ie.getSource() == cb1)
ta.setFont(
new Font(
f.getName(),
Font.BOLD,
f.getSize()
)
);
else
ta.setFont(
new Font(
f.getName(),
Font.ITALIC,
f.getSize()
)
);
}
}
Types of Layouts:
1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBag Layout
1.Flow Layout Manager:
The „Flow Layout‟ is the default layout manager for applets and panels. The
components are arranged from the upper left corner to the right bottom
corner. When there are number of components, they are arranged row wise
and left to right.
Example of FlowLayout:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
</applet> */
Button b1,b2,b3;
String msg="Layouts";
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
int val;
if(e.getSource() == b1)
val=FlowLayout.LEFT;
val=FlowLayout.RIGHT;
else
val=FlowLayout.CENTER;
msg="Layout - Center aligned";
setLayout(new FlowLayout(val));
validate();
repaint();
import java.applet.Applet;
import java.awt.*;
l.setBackground(Color.yellow);
add(l, BorderLayout.NORTH);
add(sb1, BorderLayout.WEST);
add(sb2, BorderLayout.EAST);
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
private Tab1 p;
public MyCardPanel()
p = new Tab1();
p1 = new Tab2();
p2 = new Tab3();
setBackground(activeColor);
setBounds(200,200,300,350);
addWindowListener(new Terminator());
controls.add(p);
controls.add(p1);
controls.add(p2);
border.add(controls, "North");
border.add(cardPanel, "Center");
add(border);
setVisible(true);
dispose();
public FirstCard()
setBackground(activeColor);
public SecondCard()
setBackground(activeColor);
public ThirdCard()
{
setBackground(activeColor);
public Tab1()
addMouseListener(new MouseAdapter()
card.show(cardPanel, "Card1");
setBackground(activeColor);
p1.setBackground(inactiveColor);
p2.setBackground(inactiveColor);
});
g.drawString("Tab 1",25,20);
}
public Tab2()
setBackground(inactiveColor);
addMouseListener(new MouseAdapter()
card.show(cardPanel, "Card2");
setBackground(activeColor);
p.setBackground(inactiveColor);
p2.setBackground(inactiveColor);
});
}
public void paint(Graphics g)
g.drawString("Tab 2",25,20);
public Tab3()
setBackground(inactiveColor);
addMouseListener(new MouseAdapter()
card.show(cardPanel, "Card3");
setBackground(activeColor);
p.setBackground(inactiveColor);
p1.setBackground(inactiveColor);
});
}
public void paint(Graphics g)
g.drawString("Tab 3",25,20);
/*
</applet>
*/
Example of GridLayout:
import java.applet.Applet;
import java.awt.*;
{
setLayout (new GridLayout(5, 3)); // 5 rows, 3 columns, no gaps
Example I:-
</applet> */
import java.applet.*;
{
public void init()
System.out.println("Componenet is initializing..");
System.out.println("Started..");
System.out.println("Stopped..");
System.out.println("Destroyed..");
Example II:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ap1 extends Applet implements ActionListener
Label lab;
TextField tf1,tf2,tf3;
Button btnresult;
tf1=new TextField(5);
tf2=new TextField(5);
tf3=new TextField(5);
btnresult.addActionListener(this);
add(lab);
add(tf1);
add(btnresult);
add(tf2);
add(tf3);
System.out.println("Hai.. ");
int x=Integer.parseInt(tf1.getText());
int y=Integer.parseInt(tf2.getText());
int z=x+y;
//tf3.setText(Integer.toString(z));
appletviewer ap1.java
appletviewer ap1.html */
Example I
import java.applet.*;
import java.awt.*;
</APPLET>*/
String Msg;
setForeground(Color.green);
setBackground(Color.black);
setFont(new Font("Times New Roman",Font.BOLD+Font.ITALIC,36));
Msg= getParameter("Message");
g.drawString("HelloWorld",50,100);
->AppletViewer HelloWorld.java
Example II
</applet>*/
import java.awt.*;
import java.applet.*;
{
Image img;
img=getImage(getCodeBase(),"2.jpg");
Example III
/*
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.lang.*;
setBackground(Color.blue);
g.setColor(Color.white);
String Functions
Java provides a class called String to represent text data.
Example:
Example I
import java.util.Scanner;
class A55
typeofwork=input.nextLine();
Methods:
The class String includes various methods to compare string, find length of string,
remove white spaces characters of string and much more.
length() charAt()
concat() compareTo()
indexOf() lastIndedOf()
replace() subString()
toString() Trim()
Example I:
class A56
System.out.println(empname.charAt(10));
}
Example II:
class A57
empname = "Aptech";
System.out.println(empname.concat(" Grafx"));
Example III
class A58
empname = "Aptech";
System.out.println(empname.compareTo("Aptech"));
}
}
Example IV
class A59
System.out.println(str);
str.append(5.0);
System.out.println(str);
Example V
class A60
System.out.println(str);
}
}
Example VI
class A61
}
STREAMS
Figure 2: Input Stream from Application to Source (Hard Disk and other memory
devices)
The data will be passed through streams from one device to another
device. So stream can be a sequence of data.
A program uses input stream to reads the data into a source where as
an output stream writes data from source to the application.
In java, Streams can be observed in the program that can be used to
handle data from a file or other similar sources.
There are various stream handling functions in Java, which are given
in a package called java.IO. But these can be classified into 2 types:
Byte Streams:
These are simple input and output streams which reads 8-bit
characters one at a time.
System.out class :
The standard output stream is used to typically display the output on the screen.
System.in class :
The standard input stream usually comes from the keyboard and is used for reading
characters of data.
System.err class :
This is standard error stream.
Example I
import java.io.*;
class FileDetails
{
Example II
import java.io.*;
class ReadFile
{
public static void main(String args[])throws IOException
{
//It reads the data in binary format(Binary Stream (ASII Codes))
FileInputStream f1 = new FileInputStream("one.txt");
int x = f1.read();
while(x!=-1)
{
System.out.print((char)x);
x=f1.read();
}
f1.close();
}
}
Example III
import java.io.*;
class SequenceDemo
{
public static void main(String args[])throws IOException
{
FileInputStream f1 = new FileInputStream("one.txt");
FileInputStream f2 = new FileInputStream("two.txt");
Example IV
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) {
try {
// Create a file writer
FileWriter fw = new FileWriter("three.txt");
// Write strings to the file
for(int i = 0; i < 12; i++) {
fw.write("Line " + i + "\n");
}
// Close file writer
fw.close();
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
Example V
import java.io.*;
class BufferedInputStreamDemo {
public static void main(String args[]) {
try {
Example VI
import java.io.*;
class SequenceDemo
{
public static void main(String args[])throws IOException
{
FileInputStream f1 = new FileInputStream("one.txt");
FileInputStream f2 = new FileInputStream("two.txt");
SequenceInputStream sis = new SequenceInputStream(f1,f2);
int x = sis.read();
while(x!=-1)
{
System.out.print((char)x);
x=sis.read();
}
sis.close();
f1.close();
f2.close();
}
}