Вы находитесь на странице: 1из 33

UNIT-1(PART-2)

Introduction
Java is a programming language and computing platform first released by Sun
Microsystems in 1995.
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is
known as a platform. Since Java has its own runtime environment (JRE) and API,
it is called platform.

Features of JAVA
Following are the features of Java:

1.Simple
2.Object-Oriented
3.Portable
4.Platform independent
5.Secured
6.Robust
7.Architecture neutral
8.Dynamic
9.Interpreted
10.High Performance
11.Multithreaded
12.Distributed
1.Simple
According to Sun, Java language is simple because:

Syntax is based on C++ (so easier for programmers to learn it after C++)
Removed many confusing and/or rarely-used features e.g. explicit pointers,
operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java

2.Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3.Platform-independent
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms.
It has two components:
1.Runtime Environment
2.API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris,
Mac/OS etc. Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

4.Secured
Java is secured because:
a) No explicit pointer
C/C++ language uses pointers, which may cause unauthorized access to memory
blocks when other programs get the pointer values. Unlike conventional C/C++
language, Java never uses any kind of pointers. Java has its internal mechanism
for memory management. It only gives access to the data to the program if has
appropriate verified authorization.
b)Byte code
Every time when a user compiles the Java program, the Java compiler creates a
class file with Bytecode, which are tested by the JVM at the time of
program execution for viruses and other malicious files.

c)Protection from security attacks


It allows developers to declare classes or methods as FINAL. We all know that
any class or method declared as final can’t be overridden, which helps
developers to protect code from security attacks like creating a subclass and
replacing it with the original class and override methods.

5.Robust

Robust simply means strong. Java uses strong memory management. There are
lack of pointers that avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in
java. All these points makes java robust.

6.Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is
fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. But in java, it
occupies 4 bytes of memory for both 32 and 64 bit architectures.

7.Portable
We may carry the java byte code to any platform.

8.High-performance
Java is faster than traditional interpretation since byte code is "close" to native
code still somewhat slower than a compiled language (e.g., C++)
8.Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.

9.Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-
media, Web applications etc.

Difference between JDK, JRE and JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification


that provides runtime environment in which java byte code can be executed.
JVM is:
1.A specificationwhere working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
2.An implementation Its implementation is known as JRE (Java Runtime
Environment).
3.Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

JVMs are available for many hardware and software platforms. JVM, JRE and JDK
are platform dependent because configuration of each OS differs. But, Java is
platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE (Java Runtime Environment)
JRE is an acronym for Java Runtime environment.It is used to provide runtime
environment.It is the implementation of JVM. It physically exists. It contains set
of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides
Sun Micro Systems.
The jre directory contains the Java Runtime Environment facilities that are used
when you execute a
Java program. The classes in the Java libraries are stored in the jre\lib directory.
JDK(Java Development Kit.)

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

Object and Class in Java


Object
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc.
An object has three characteristics:
state:represents data (value) of an object.
behavior:represents the behavior (functionality) of an object such as
deposit, withdraw etc.
identity:Object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. But, it is used internally by the
JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as
its state. It is used to write, so writing is its behavior.
Object is a run time entity.
Object is an entity which has state and behavior.
Object is an instance of a class.

Class
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
A class in Java can contain:
fields
methods
constructors
Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.
Examples
1.class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Explanation:
class keyword is used to declare a class in java.
Public keyword is an access modifier which represents visibility, it means
it is visible to all.
Static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no need
to create object to invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.
Void is the return type of the method, it means it doesn't return any value.
Main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.

2. class Student{
int id=10;
String name=”Sachin”;

public static void main(String args[]){


Student s1=new Student();//creating an object of Student,The new keyword is
used to allocate memory at run time. All objects get memory in Heap
memory area.
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

Data types in java

Variables in Java
There are three types of variables in java:-
local
instance
static

1) Local Variable
A variable which is declared inside the method is called local variable.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3)Static Variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of
employees,college name of students etc.
The static variable gets memory only once in class area at the time of
class loading.

Advantage of static variable


It makes your program memory efficient (i.e. it saves memory).
Example of static variable
class Student8{
int rollno;
String name;
static String college="ITS";
Student8(int r,String n){
rollno=r;
name=n;
}
void display(){
System.out.println(rollno+""+name+""+college);}
public static void main(String args[]){
Student8 s1=new Student8(111,"Karan");
Student8 s2=new Student8(222,"Aryan");
s1.display();
s2.display();)}

Example of all types of variables


class A{
int data=50;//instance
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}
Method in java
In order to call a method we need object of the class in which that method is
declared.
1.Program to find minimum of numbers(method is not static)
public class ExampleMinNumber {
public void minFunction(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
System.out.println(min);
}

public static void main(String[] args) {


int a = 11;
int b = 6;
ExampleMinNumber mn=new ExampleMinNumber();
mn.minFunction(a, b);
}
}
2. Program to find rank (method is static)
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
} }}

3.Program to find minimum of numbers(method is static and returns a


value)
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
OOPs (Object Oriented Programming System)
Concepts
Following are the Oops concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
1.Object
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.

2.Class
Collection of objects is called class. It is a logical entity.

3.Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Class Animal{
String food=”nonveg”;
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
String drink=”milk”;
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
System.out.println(d.food);

d.bark();
d.eat();
}}

4.Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g. shape
or rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks
woof etc.There are two types of polymorphism compiletime
polymorphism(method overloading) and runtime polymorphism(method
overriding).
Method overloading
If a class has multiple methods having same name but different signatures, it is
known as Method Overloading. Different signatures means the parameters of
methods may differ in:
a) no of arguments
b) their data types
b) their sequence
Example
1.differ in no of arguments
class Adder{
public int add(int a,int b){return a+b;}
public int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Adder r=new Adder();
System.out.println(r.add(11,11));
System.out.println(r.add(11,11,11));
}}

2. differ in data types


Example
class Adder{
public int add(float a,float b){return a+b;}
public int add(int a,int b){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Adder r=new Adder();
System.out.println(r.add(11.1,11.1));
System.out.println(r.add(11,11));
}}
3) sequence is different
class Adder{
public int add(int a,float b){return a+b;}
public int add(float a,int b){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Adder r=new Adder();
System.out.println(r.add(11,11.1));
System.out.println(r.add(11.1,11));
}}

Method overriding
Runtime polymorphism or Method overriding is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of
a superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
Class Bike{
void run(){System.out.println("running");
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b =new Splender();//upcasting
b.run();
}
}

Difference between method overloading and method


overriding

No. Method Overloading Method Overriding


Method overriding is used to
provide the specific
1 Method overloading is used to increase
implementation of the
) the readability of the program.
method that is already
provided by its super class.

Method overriding occurs in


2 Method overloading is performed within
two classes that have IS-A
) class.
(inheritance) relationship.

3 In case of method overloading, In case of method overriding,


) parameter must be different. parameter must be same.

Method overriding is the


4 Method overloading is the example of
example of run time
) compile time polymorphism.
polymorphism.

In java, method overloading can't be


performed by changing return type of the
5 Return type must be same in
method only.Return type can be same or
) method overriding.
different in method overloading. But you
must have to change the parameter.
5.Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

6.Encapsulation
Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.

String Handling
Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters.
Each time you create a string literal, the JVM checks the string constant pool
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

In the above example only one object will be created. Firstly JVM will not find
any string object with the value "Welcome" in string constant pool, so it will
create a new object. After that it will find the string with the value "Welcome" in
the pool, it will not create new object but will return the reference to the same
instance.
Types of string
1.Immutable string
2.Mutable string

1.Immutable String
In java, string objects are immutable. Immutable simply means unmodifiable
or unchangeable.
Once string object is created its data or state can't be changed but a new string
object is created.
Class Testimmutablestring{
public static void main(String args[]){
String s="Jon";
s.concat("Snow");//concat() method appends the string at the end
System.out.println(s);//will print Jon because strings are immutable objects
}
}

2.Mutable String

Mutable means you can change the original string. In java we can make mutable
string using
1.StringBuffer class
2.StringBuilder class

Example
1.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Winter is ");
sb.append("Coming ");//now original string is changed
System.out.println(sb);//prints Winter is coming
}
}

2.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("You know");
sb.append("nothing");//now original string is changed
System.out.println(sb);//prints You know nothing
}
}
Difference between Stringbuffer and Stringbuilder class
Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order while StringBulider
class is not.

String Functions
Here are some string functions:
public class StringTutorial {

public static void main(String[] args) {


String test = "John Snow";
System.out.println(test.equals("John Snow"));//matches character by character,
it will return true.
System.out.println(test.equalsIgnoreCase("john snow"));// returns true as it will
ignore case.
System.out.println(test == new String("John Snow"));//return false as ==
checks hash code or address and new
keyword forces to make a new string, So
hashcode won't match.

System.out.println(test.concat("Ygritte"));// o/p-John Snow Ygritte, but there will


be no change in the original string
rather a new object will be formed.
System.out.println(test.indexOf(" S"));// o/p 5
System.out.println(test.charAt(6));// o/p n
System.out.println(test.trim());// John Snow, removes spaces before and at the
end of string
System.out.println(test.compareTo("Robb")); //o/p-> -8 returns the first non zero
difference between ascii code of the characters .
For example ascii code of J and R are 74 and 82
respectively and 74-82=-8,so it will return -8.
}

Exception Handling
Exception-Exception is an abnormal condition.
Exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at run time.
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code. When an exceptional condition
arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the exception
itself, or pass it on. Either way, at some point, the exception is caught and
processed. Exceptions can be generated by the Java run-time system, or they can
be manually generated by your code. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the Java language or the constraints
of the Java execution environment. Manually generated exceptions are typically
used to report some error condition to the caller of a method.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
The core advantage of exception handling is to maintain the normal flow of
the application. Exception normally disrupts the normal flow of the application
that is why we use exception handling
Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally

Try block
Program statements that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown.
Catch block
Your code can catch this exception (using catch) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java run-
time system.
Throw and throws keyword
To manually throw an exception, use the keyword throw. Any exception that is
thrown out of a method must be specified as such by a throws clause.
Finally block
Any code that absolutely must be executed after a try block completes is put in a
finally block. The immediate nature of an exception being thrown means that
execution of the try block code breaks off, regardless of the importance of the
code that follows the point at which the exception was thrown. This introduces
the possibility that the exception leaves things in an unsatisfactory state. You
might have opened a file, for example, and because an exception was thrown, the
code to close the file is not executed.
The finally block provides the means for you to clean up at the end of executing a
try block. You use a finally block when you need to be sure that some particular
code is run before a method returns, no matter what exceptions are thrown
within the associated try block. A finally block is always executed, regardless of
whether or not exceptions are thrown during the execution of the associated try
block. If a file needs to be closed, or a critical resource released, you can
guarantee that it is done if the code to do it is put in a finally block. The finally
block has a very simple structure:
finally { // Clean-up code to be executed last }
Just like a catch block, a finally block is associated with a particular try block,
and it must be located immediately following any catch blocks for the try block.
If there are no catch blocks then you position
the finally block immediately after the try block. If you don't do this, your
program does not compile.
Note
The primary purpose for the try block is to identify code that may result in an
exception being thrown. However, you can use it to contain code that doesn't
throw exceptions for the convenience of using a finally block. This can be useful
when the code in the try block has several possible exit points — break or return
statements, for example — but you always want to have a specific set of
statements executed after the try block has been executed to make sure things
are tidied up, such as closing any open fi les. You can put these in a finally block.
Note that if a value is returned within a finally block, this return overrides any
return statement executed in the try block.
Types of Exceptions

1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException and Class Not
Found Exception etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
Example
1. int a=50/0;//ArithmeticException
2. String s=null;
System.out.println(s.length());//NullPointerException

3.int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Program of try -catch


class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0; a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero."); }
System.out.println("After catch statement.");
}}
output:
Division by zero. After catch statement.

Example of throw
class ThrowDemo {
public void demoproc()
{
throw new NullPointerException("demo");
}

public static void main(String args[])


{
try
{
demoproc();
}
catch(NullPointerException e) {
System.out.println("caught: " + e);
}}}

O/p:
java.lang.NullPointerException: demo
Here, new is used to construct an instance of NullPointerException. Many of
Java’s built in run-time exceptions have at least two constructors: one with no
parameter and one that takes a string parameter. When the second form is used,
the argument specifies a string that describes the exception. This string is
displayed when the object is used as an argument to print( ) or println( ). It can
also be obtained by a call to getMessage( ), which is defined by Throwable.
Example of throws
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try { throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}}}
O/p:
inside throwOne caught java.lang.IllegalAccessException: demo

Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is an abstract representation of an input or output device that is a
source of, or destination for, data.
The stream concept enables you to transfer data to and from diverse physical
devices such as disk fi les, communications links, or just your keyboard, in
essentially the same way.
In general you can write data to a stream or read data from a stream. You can
visualize a stream as a sequence of bytes that flows into or out of your program

Types of Streams
1.Byte or Binary stream
2.Character Stream
The java.io package supports two types of streams — binary streams, which
contain binary data, and character streams, which contain character data.
Binary Stream
When you write data to a binary stream, the data is written to the stream as a
series of bytes, exactly as it appears in memory. No transformation of the data
takes place. Binary numerical values are just written as a series of bytes, 4 bytes
for each value of type int, 8 bytes for each value of type long, 8 bytes for each
value of type double, and so on.
Example
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String str = null;
do {
str = sc.nextLine();
System.out.println(str);
} while (!str.equals("exit"));
sc.close();

Character Stream
Character streams are used for storing and retrieving text. You may also use
character streams to read text files not written by a Java program.
All binary numeric data has to be converted to a textual representation before
being written to a character stream. This involves generating a character
representation of the original binary data value.
Reading numeric data from a stream that contains text involves much more work
than reading binary data.
When you read a value of type int from a binary stream, you know that it consists
of 4 bytes. When you read an integer from a character stream, you have to
determine how many characters from the stream make up the value. For each
numerical value you read from a character stream, you have to be able to
recognize where the value begins and ends and then convert the token — the
sequence of characters that represents the value — to its binary form.
Example
import java.io.BufferedInputStream;
BufferedInputStream bis = new BufferedInputStream(System.in);
Scanner sc = new Scanner(bis);
String str = null;
do{
str = sc.nextLine();
System.out.println(str);
} while(!str.equals("exit"));
sc.close();
Java Applet
Applet is a special type of program that is embedded in the web page to generate
the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet
Plugin is required at client browser to execute applet.
Lifecycle of Java Applet

1.Applet is initialized.

2.Applet is started.

3.Applet is painted.

4.Applet is stopped.

5.Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4
life cycle methods of applet.

1.public void init():is used to initialized the Applet. It is invoked only once.

2.public void start():is invoked after the init() method or browser is


maximized. It is used to start the Applet.
3.public void stop():is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.

4.public void destroy():is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1.public void paint(Graphics g):is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc etc.

Example
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class AppletEx extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,100,100);
g.setColor(Color.BLUE);
g.fillRectangle(120,120,100,100);
setBackground(Color.YELLOW);
}
}

MULTITHREADING:
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called a
thread,and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
There are two distinct types of multitasking: process-based and thread-based.
understand the A process is a program that is executing. Thus,process-based
multitasking is the feature that allows your computer to run two or more programs
concurrently. For example, process-based multitasking enables you to run the Java
compiler at the same time that you are using a text editor.
In process-based multitasking, a program is the smallest unit of code that can be
dispatched by the scheduler.In a thread-based multitasking environment, the thread is
the smallest unit of dispatchable code. This means that a single program can perform
two or more tasks simultaneously. For example, a text editor can format text at the same
time that it is printing, as long as these two actions are being performed by two
separate threads.

Life Cycle Of Thread:

Life Cycle of Thread goes through the following states:

• New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread.

• Runnable − After a newly born thread is started, the thread becomes


runnable. A thread in this state is considered to be executing its task.
• Non-Runnable − Sometimes, a thread transitions to the waiting state
while the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
• Terminated (Dead) − A runnable thread enters the terminated state when
it completes its task or otherwise terminates.

Creating Thread:
We can define a class that is to represent a thread in two ways:
1. Defining a subclass of Thread that provides a definition of the run()method that
overrides the
inherited method.
2.Defining class as implementing the Runnable interface, which declares the run()
method,
and then creates a Thread object in your class when you need it.

Example1:By extending Thread Class

public class ThreadTutorial {

public static void main(String[] args) {


ThreadEx3 thread3 = new ThreadEx3();
thread3.start();

System.out.println("Main Thread");
}
}
class ThreadEx2 extends Thread {

@Override
public void run() {

for (int i = 0; i < 5; i++) {


System.out.println("Child Thread: " + i);
}
}
Output: Main Thread 0 1 2 3 4

Example2:By implementing runnable interface.

public class ThreadTutorial {


public static void main(String[] args) {
Runnable obj = new ThreadEx();
Thread th = new Thread(obj);
th.start();
System.out.println("Main Thread");
}
}
class ThreadEx implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread: " + i);
}}
Output: Main Thread 0 1 2 3 4

Sleep method of the Thread:


Sleep method is of Thread class is used to sleep a thread for the specified
amount of time.

Syntax: public static void sleep(long miliseconds)throws InterruptedException

Example:
public class ThreadTutorial {
public static void main(String[] args) {
ThreadEx3 thread3 = new ThreadEx3();
thread3.start();
System.out.println("Main Thread");
}
}
class ThreadEx3 extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 20; i++) {
if(i == 5) {
Thread.sleep(5000);
}

System.out.println("Child 2: " + i);


}
} catch(InterruptedException ex) {
System.err.println(ex.getMessage());
}
}
}

AWT(ABSTRACT WINDOW TOOLKIT)


AWT is an API through which we can make GUI application or desktop
application. It is platform dependent API for creating (GUI) for java programs
i.e. the controls of AWT GUI will have different platforms like windows,MAC,Unix
etc.

The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical
fashion, it is easier to understand.
Fig:AWT Hierarchy

Component
At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. All user interface
elements that are displayed on the screen and that interact with the user are
subclasses of Component.It defines over a hundred public methods that are
responsible for managing events, such as mouse and keyboard input, positioning and
sizing the window, and repainting. A Component object is responsible for
remembering the current foreground and background colors and the currently
selected text font.

Container
The Container class is a subclass of Component.It has additional methods that allow
other Component objects to be nested within it. Other Container objects can be stored
inside of a Container(since they are themselves instances of Component).
Window
The Window class creates a top-level window. A top-level window is not contained within
any other object; it sits directly on the desktop. Generally, we won’t create Window
objects directly. Instead, we will use a subclass of Window called Frame.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.

AWT Controls:
list of commonly used controls while designed GUI using AWT is as follows:
1. TextField
2.Button
3.Label
4.CheckBox
5.List
6.TextArea
7.Dialog
8.Image etc.
To create any of the above control in GUI we need to create object for that class.
Example: Creating Button in AWT.
import java.awt.*;
import java.awt.event.*;

public class ButtonEX extends Frame


{
public ButtonEx()
{

Button btn=new Button("Hello World");


add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("AWT EXAMPLE"); //setting title.
B.setBounds(50,50,100,100); // setting position of button.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
ButtonEx t = new ButtonEx(); //creating a frame.
}
}

Layout Managers
Layout manager is responsible for positioning the controls within the container.
They eliminate the need of user to place the control on their own. A Layout
manager is an interface that automatically arranges your controls within a window by
using some type of algorithm. This interface has several classes.

1.FlowLayout:
FlowLayout is the default layout manager. FlowLayout implements a simple layout
style, which is similar to how words flow in a text editor. The direction of the layout is
governed by the container ’s component orientation property, which, by default, is left
to right, top to bottom. Therefore, by default, components are laid out line-by-line
beginning at the upper-left corner. In all
cases, when a line is filled, layout advances to the next line. A small space is left
between each component, above and below, as well as left and right. Constructors for
flow layouts are:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert )
The first form creates the default layout, which centers components and leaves five
pixels of space between each component. The second form lets you specify how each
line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.

Example:

2.Grid Layout:The GridLayout is used to arrange the components in


rectangular grid. One component is displayed in each rectangle.The constructors
supported by GridLayout
are:
GridLayout( )
GridLayout(int numRows , int numColumns)

The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. Either numRows or
numColumns can be zero.

Example:

3. Box Layout:The BoxLayout


is used to arrange the
components either vertically or
horizontally. Constructor of
BoxLayout class
BoxLayout(Container c, int
axis): creates a box layout that
arranges the components with
the given axis.
Note: BoxLayout class is
found in javax.swing package.

Fields of BoxLayout class


1. public static final int X_AXIS
2. public static final int Y_AXIS

Example:

Event Handling:
Event: Any activity that interrupts the current ongoing activity. Event source is
the object that generates the event. The task of handling event is done by event-
listener. When an event occur find an object of appropriate type is created. Then
that object is then passed to a listener. A listener must implement that the
interface that has the method for event handling.

Event Classes Listener Interfaces


ActionEvent ActionListener
MouseEvent MouseListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener
FocusEvent FocusListener

Example: Program to display text in TextField On click of Button


import java.awt.Button;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;

public class AwtFrame extends Frame {


public AwtFrame() throws HeadlessException {
Button btn = new Button("Click Here");
TextField t = new TextField(20);
TextField tf1 = new TextField(20);
btn.addActionListener(new ButtonActionListener(tf));
FlowLayout fl = new FlowLayout(FlowLayout.CENTER);
setLayout(fl);
add(btn);
add(t); // OR (We can use any of the layout, accordingly output will
change)
GridLayout gl = new GridLayout(2, 1);
setLayout(gl);
add(btn);
add(t); // OR
BoxLayout bl = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(bl);
add(btn);
add(tf);
add(tf1);
setTitle("Awt Tutorial");
setSize(300, 300);
setVisible(true);
}

public static void main(String[] args) {


new AwtFrame();
}
}

class ButtonActionListener implements ActionListener {


TextField tf;
public ButtonActionListener(TextField tf) {
this.tf = tf;
}
@Override
public void actionPerformed(ActionEvent ae) {
tf.setText("Button Clicked");
}
}

Вам также может понравиться