0% found this document useful (0 votes)
13 views24 pages

Features of Java: Unit-I

The document provides an overview of Advanced Java Programming, focusing on the features of Java such as simplicity, object-orientation, portability, and security. It also covers applets, their lifecycle, and the Java AWT (Abstract Window Toolkit) for creating graphical user interfaces, including various controls like buttons, text fields, and event handling mechanisms. Additionally, it explains the structure of AWT controls and the process of event handling in Java applications.

Uploaded by

Sujeet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Features of Java: Unit-I

The document provides an overview of Advanced Java Programming, focusing on the features of Java such as simplicity, object-orientation, portability, and security. It also covers applets, their lifecycle, and the Java AWT (Abstract Window Toolkit) for creating graphical user interfaces, including various controls like buttons, text fields, and event handling mechanisms. Additionally, it explains the structure of AWT controls and the process of event handling in Java applications.

Uploaded by

Sujeet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Advance Java Programming

Unit-I.

Introduction to Java

Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as java buzzwords.

A list of most important features of Java language is given below.

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

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies 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

Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. 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 a
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, for example, 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).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the 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. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.

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.

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage
collection).

 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.awt and 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

1. It takes very less response time as it works on the client side.


2. It can be run on any browser which has JVM running in it.

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 is called 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.

Note: The stop() method is always called before destroy() method.

Example of an Applet Skeleton


import java.awt.*;

import java.applet.*;

public class AppletTest extends Applet

public void init()

//initialization

public void start ()

//start or resume execution

public void stop()

//suspend execution

{
public void destroy()

//perform shutdown activity

public void paint (Graphics g)

//display the content of window

Example of an Applet
import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet

int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(10, 30, 120, 120, 2, 3);

}
 Introduction to Java AWT
Controls
Java AWT controls are the controls that are used to design graphical

user interfaces or web applications. To make an effective GUI, Java

provides java.awt package that supports various AWT controls like

Label, Button, CheckBox, CheckBox Group, List, Text Field, Text

Area, Choice, Canvas, Image, Scrollbar, Dialog, File Dialog, etc that

creates or draw various components on web and manage the GUI

based application.

Structure of the Java AWT Controls


The structure of the AWT is quite simple and it is used extensively in

programs. Every AWT inherits controls from the Container Class.


Container Class
It represents objects in graphical representation and it is an abstract

class in the GUI interface.

The following are the list of commonly used UI elements in the GUI

or commonly known as Graphical User Interface.

1. Label
A label is a user for placing text inside the container. A label is used

only for inputting text. The label does not imply that the text can be

altered or it can be used as a button which can be further worked

upon.

Syntax:

Label n=new Label("Name:",Label.CENTER);

2. Button
This command generates a button in the User Interface. Clicking on

the button would move the command to another page or another

web server which is used to show several other outputs in the user

interface page.

Syntax:
a1=new Button("submit");

a2=new Button("cancel");

3. Checkbox
There can be a certain question and the checkbox is used to

determine the true or false nature of the question being asked. If

the checkbox is ticked then it means that the said question is true

which if it is unchecked it means that the said question is false. It is

basically a true or false state in Java programming language.

Syntax:

Checkbox checkbox1 = new Checkbox("Hello World");

4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that

are being used in the programming language. There are many

checkboxes that are being used and hence the group of checkboxes

is known as the checkbox group.

Syntax:
CheckboxGroup cb = new CheckboxGroup();

Checkbox checkBox1 = new Checkbox("Hello", cb, true);

checkBox1.setBounds (100,100, 50,50);

5. List
The list gives a scrolling list of items for the user. The scrolling list of

items is also being set by the user. The user sets the scrolling list of

items such as Fruits, Vegetables, some questionnaire or other facts.

Syntax:

List l1=new List(4);

l1.setBounds(100,100, 75,75);

6. Text Field
A text field is used for the editing of a particular line of text which

can be used within the programming concept.

Syntax:

na=new TextField(20);

7. Text Area
A text area is used for the editing of multiple lines of text. The only

difference between the Text field and Text area is that Text Field is

used for editing a single line of text within the user interface while a

Text Area is used for editing multiple lines of text.

Syntax:

TextArea area=new TextArea("Welcome to the universe");

area.setBounds(10,30, 300,300);

8. Choice
A choice, as the name implies, shows the various options and the

choice that is selected is shown in the top menu bar of the screen.

Syntax:

Choice c=new Choice();

c.setBounds(100,100, 75,75);

c.add("Subject 1");

c.add("Subject 2");

c.add("Subject 3");
c.add("Subject 4");

c.add("Subject 5");

9. Canvas
In the canvas space, there can be an input being given by the user

or the user can draw something on the Canvas space being given.

Syntax:

f.add(new MyCanvas());

f.setLayout(null);

f.setSize(400, 400);

f.setVisible(true);

10. Image
There can be a single image or multiple images within a UI. There

can be a button being associated with an image and when it is

clicked it can produce some functionality.

Syntax:

Image i=t.getImage("pic2.gif");
11. Scroll Bar
The scroll bar like a normal one is used to scroll or move from a

varied range of values. The user selects one value from those range

of values.

Syntax:

Scrollbar s=new Scrollbar();

s.setBounds(100,100, 50,100);

12. Dialog
The dialog is used to take some form of input from the user and

produce it in a sequential manner.

Syntax:

d = new Dialog(f , "Hello World", true);

13. File Dialog


From a file dialog, a user can select a file which he/she wishes to

use.

Syntax:
FileDialog(Dialog parent)

 Java GUI Event Handling


Any program that uses GUI (graphical user interface) such as Java application written
for windows, is event driven. Event describes the change in state of any object. For
Example : Pressing a button, Entering a character in Textbox, Clicking or Dragging a
mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs.

How Events are handled?


A source generates an Event and send it to one or more listeners registered with the
source. Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.

Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is ActionListener


selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also when it
enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEven generated when mouse wheel is moved MouseWheelListene


t

WindowEvent generated when window is activated, deactivated, WindowListener


deiconified, iconified, opened or closed

ComponentEvent generated when component is hidden, moved, resized ComponentEventLis


or set visible

ContainerEvent generated when component is added or removed from ContainerListener


container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener


FocusEvent generated when component gains or loses keyboard FocusListener
focus

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example of Event Handling


import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import java.applet.*;

import java.awt.event.*;

import java.awt.*;

public class Test extends Applet implements KeyListener

String msg="";

public void init()

addKeyListener(this);

public void keyPressed(KeyEvent k)

showStatus("KeyPressed");
}

public void keyReleased(KeyEvent k)

showStatus("KeyRealesed");

public void keyTyped(KeyEvent k)

msg = msg+k.getKeyChar();

repaint();

public void paint(Graphics g)

g.drawString(msg, 20, 40);

HTML code:
<applet code="Test" width=300, height=100>

</applet>
Multithreading in java with
examples
A thread is a light-weight smallest part of a process that can run concurrently with
the other parts(other threads) of the same process. Threads are independent
because they all have separate path of execution that’s the reason if an
exception occurs in one thread, it doesn’t affect the execution of other threads.
All threads of a process share the common memory. The process of executing
multiple threads simultaneously is known as multithreading.

Let’s summarize the discussion in points:


1. The main purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to maximum utilize the CPU time. A
multithreaded program contains two or more parts that can run concurrently.
Each such part of a program called thread.

2. Threads are lightweight sub-processes, they share the common memory


space. In Multithreaded environment, programs that are benefited from
multithreading, utilize the maximum CPU time so that the idle time can be kept to
minimum.

3. A thread can be in one of the following states:


NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an
action for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.

Creating a thread in Java


There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the
example below.

 getName(): It is used for Obtaining a thread’s name


 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

Method 1: Thread creation by extending Thread


class
Example 1:

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:
My thread is in running state.

You might also like