Unit 1 Part 2
Unit 1 Part 2
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired
by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few
implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any Java Virtual
Machine.
It is used for:
Features of Java
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that played an
important role in moulding out the final form of this outstanding language. Those features are:
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and
ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner
way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily extendedas it
is based on Object Model. Following are some basic concept of OOP's.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error
checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage Collector and
Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine with
Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on computer networks. Java
has a special class library for communicating using TCP/IP protocols. Creating network
connections is very much easy in Java as compared to C/C++.
What is a Variable?
When we want to store any information, we store it in an address of the computer. Instead of
remembering the complex address where we have stored our information, we name that
address.The naming of an address is known as variable. Variable is the name of memory
location.
In other words, variable is a name which is used to store a value of any type during program
execution.
datatype variableName;
Here, datatype refers to type of variable which can any like: int, float etc. and variableName
can be any like: empId, amount, price etc.
Java Programming language defines mainly three kind of variables.
1. Instance Variables
2. Static Variables (Class Variables)
3. Local Variables
Once a primitive data type has been declared its type can never change, although in
most casesits value can change. These eight primitive type can be put into four
groups
Integer
This group includes byte, short, int, long
byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default
value zero.example: byte b=10;
short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767.
Default value zero. example: short s=11;
int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to
2147483647.Default value zero. example: int i=10;
long : It is 8 bytes(64-bits) integer data type. Value range from -
9,223,372,036,854,775,808 to9,223,372,036,854,775,807. Default value zero.
example: long l=100012;
Example:
Lets create an example in which we work with integer type data and we can get idea
how to usedatatype in the java program.
package corejava;
}
}
b= 20 s= 20 i= 20 l= 20
Floating-Point Number
This group includes float, double
float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double db=11.123;
Example:
In this example, we used floating point type and declared variables to hold floating values.Floating
type is useful to store decimal point values.
f= 20.25 d= 20.25
Characters
This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535.
example: charc='a';
Char Type Example
Char type in Java uses 2 bytes to unicode characters. Since it works with unicode then we can
store alphabet character, currency character or other characters that are comes under the unicode
set.
S&$
Boolean
This group represent boolean, which is a special type for representing true/false values. They are
defined constant of the language. example: boolean b=true;
Boolean Type Example
Boolean type in Java works with two values only either true or false. It is mostly use in
conditional expressions to perform conditional based programming.
boolean f = false;
System.out.println(f);
true false
In object oriented system, we deal with object that stores properties. To refer those objects we
use reference types.
We will talk a lot more about reference data type later in Classes and Object lesson.
Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are
called Identifier. Identifier must follow some rules. Here are the rules:
Some valid identifiers are: int a, class Car, float amount etc.
Java Arrays
An array is a collection of similar data types. Array is a container object that hold values of
homogeneous type. It is also known as static data structure because size of an array must be
specified at the time of its declaration.
Array starts from zero index and goes to n-1 where n is length of the array.
In Java, array is treated as an object and stores into heap memory. It allows to store primitive
values or reference values.
Array can be single dimensional or multidimensional in Java.
Features of Array
● It is always indexed. Index begins from 0.
● It is a collection of similar data types.
● It occupies a contiguous memory location.
● It allows to access elements randomly.
Example :
int[ ] arr; char[ ]
arr; short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.
Initialization of Array
Initialization is a process of allocating memory to an array. At the time of initialization, we specify
the size of array to reserve memory area.
Initialization Syntax
class Demo
{
public static void main(String[] args)
{
int[] arr = new int[5];for(int x :
arr)
{
System.out.println(x);
}
}
}
00000
In the above example, we created an array arr of int type and can store 5 elements. We iterate
the array to access its elements and it prints five times zero to the console. It prints zero because
we did not set values to array, so all the elements of the array initialized to 0 by default.
Set Array Elements
We can set array elements either at the time of initialization or by assigning direct to its index.
int[] arr = {10,20,30,40,50};
Here, we are assigning values at the time of array creation. It is useful when we want to store static
data into the array.
or
arr[1] = 105
Here, we are assigning a value to array’s 1 index. It is useful when we want to store dynamic data into
the array.
Array Example
Here, we are assigning values to array by using both the way discussed above.
class Demo
{
public static void main(String[] args)
{
int[] arr = {10,20,30,40,50};
for(int x : arr)
{
System.out.println(x);
}
// assigning a value
arr[1] = 105;
System.out.println("element at first index: " +arr[1]);
}
}
Here, we are traversing array elements using loop and accessed an element randomly.
Note:-To find the length of an array, we can use length property of array object like:
array_name.length.
Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have multiple
rows and multiple columns unlike single dimensional array, which can have only onerow index.
It represent data into tabular form in which data is stored into row and columns.
Multi-Dimensional Array Declaration
datatype[ ][ ] arrayName;
Initialization of Array
datatype[ ][ ] arrayName = new int[no_of_rows][no_of_columns];
The arrayName is the name of array, new is a keyword used to allocate memory and no_of_rows
and no_of_columns both are used to set size of rows and columns elements.
Like single dimensional array, we can statically initialize multi-dimensional array as well.
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
Example:
class Demo
{
public static void main(String[] args)
{
int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
for(int i=0;i<3;i++)
{
for (int j = 0; j < 5; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
// assigning a value
System.out.println("element at first row and second column: "
+arr[0][1]);
}
}
Java Class
In Java everything is encapsulated under classes. Class is the core of Java language. It can be
defined as a template that describe the behaviors and states of a particular entity.
A class defines new data type. Once defined this new type can be used to create object of that
type.
Object is an instance of class. You may also call it as physical existence of a logical template
class.
In Java, to declare a class class keyword is used. A class contain both data and methods that
operate on that data. The data or variables defined within a class are called instance variables
and the code that operates on this data is known as methods.
Thus, the instance variables and methods are known as class members.
Rules for Java Class
A Java class can contains fields, methods, constructors, and blocks. Lets see a general structure
of a class.
Java class Syntax
The fields declared inside the class are known as instance variables. It gets memory when anobject
is created at runtime.
Methods in the class are similar to the functions that are used to perform operations andrepresent
behavior of an object.
After learning about the class, now lets understand what is an object.
Java Object
Object is an instance of a class while class is a blueprint of an object. An object represents theclass
and consists of properties and behavior.
Properties refer to the fields declared with in class and behavior represents to the methods available in
the class.
In real world, we can understand object as a cell phone that has its properties like: name, cost, color
etc and behavior like calling, chatting etc.
So we can say that object is a real world entity. Some real world objects are: ball, fan, car etc.There is
a syntax to create an object in the Java.
Lets see an example to create an object of class Student that we created in the above classsection.
Although there are many other ways by which we can create object of the class. we have covered
this section in details in a separate topics.
Methods in Java
Method in Java is similar to a function defined in other programming languages. Method describes
behavior of an object. A method is a collection of statements that are grouped together to perform an
operation.
For example, if we have a class Human, then this class should have methods like eating(), walking(),
talking() etc, which describes the behavior of the object.
Declaring method is similar to function. See the syntax to declare the method in Java.
return-type methodName(parameter-list)
{
//body of method
}
return-type refers to the type of value returned by the method.
Method may have an optional return statement that is used to return value to the caller function.
Example of a Method:
Lets understand the method by simple example that takes a parameter and returns a string value.
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in
method heading.
Inheritance defines is-a relationship between a Super class and its Sub class.
Purpose of Inheritance
1. It promotes the code reusabilty i.e the same methods and variables which are defined in a
parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Disadvantages of Inheritance
1. Main disadvantage of using inheritance is that the two classes (parent and child class)
gets tightly coupled.
2. This means that if we change code of parent class, it will affect to all the child classes
which is inheriting/deriving the parent class, and hence, it cannot be independent of
each other.
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
We can get a quick view of type of inheritance from the below image.
Single Inheritance
When a class extends to another class then it forms single inheritance. In the below example, we
have two classes in which class A extends to class B that forms single inheritance.
class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}
}
}
Multilevel Inheritance
When a class extends to another class that also extends some other class forms a multilevel
inheritance. For example a class C extends to class B that also extends to class A and all the data
members an methods of class A and B are now accessible in class C.
Example:
class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}
Hierarchical Inheritance
When a class is extended by two or more classes, it forms hierarchical inheritance. For example,class
B extends to class A and class C also extends to class A in that case both B and C share properties of
class A.
class A{
int a = 10; void
show() {
System.out.println("a = "+a);
}
}
Java Package
Package is a collection of related classes. Java uses package to group related classes, interfaces and
sub-packages.
We can assume package as a folder or a directory that is used to store similar files.
In Java, packages are used to avoid name conflicts and to control access of class, interface and
enumeration etc. Using package it becomes easier to locate the related classes and it also provides a
good structure for projects with hundreds of classes and other files.
Lets understand it by a simple example, Suppose, we have some math related classes andinterfaces
then to collect them into a simple place, we have to create a package.
Types Of Package
Package can be built-in and user-defined, Java provides rich set of built-in packages in form of
API that stores related classes and sub-packages.
● Built-in Package: math, util, lang, i/o etc are the example of built-in packages.
● User-defined-package: Java package created by user to categorize their project's classes and interface
are known as user-defined packages.
How to Create a Package
Creating a package in java is quite easy, simply include a package command followed by name
of the package as the first statement in java source file.
Java uses file system directories to store packages. For example the .javafile for any class you define to
be part of mypack package must be stored in a directory called mypack.
Example of Java packages
Now lets understand package creation by an example, here we created a leanjava package that stores
the FirstProgram class file.
//save as FirstProgram.javapackage
learnjava;
public class FirstProgram{
public static void main(String args[]) { System.out.println("Welcome to package example");
}
}
Example
In this example, we are creating a class A in package pack and in another class B, we are accessing it
while creating object of class A.
//save by A.java
package pack; public
class A {
public void msg() { System.out.println("Hello");
}
}
//save by B.javapackage
mypack; class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified nameobj.msg();
}
}
Java Interfaces
Interface is a concept which is used to achieve abstraction in Java. This is the only way by which we
can achieve full abstraction. Interfaces are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body. It can have When you
create an interface it defines what a class can do without saying anything about how the class will do
it.
It can have only abstract methods and static fields. However, from Java 8, interface can have
default and static methods and from Java 9, it can have private methods as well.
When an interface inherits another interface extends keyword is used whereas class use
implements keyword to inherit an interface.
Advantages of Interface
Syntax:
interface interface_name {
// fields
// abstract/private/default methods
}
Suppose we run a program to read data from a file and if the file is not available then the program
will stop execution and terminate the program by reporting the exception message.
The problem with the exception is, it terminates the program and skip rest of the execution that means
if a program have 100 lines of code and at line 10 an exception occur then program will terminate
immediately by skipping execution of rest 90 lines of code.
To handle this problem, we use exception handling that avoid program termination and continue the
execution by skipping exception code.
Java exception handling provides a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
Uncaught Exceptions
Lets understand exception with an example. When we don't handle the exceptions, it leads to
unexpected program termination. In this program, an ArithmeticException will be throw due todivide
by zero.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an exception
and then throw it. As we don't have any mechanism for handling exception in the above program,
hence the default handler (JVM) will handle the exception and will print the details of the exception
on the terminal.
Java Exception
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsiblefor
doing something about the exception is called an exception handler
How to Handle Exception
Java provides controls to handle exception in the program. These controls are listed below.
● Checked Exception
The exception that can be predicted by the JVM at the compile time for example : File that
need to be opened is not found, SQLException etc. These type of exceptions must bechecked
at compile time.
● Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException class. Unchecked
exception are ignored at compile time and checked at runtime. For example :
ArithmeticException, NullPointerException, Array Index out of Bound exception.
Unchecked exceptions are checked at runtime.
● Error
Errors are typically ignored in code because you can rarely do anything about an error. For
example, if stack overflow occurs, an error will arise. This type of error cannot be handled in
the code.
Java Exception class Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
● Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
● RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
● Exceptions of type Error are used by the Java run-time system to indicate errors having
to do with the run-time environment, itself. Stack overflow is an example of such an
error.
try
{
// suspected code
}
catch(Exception1 e)
{
// handler code
}
catch(Exception2 e)
{
// handler code
}
Now lets see an example to implement the multiple catch block that are used to catch
possibleexception.
The multiple catch blocks are useful when we are not sure about the type of exception during
program execution.
Examples for Multiple Catch blocks
In this example, we are trying to fetch integer value of an Integer object. But due to bad input,
itthrows number format exception.
class Demo{
public static void main(String[] args) {
try
{
Integer in = new Integer("abc");in.intValue();
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}
An instance of Thread class is just an object, like any other object in java. But a thread of execution
means an individual "lightweight" process that has its own call stack. In java eachthread has its own
call stack.
Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory and perform context switching
aswell that helps to share the memory and reduce time of switching between threads.
Multitasking
Multitasking is a process of performing multiple tasks simultaneously. We can understand it by
computer system that perform multiple tasks like: writing data to a file, playing music, downloading
file from remote server at the same time.
We can create thread either by extending Thread class or implementing Runnable interface.
Bothincludes a run method that must be override to provide thread implementation.
It is recommended to use Runnable interface if you just want to create a thread but can
useThread class for implementation of other thread functionalities as well.
We will discuss it in details in our next topics.
The mainthread
When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main
method.This thread is called as main thread. Although the main thread is automatically created,
you can control it by obtaining a reference to it by calling currentThread() method.
class MainThread
{
public static void main(String[] args)
{
Thread t = Thread.currentThread(); t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
1. New : A thread begins its life cycle in the new state. It remains in this state until the start()
method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this
stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
tomake input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your
codeunderstand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are
These two abstract classes have several concrete classes that handle unicode character.
Reading Characters
read()method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));char c = (char)br.read();
//Reading character
}
}
import java.io.*;class
MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new
BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser. This is the first
Java program that can run over the network using the browser. Applet is typically embedded
inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed on an
Internet server, transported over Internet, and can be automatically installed and run as apart of a
web document.
After a user receives an applet, the applet can produce a graphical user interface. It has limited
access to resources so that it can run complex computations without introducing the risk of
viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
JVM creates an instance of the applet class and invokes init()method to initialize an Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.
Lifecycle of Java Applet
Following are the stages in Applet
1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
A Simple Applet
import java.awt.*; import
java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awtand java.applet.
java.awt.*imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. java.applet.* imports the applet package, which contains the class Applet.
Every applet that you create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that is
outside the program.Every Applet application must declare a paint() method. This method is
defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about applet
application is that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main()method.
Advantages of Applets
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
● init() : init() is the first method to be called. This is where variable are initialized. This method
iscalled only once during the runtime of applet.
● start() : start() method is called after init(). This method is called to restart an applet after it has
been stopped.
● stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
● destroy() : destroy() method is called when your applet needs to be removed completely from
memory.
1. Using equals()method
2. Using ==operator
3. By CompareTo()method
Example
It compares the content of the strings. It will return true if string matches, else returns false.
public class Demo{
public static void main(String[] args) {String s = "Hell";
String s1 = "Hello";String s2
= "Hello";
boolean b = s1.equals(s2); //true
System.out.println(b);
b= s.equals(s1) ; //false
System.out.println(b);
}
}
true false
Event Handling
AWT is the foundation upon which Swing is made i.e Swing is a improved GUI API that extendsthe
AWT. But now a days AWT is merely used because most GUI Java programs are implemented using
Swing because of its rich implementation of GUI controls and light-weightednature.
Creating a Frame
There are two ways to create a Frame. They are,
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible
Example:
Lets take an example to create a button and it to the frame by providing coordinates.
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is
allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
import java.awt.*;class
LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo"); Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e
true or false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it
returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");Checkbox ckbox1 = new
Checkbox("Yes", true); ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1); checkB_f.add(ckbox2);
checkB_f.setSize(400,400); checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
AWT Layouts:
Introduction
Layout means the arrangement of components within the container. In other way we can say that
placing the components at a particular position within the container. The task of layouting the
controls is done automatically by the Layout Manager.
Layout Manager
The layout manager automatically positions all the components within the container. If we do not
use layout manager then also the components are positioned by the default layout manager. It is
possible to layout the controls by hand but it becomes very difficult because of the following two
reasons.
Java provide us with various layout manager to position the controls. The properties like size,shape
and arrangement varies from one layout manager to other layout manager. When the size of the applet
or the application window changes the size, shape and arrangement of the components also changes
in response i.e. the layout managers adapt to the dimensions of appletviewer or the application
window.
The layout manager is associated with every Container object. Each layout manager is an object of the
class that implements the LayoutManager interface.
Sr.
Interface & Description
No.
LayoutManager
1 The LayoutManager interface declares those methods which need to be implemented by the
class whose object will act as a layout manager.
LayoutManager2
1 The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
CardLayout
2 The CardLayout object treats each component in the container as a card. Only one card is visible
at a time.
FlowLayout
3
The FlowLayout is the default layout.It layouts the components in a directional flow.
GridLayout
4
The GridLayout manages the components in form of a rectangular grid.
GridBagLayout
5 This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of
same size.