Java Programming Notes For VBSPU 3rd Semester PDF
Java Programming Notes For VBSPU 3rd Semester PDF
Java Programming Notes For VBSPU 3rd Semester PDF
Semester-3
BCA 304
Java Programming
(According to Purvanchal University Syllabus)
Unit – 1
Introduction to Java
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by
Oracle Corporation. It was developed by James Gosling and Patrick Naught
on. It is a simple programming language. Writing, compiling and debugging
a program is easy in java. It helps to create modular programs and reusable
code.
Java terminology
Before we start learning Java, let’s get familiar with common java terms.
This is generally referred as JVM. Before, we discuss about JVM let’s see the
phases of program execution. Phases are as follows: we write the program,
then we compile the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you
and me.
2) Compilation of program is done by javac compiler, javac is the primary
java compiler included in java development kit (JDK). It takes java program
as input and generates java byte code as output.
3) In third phase, JVM executes the byte code generated by compiler. This
is called program run phase.
bytecode
As discussed above, javac compiler of JDK compiles the java source code into
bytecode so that it can be executed by JVM. The bytecode is saved in a .class file
by compiler.
(Java Runtime Environment), compilers and various tools like JavaDoc, Java
debugger etc.
In order to create, compile and run Java program you would need JDK installed on
your computer.
Compiler (javac) converts source code (.java file) to the byte code (.class
file). As mentioned above, JVM executes the byte code produced by
compiler. This byte code can run on any platform such as Windows, Linux,
and Mac OS etc. Which means a program that is compiled on windows can
run on Linux and vice-versa?
Each operating system has different JVM; however the output they produce
after execution of byte code is same across all operating systems. That is
why we call java as platform independent language.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Object- An entity that has state and behavior is known as an object e.g. chairs,
bike, marker, pen, table, car etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
3. Simple
4. Robust Language
5. Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why
several security flaws like stack corruption or buffer overflow is impossible
to exploit in Java.
6. Java is distributed
7. Multithreading
Keywords–
Keywords are words that have already been defined for Java compiler. They
have special meaning for the compiler. Java Keywords must be in your
information because you cannot use them as a variable, class or a method
name.
Constants–
Constants in Java. A constant is a variable which cannot have its value
changed after declaration. It uses the 'final' keyword.
Syntax
modifier final dataType variableName = value; //global constant
For example: Here num is a variable and int is a data type. We will discuss the
data type in next tutorial so do not worry too much about it, just understand
that int data type allows this num variable to hold integer values. You can
read data types here but I would recommend you to finish reading this guide
before proceeding to the next one.
int num;
Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
char ch;
int number;
...
ch = 'A';
number = 100;
Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
Instance variable
Each instance (objects) of class has its own copy of instance variable. Unlike static
variable, instance variables have their own separate copy of instance variable. We
have changed the instance variable value using object obj2 in the following
program and when we displayed the variable using all three objects, only the obj2
value got changed, others remain unchanged. This shows that they have their
own copy of instance variable.
Local Variable
These variables are declared inside method of the class. Their scope is limited to
the method which means that You can’t change their values and access them
outside of the method.
Data types
Data type defines the values that a variable can take, for example if a variable has
int data type, it can only take integer values. In java we have two categories of
data type: 1) Primitive data types 2) Non-primitive data types – Arrays and Strings
are non-primitive data types.
Java is a statically typed language. A language is statically typed, if the data type
of a variable is known at compile time. This means that you must specify the type
of the variable (Declare the variable) before you can use it.
byte, short, int and long data types are used for storing whole numbers.
boolean data type is used for variables that holds either true or false.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
num2 = num1;
System.out.println("= Output: "+num2);
num2 += num1;
System.out.println("+= Output: "+num2);
num2 -= num1;
System.out.println("-= Output: "+num2);
num2 *= num1;
System.out.println("*= Output: "+num2);
num2 /= num1;
System.out.println("/= Output: "+num2);
num2 %= num1;
System.out.println("%= Output: "+num2);
}
}
Output:
= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0
3) Auto-increment and Auto-decrement Operators
++ and —
num++ is equivalent to num=num+1;
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and
it would return false if b1 is true.
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
}
}
Output:
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if
either bit is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if
they are not equal, else it returns 0. In our example it would return 29 which is
equivalent to 00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0.
In our example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left
bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is
equivalent to 00101100
num1 >> 2 is right shift operator that moves the bits to the right, discards the far
right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is
equivalent to 00000010
result = ~num1;
System.out.println("~num1: "+result);
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the
result.
Syntax:
num2: 200
num2: 100
Operator Precedence in Java
For More Information go to www.dpmishra.com
19
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Multiplicative
* /%
Additive
+ –
Shift
<< >> >>>
Relational
> >= < <=
Equality
== !=
Bitwise AND
&
Bitwise XOR
^
Bitwise OR
|
Logical AND
&&
Logical OR
||
Ternary
?:
Assignment
= += -= *= /= %= > >= < <= &= ^= |=
Expressions
Expressions are essential building blocks of any Java program, usually
created to produce a new value, although sometimes an expression simply
assigns a value to a variable. Expressions are built using values, variables,
operators and method calls.
An expression is a statement that can convey a value. Some of the most
common expressions are mathematical, such as in the following source
code example:
int x = 3;
int y = x;
int z = x * y;
1 if statement
2 if...else statement
3 nested if statement
4 switch statement
?: Operator-
We have covered conditional operator ? : in the previous chapter which can be
used to replace if...else statements. It has the following general form −
Loops-
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of
the programming languages −
1 while loop
2 for loop
3 do...while loop
Like a while statement, except that it tests the condition at the end
of the loop body.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
Labeled loop-
According to nested loop, if we put break statement in inner loop, compiler will
jump out from inner loop and continue the outer loop again. What if we need to
jump out from the outer loop using break statement given inside inner loop?
The answer is, we should define lable along with colon(:) sign before loop.
Introducing Classes
Object and methods:
Defining a class-
Java is an Object-Oriented Language. As a language that has the Object-Oriented
feature, Java supports the following fundamental concepts −
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
// body
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is
shown in the following syntax −
Syntax
Creating objects-
In this example, we have created a Student class which has two data members id
and name. We are creating the object of the Student class by new keyword and
printing the object's value.
File: Student.java
Output:
0
null
Constructors-
Constructor is a block of code that initializes the newly created object. A
constructor resembles an instance method in java but it’s not a method as it
doesn’t have a return type. In short constructor and method are different(More
on this at the end of this guide). People often refer constructor as special type of
method in Java.
Constructor has same name as the class and looks like this in a java code.
Here we have created an object obj of class Hello and then we displayed the
instance variable nameof the object. As you can see that the output
is BeginnersBook.com which is what we have passed to the name during
initialization in constructor. This shows that when we created the object obj the
constructor got invoked. In this example we have used this keyword, which refers
to the current object, object obj in this example. We will cover this keyword in
detail in the next tutorial.
BeginnersBook.com
Class Inheritance-
A class that is derived from another class is called subclass and inherits all fields
and methods of its superclass. In Java, only single inheritance is allowed and thus,
every class can have at most one direct superclass. A class can be derived from
another classthat is derived from another class and so on.
Unit – 2
Arrays and Strings
Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
Creating an array-
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
It creates an array using new dataType[arraySize].
It assigns the reference of the newly created array to the variable
arrayRefVar.
2-D Array-
The Two Dimensional Array in Java programming language is nothing but an
Array of Arrays. If the data is linear we can use the One Dimensional Array
but to work with multi-level data we have to use Multi-Dimensional Array.
Two Dimensional Array in Java is the simplest form of Multi-Dimensional
Array. In Two Dimensional Array, data is stored in row and columns and we
can access the record using both the row index and column index (like an
Excel File).
Square brackets is used to declare a String array. There are two ways of using it.
The first one is to put square brackets after the String reserved word. For
example:
String[] thisIsAStringArray;
Another way of declaring a String Array is to put the square brackers after the
name of the variable. For example:
String thisIsAStringArray[];
Both statements will declare the variable "thisIsAStringArray" to be a String Array.
Note that this is just a declaration, the variable "thisIsAStringArray" will have the
value null. And since there is only one square brackets, this means that the
variable is only a one-dimensional String Array. Examples will be shown later on
how to declare multi-dimensional String Arrays.
Comparison Chart
BASIS FOR
STRING STRINGBUFFER
COMPARISON
immutable.
concatenation. concatenation.
Wrapper classes-
classes
A Wrapper class is a class whose object wraps or contains a primitive data
types. When we create an object to a wrapper class, it contains a field and
in this field, we can store a primitive data types. In other words, we can
wrap a primitive value into a wrapper class object.
Primitive Data types and their Corresponding Wrapper class
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
another.
information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is
known as superclass
ass (base class, parent class).
Basic types-
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple
inheritance. This means that a class cannot extend more than one class.
Therefore following is illegal −
Example
However, a class can implement one or more interfaces, which has helped
Java get rid of the impossibility of multiple inheritance.
Using super-
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where
the super keyword is used.
It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables
we use super keyword as shown below.
super.variable
super.method();
Object class-
Every class in Java is directly or indirectly derived from the Object class. If a
Class does not extend any other class then it is direct
child class of Object and if extends other class then it is an indirectly
derived. Therefore the Object class methods are available to all Java
classes.
Comparison Chart
BASIS FOR
PACKAGES INTERFACES
COMPARISON
together.
BASIS FOR
PACKAGES INTERFACES
COMPARISON
Access protection-
Protected Access Modifier - Protected. Variables, methods, and
constructors, which are declared protected in a superclass can be accessed
only by the subclasses in other package or any class within the package of
the protected members' class.
Extending interfaces-
An interface can extend another interface in the same way that a class can
extend another class. The extends keyword is used to extend an interface, and
the child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
Example
// Filename: Sports.java
// Filename: Football.java
// Filename: Hockey.java
The Hockey interface has four methods, but it inherits two from Sports; thus, a
class that implements Hockey needs to implement all six methods. Similarly, a
class that implements Football needs to define the three methods from Football
and the two methods from Sports.
Packages-
A package as the name suggests is a pack(group) of classes, interfaces and other
packages. In java we use packages to organize our classes and interfaces. We have
two types of packages in Java: built-in packages and the packages we can create
(also known as user defined package). In this guide we will learn what are
packages, what are user-defined packages in java and how to use them.
In java we have several built-in packages, for example when we need user input,
we import a package like this:
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
As mentioned in the beginning of this guide that we have two types of packages in
java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are
known as built-in packages.
For More Information go to www.dpmishra.com
42
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Unit – 3
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be
maintained.
import java.io.File;
import java.io.FileReader;
System.out.println(num[5]);
Errors − These are not excep ons at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your code
because you can rarely do anything about an error. For example, if a stack
overflow occurs, an error will arise. They are also ignored at the time of
compilation.
Uncaught exceptions-
If you do not handle a runtime exception in your program, the default behavior
will be to terminate the program and dump the call stack trace on the console.
Java provides an elegant mechanism of handling Runtime Exceptions that you
might have not handled in your program. UncaughtExceptionHandler can be
defined at three levels. From highest to lowest they are:
1. Thread.setDefaultUncaughtExceptionHandler
2. ThreadGroup.uncaughtException
3. Thread.setUncaughtExceptionHandler
Uncaught exception handling is controlled first by the thread, then by the
thread’s Thread Group object and finally by the default uncaught exception
handler.
Throw-
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated one or an exception that
you just caught, by using the throw keyword.
Example
import java.io.*;
// Method implementation
Final-
The finally block follows a try block or a catch block. A finally block of code
always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you
want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following
syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Built in exception-
Java defines several exception classes inside the standard package java.lang.
Java defines several other types of exceptions that relate to its various class
libraries. Following is the list of Java Unchecked RuntimeException.
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible type.
4 ClassCastException
Invalid cast.
5 IllegalArgumentException
Illegal argument used to invoke a method.
6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
7 IllegalStateException
Environment or application is in incorrect state.
8 IllegalThreadStateException
Requested operation not compatible with the current thread state.
9 IndexOutOfBoundsException
Some type of index is out-of-bounds.
10 NegativeArraySizeException
Array created with a negative size.
11 NullPointerException
Invalid use of a null reference.
12 NumberFormatException
Invalid conversion of a string to a numeric format.
13 SecurityException
Attempt to violate security.
14 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15 UnsupportedOperationException
An unsupported operation was encountered.
Example
import java.io.*;
this.amount = amount;
return amount;
Multithreaded programming
For More Information go to www.dpmishra.com
49
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Fundamentals-
Java is a multi-threaded programming language which means we can
develop multi-threaded program using Java. A multi-threaded program
contains two or more parts that can run concurrently and each part can
handle a different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs.
Timed Waiting − A runnable thread can enter the med wai ng state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when
it completes its task or otherwise terminates.
Thread class-
Thread class is the main class on which Java's Multithreading system is based.
Thread class, along with its companion interface Runnable will be used to create
and run threads for utilizing Multithreading feature of Java.
Runnable interface-
If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −
Step 1
As a first step, you need to implement a run() method provided by
a Runnable interface. This method provides an entry point for the thread and
you will put your complete business logic inside this method. Following is a
simple syntax of the run() method −
void start();
Example
Here is an example that creates a new thread and starts running it −
private Thread t;
threadName = name;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
if (t == null) {
t.start ();
R1.start();
R2.start();
Interthread communication-
These methods have been implemented as final methods in Object, so they are
available in all the classes. All three methods can be called only from within
a synchronized context.
Be aware that the latest versions of Java has deprecated the usage of suspend( ),
resume( ), and stop( ) methods and so you need to use available alternatives.
Unit – 4
For More Information go to www.dpmishra.com
56
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Input/output
Basics-
The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java. All these streams represent an input source and
an output destination. The stream in the java.io package supports many data
such as primitives, object,
t, localized characters, etc.
Stream-
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for wri ng data to a
destination.
Java provides strong but flexible support for I/O related to files and networks but
this tutorial covers very basic functionality related to streams and I/O. We will
see the most commonly used examples one by one −
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}
For More Information go to www.dpmishra.com
58
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to
copy an input file (having unicode characters) into an output file −
Example
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
Predefined streams-
As you know, all Java programs automatically import the java.lang package.
This package defines a class called System, which encapsulates several
aspects of the run-time environment. Among other things, it contains three
predefined stream variables, called in, out, and err. These fields are
declared as public, final, and static within System. This means that they can
be used by any other part of your program and without reference to a
specific System object.
FileOutputStream, which
The two important streams are FileInputStream and FileOutputStream
would be discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using
the keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream
object to read the file −
Once you have InputStream object in hand, then there is a list of helper methods
which can be used to read to stream or to do other operations on the stream.
Networking
Basics-
Authenticator
Inet6Address
Ser verSocket
CacheRequest
InetAddress
Socket
CacheResponse
InetSocketAddress
SocketAddress
ContentHandler
Inter faceAddress (Added by SocketImpl
Java SE 6.)
CookieHandler
JarURLConnection
SocketPermission
CookieManager (Added by MulticastSocket
URI
Java SE 6.)
DatagramPacket
NetPermission
URL
Unit – 5
Event Handling
Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism have the code which is
known as event handler that is executed when an event occurs. Java Uses
the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.Let's have a brief
introduction to this model.
Different mechanism-
Steps involved in event handling
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and
information about the source and the event get populated with in same
object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.
Points to remember about listener
In order to design a listener class we have to develop some listener
interfaces.These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your
class can not act as a listener class for a source object.
Event classes-
The Event classes represent the event. Java provides us various Event
classes but we will discuss those which are more frequently used.
Following is the list of commonly used event classes.
1 AWTEvent
It is the root event class for all AWT events. This class and its
subclasses supercede the original java.awt.Event class.
2 ActionEvent
The ActionEvent is generated when button is clicked or the item of a
list is double clicked.
3 InputEvent
The InputEvent class is root event class for all component-level input
events.
4 KeyEvent
On entering the character the Key event is generated.
5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted by
Adjustable objects.
9 ComponentEvent
The object of this class represents the change in state of a window.
10 ContainerEvent
The object of this class represents the change in state of a window.
11 MouseMotionEvent
The object of this class represents the change in state of a window.
12 PaintEvent
The object of this class represents the change in state of a window.
1 ActionListener
This interface is used for receiving the action events.
2 ComponentListener
This interface is used for receiving the component events.
3 ItemListener
This interface is used for receiving the item events.
4 KeyListener
This interface is used for receiving the key events.
5 MouseListener
This interface is used for receiving the mouse events.
6 TextListener
This interface is used for receiving the text events.
7 WindowListener
This interface is used for receiving the window events.
8 AdjustmentListener
This interface is used for receiving the adjusmtent events.
9 ContainerListener
This interface is used for receiving the container events.
10 MouseMotionListener
This interface is used for receiving the mouse motion events.
11 FocusListener
This interface is used for receiving the focus events.
1 FocusAdapter
An abstract adapter class for receiving focus events.
2 KeyAdapter
An abstract adapter class for receiving key events.
3 MouseAdapter
An abstract adapter class for receiving mouse events.
4 MouseMotionAdapter
An abstract adapter class for receiving mouse motion events.
5 WindowAdapter
Inner Classes-
Java inner class or nested class is a class which is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place so that
it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private data
members and methods.
Graphics Controls
Sr. Control & Description
No.
1 Graphics
It is the top level abstract class for all graphics contexts.
2 Graphics2D
It is a subclass of Graphics class and provides more sophisticated
control over geometry, coordinate transformations, color
management, and text layout.
3 Arc2D
Arc2D is the abstract superclass for all objects that store a 2D arc
defined by a framing rectangle, start angle, angular extent (length of
the arc), and a closure type (OPEN, CHORD, or PIE).
4 CubicCurve2D
The CubicCurve2D class is the abstract superclass fpr all objects which
store a 2D cubic curve segment and it defines a cubic parametric
curve segment in (x,y) coordinate space.
5 Ellipse2D
The Ellipse2D is the abstract superclass for all objects which store a
2D ellipse and it describes an ellipse that is defined by a framing
rectangle.
6 Rectangle2D
The Rectangle2D class is an abstract superclass for all objects that
store a 2D rectangle and it describes a rectangle defined by a location
(x,y) and dimension (w x h).
TextField
The object of a TextField class is a text component that allows the editing of a
single line text. It inherits TextComponent class.
1. import java.awt.*;
2. class TextFieldExample{
3. public static void main(String args[]){
4. Frame f= new Frame("TextField Example");
5. TextField t1,t2;
6. t1=new TextField("Welcome to Javatpoint.");
7. t1.setBounds(50,100, 200,30);
8. t2=new TextField("AWT Tutorial");
9. t2.setBounds(50,150, 200,30);
10. f.add(t1); f.add(t2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14.}
15.}
Menu Hiearchy
Handling Image-
For More Information go to www.dpmishra.com
73
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
Java applet-
For More Information go to www.dpmishra.com
74
Keep Learning with us VBSPU BCA 3rd sem. JAVA Programming
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following −
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not
define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser.
The security of an applet is often referred to as sandbox security,
comparing the applet to a child playing in a sandbox with various rules that
must be followed.
Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.