Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
Can you provide the Java Transient Keyword?
|
If you don't want to serialize any data member of a class, you can mark it as transient.
Employee.java
class Employee implements Serializable{
transient int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the value of id. It will return default value always. In such case, it will return 0 because the data type of id is an integer.
|
Can you give me the SerialVersionUID?
|
The serialization process at runtime associates an id with each Serializable class which is known as SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and receiver must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the same SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object. We can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested to explicitly declare the serialVersionUID field in the class and have it private also. For example:
private static final long serialVersionUID=1L;
Now, the Serializable class will look like this:
Employee.java
import java.io.Serializable;
class Employee implements Serializable{
private static final long serialVersionUID=1L;
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
|
What is Java transient Keyword?
|
In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the type of data stored in that instance. Deserialization performs exactly opposite operation. It converts the byte sequence into original object data. During the serialization, when we do not want an object to be serialized we can use a transient keyword.
|
Why to use the transient keyword?
|
The transient keyword can be used with the data members of a class in order to avoid their serialization. For example, if a program accepts a user's login details and password. But we don't want to store the original password in the file. Here, we can use transient keyword and when JVM reads the transient keyword it ignores the original value of the object and instead stores the default value of the object.
Syntax:
private transient <member variable>;
Or
transient private <member variable>;
|
When to use the transient keyword?
|
1)The transient modifier can be used where there are data members derived from the other data members within the same instance of the class.
2)This transient keyword can be used with the data members which do not depict the state of the object.
3)The data members of a non-serialized object or class can use a transient modifier.
|
Can you provide an Example of Java Transient Keyword?
|
Let's take an example, we have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but we don't want to serialize one value, e.g. age then we can declare the age data member as transient.
In this example, we have created two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.
PersistExample.java
import java.io.*;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
class PersistExample{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
out.close();
f.close();
System.out.println("success");
}
}
Output:
success
Now write the code for deserialization.
DePersist.java
import java.io.*;
class DePersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
in.close();
}
}
Output:
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
In this article, we have discussed use of transient keyword in Java, where to use transient keyword and implementation of transient keyword in a Java program.
|
What is Java Networking?
|
Java Networking is a concept of connecting two or more computing devices together so that we can share resources.
Java socket programming provides facility to share data between different computing devices.
|
What is the Advantage of Java Networking?
|
1.Sharing resources
2.Centralize software management
The java.net package supports two protocols,
1.TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2.UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be transferred along two or more nodes
|
What is Java Networking Terminology?
|
The widely used Java networking terminologies are given below:
1.IP Address
2.Protocol
3.Port Number
4.MAC Address
5.Connection-oriented and connection-less protocol
6.Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
-TCP
-FTP
-Telnet
-SMTP
-POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
|
What is java.net package?
|
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs.
The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below:
-Authenticator
-CacheRequest
-CacheResponse
-ContentHandler
-CookieHandler
-CookieManager
-DatagramPacket
-DatagramSocket
-DatagramSocketImpl
-InterfaceAddress
-JarURLConnection
-MulticastSocket
-InetSocketAddress
-InetAddress
-Inet4Address
-Inet6Address
-IDN
-HttpURLConnection
-HttpCookie
-NetPermission
-NetworkInterface
-PasswordAuthentication
-Proxy
-ProxySelector
-ResponseCache
-SecureCacheResponse
-ServerSocket
-Socket
-SocketAddress
-SocketImpl
-SocketPermission
-StandardSocketOptions
-URI
-URL
-URLClassLoader
-URLConnection
-URLDecoder
-URLEncoder
-URLStreamHandler
List of interfaces available in java.net package:
-ContentHandlerFactory
-CookiePolicy
-CookieStore
-DatagramSocketImplFactory
-FileNameMap
-SocketOption<T>
-SocketOptions
-SocketImplFactory
-URLStreamHandlerFactory
-ProtocolFamily
|
What is Java Socket Programming?
|
Java Socket programming is used for communication between the applications running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1.IP Address of Server, and
2.Port number.
Here, we are going to make one-way client and server communication. In this application, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side.
|
What is Socket class?
|
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.
Method: public InputStream getInputStream()
Description: returns the InputStream attached with this socket.
Method: public OutputStream getOutputStream()
Description: returns the OutputStream attached with this socket.
Method: public synchronized void close()
Description:closes this socket
|
Can you provide the ServerSocket class?
|
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.
Method: public Socket accept()
Description: returns the socket and establish a connection between server and client.
Method: public synchronized void close()
Description: closes the server socket.
|
Can you provide an Example of Java Socket Programming?
|
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each command prompt
|
What is Java URL?
|
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web.
A URL contains many information:
1.Protocol: In this case, http is the protocol.
2.Server name or IP Address: In this case, www.javatpoint.com is the server name.
3.Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
4.File Name or directory name: In this case, index.jsp is the file name.
|
Can you give me the Constructors of Java URL class?
|
URL(String spec)
Creates an instance of a URL from the String representation.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given context.
|
Can you give me the Commonly used methods of Java URL class?
|
The java.net.URL class provides many methods. The important methods of URL class are given below.
Method: public String getProtocol()
Description: it returns the protocol of the URL.
Method:public String getHost()
Description: it returns the host name of the URL.
Method: public String getPort()
Description: it returns the Port Number of the URL.
Method: public String getFile()
Description: it returns the file name of the URL.
Method: public String getAuthority()
Description: it returns the authority of the URL.
Method: public String toString()
Description: it returns the string representation of the URL.
Method:public String getQuery()
Description: it returns the query string of the URL.
Method: public String getDefaultPort()
Description: it returns the default port of the URL.
Method: public URLConnection openConnection()
Description: it returns the instance of URLConnection i.e. associated with this URL.
Method: public boolean equals(Object obj)
Description: it compares the URL with the given object.
Method: public Object getContent()
Description: it returns the content of the URL.
Method: public String getRef()
Description: it returns the anchor or reference of the URL.
Method: public URI toURI()
Description: it returns a URI of the URL.
|
Can you provide an Example of Java URL class?
|
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
|
What is Java URLConnection Class?
|
The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL.
|
What is the URL?
|
-URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that helps to find a resource on the World Wide Web (WWW).
-URL has two components:
1.The protocol required to access the resource.
2.The location of the resource.
|
What are the Features of URLConnection class?
|
1.URLConnection is an abstract class. The two subclasses HttpURLConnection and JarURLConnection makes the connetion between the client Java program and URL resource on the internet.
2.With the help of URLConnection class, a user can read and write to and from any resource referenced by an URL object.
3.Once a connection is established and the Java program has an URLConnection object, we can use it to read or write or get further information like content length, etc.
Constructor: protected URLConnection(URL url)
Description: It constructs a URL connection to the specified URL.
|
Can you give me the URLConnection Class Methods?
|
Method: void addRequestProperty(String key, String value)
Description: It adds a general request property specified by a key-value pair
Method: void connect()
Description: It opens a communications link to the resource referenced by this URL, if such a connection has not already been established.
Method: boolean getAllowUserInteraction()
Description: It returns the value of the allowUserInteraction field for the object.
Method: int getConnectionTimeout()
Description: It returns setting for connect timeout
Method: Object getContent()
Description: It retrieves the contents of the URL connection.
Method: Object getContent(Class[] classes)
Description: It retrieves the contents of the URL connection.
Method: String getContentEncoding()
Description:It returns the value of the content-encoding header field.
Method: int getContentLength()
Description: It returns the value of the content-length header field.
Method: long getContentLengthLong()
Description: It returns the value of the content-length header field as long.
Method: String getContentType()
Description: It returns the value of the date header field
Method: long getDate()
Description: It returns the value of the date header field.
Method: static boolean getDefaultAllowUserInteraction()
Description: It returns the default value of the allowUserInteraction field.
Method: boolean getDefaultUseCaches()
Description: It returns the default value of an URLConnetion's useCaches flag.
Method: boolean getDoInput()
Description: It returns the value of the URLConnection's doInput flag.
Method: boolean getDoInput()
Description: It returns the value of the URLConnection's doOutput flag.
Method: long getExpiration()
Description:It returns the value of the expires header files.
Method: static FileNameMap getFilenameMap()
Description: It loads the filename map from a data file.
Method: String getHeaderField(int n)
Description: It returns the value of nth header field
Method: String getHeaderField(String name)
Description: It returns the value of the named header field.
Method: long getHeaderFieldDate(String name, long Default)
Description: It returns the value of the named field parsed as a number.
Method: int getHeaderFieldInt(String name, int Default)
Description: It returns the value of the named field parsed as a number
Method: String getHeaderFieldKey(int n)
Description: It returns the key for the nth header field.
Method: long getHeaderFieldLong(String name, long Default)
Description: It returns the value of the named field parsed as a number
Method: Map<String, List<String>> getHeaderFields()
Description: It returns the unmodifiable Map of the header field.
Method: long getIfModifiedSince()
Description: It returns the value of the object's ifModifiedSince field.
Method: InputStream getInputStream()
Description: It returns an input stream that reads from the open condition.
Method: long getLastModified()
Description: It returns the value of the last-modified header field.
Method: OutputStream getOutputStream()
Description:It returns an output stream that writes to the connection.
Method: Permission getPermission()
Description: It returns a permission object representing the permission necessary to make the connection represented by the object.
Method: int getReadTimeout()
Description: It returns setting for read timeout
Method: Map<String, List<String>> getRequestProperties()
Description: It returns the value of the named general request property for the connection.
Method: URL getURL()
Description: It returns the value of the URLConnection's URL field.
Method: boolean getUseCaches()
Description: It returns the value of the URLConnection's useCaches field.
Method:Static String guessContentTypeFromName(String fname)
Description:It tries to determine the content type of an object, based on the specified file component of a URL.
Method:static String guessContentTypeFromStream(InputStream is)
Description: It tries to determine the type of an input stream based on the characters at the beginning of the input stream.
Method: void setAllowUserInteraction(boolean allowuserinteraction)
Description: It sets the value of the allowUserInteraction field of this URLConnection.
Method: static void setContentHandlerFactory(ContentHandlerFactory fac)
Description: It sets the ContentHandlerFactory of an application.
Method: static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction)
Description: It sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.
Method: void steDafaultUseCaches(boolean defaultusecaches)
Description: It sets the default value of the useCaches field to the specified value.
Method: void setDoInput(boolean doinput)
Description: It sets the value of the doInput field for this URLConnection to the specified value.
Method: void setDoOutput(boolean dooutput)
Description:It sets the value of the doOutput field for the URLConnection to the specified value.
|
How to get the object of URLConnection Class?
|
The openConnection() method of the URL class returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
|
Can you give me the Displaying Source Code of a Webpage by URLConnecton Class?
|
The URLConnection class provides many methods. We can display all the data of a webpage by using the getInputStream() method. It returns all the data of the specified URL in the stream that can be read and displayed.
Example of Java URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
|
What is Java HttpURLConnection class?
|
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.
|
Can you give me the HttpURLConnection Class Constructor?
|
Constructor: protected HttpURLConnection(URL u)
Description: It constructs the instance of HttpURLConnection class.
|
Can you give me the Java HttpURLConnection Methods?
|
Method: void disconnect()
Description: It shows that other requests from the server are unlikely in the near future.
Method: InputStream getErrorStream()
Description: It returns the error stream if the connection failed but the server sent useful data.
Method: Static boolean getFollowRedirects()
Description: It returns a boolean value to check whether or not HTTP redirects should be automatically followed.
Method: String getHeaderField(int n)
Description: It returns the value of nth header file.
Method: long getHeaderFieldDate(String name, long Default)
Description: It returns the value of the named field parsed as a date.
Method: String getHeaderFieldKey(int n)
Description: It returns the key for the nth header file.
Method: boolean getInstanceFollowRedirects()
Description: It returns the value of HttpURLConnection's instance FollowRedirects field.
Method: Permission getPermission()
Description: It returns the SocketPermission object representing the permission to connect to the destination host and port.
Method: String getRequestMethod()
Description: It gets the request method.
Method: int getResponseCode()
Description: It gets the response code from an HTTP response message.
Method: String getResponseMessage()
Description:It gets the response message sent along with the response code from a server.
Method: void setChunkedStreamingMode(int chunklen)
Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.
Method: void setFixedLengthStreamingMode(int contentlength)
Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.
Method: void setFixedLengthStreamingMode(long contentlength)
Description: The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.
Method: static void setFollowRedirects(boolean set)
Description:It sets whether HTTP redirects (requests with response code) should be automatically followed by HttpURLConnection class.
Method: void setInstanceFollowRedirects(boolean followRedirects)
Description: It sets whether HTTP redirects (requests with response code) should be automatically followed by instance of HttpURLConnection class.
Method: void setRequestMethod(String method)
Description: Sets the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.
Method: abstract boolean usingProxy()
Description: It shows if the connection is going through a proxy.
|
How to get the object of HttpURLConnection class?
|
The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
You can typecast it to HttpURLConnection type as given below.
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
Java HttpURLConnection Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Date = Thu, 22 Jul 2021 18:08:17 GMT
Server = Apache
Location = https://www.javatpoint.com/java-tutorial
Cache-Control = max-age=2592000
Expires = Sat, 21 Aug 2021 18:08:17 GMT
Content-Length = 248
Keep-Alive =timeout=5, max=1500
Connection = Keep-Alive
|
What is Java InetAddress class?
|
Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name. There are two types of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.
IP Address
-An IP address helps to identify a specific resource on the network using a numerical representation.
-Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the destination and the source.
There are two versions of IP address:
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is more than 4 million addresses.
Features of IPv4:
-It is a connectionless protocol.
-It utilizes less memory and the addresses can be remembered easily with the class based addressing scheme.
-It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation).
Features of IPv6:
-It has a stateful and stateless both configurations.
-It provides support for quality of service (QoS).
-It has a hierarchical addressing and routing infrastructure.
TCP/IP Protocol
-TCP/IP is a communication protocol model used connect devices over a network via internet.
-TCP/IP helps in the process of addressing, transmitting, routing and receiving the data packets over the internet.
-The two main protocols used in this communication model are:
1.TCP i.e. Transmission Control Protocol. TCP provides the way to create a communication channel across the network. It also helps in transmission of packets at sender end as well as receiver end.
2.IP i.e. Internet Protocol. IP provides the address to the nodes connected on the internet. It uses a gateway computer to check whether the IP address is correct and the message is forwarded correctly or not.
|
Can you give me the Java InetAddress Class Methods?
|
Method: public static InetAddress getByName(String host) throws UnknownHostException
Description: It returns the instance of InetAddress containing LocalHost IP and name.
Method: public static InetAddress getLocalHost() throws UnknownHostException
Description: It returns the instance of InetAdddress containing local host name and address.
Method: public String getHostName()
Description: It returns the host name of the IP address.
Method: public String getHostAddress()
Description: It returns the IP address in string format.
|
Can you provide an Example of Java InetAddress Class?
|
Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website.
InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Host Name: www.javatpoint.com
IP Address: 172.67.196.82
|
Can you give me the Program to demonstrate methods of InetAddress class?
|
InetDemo2.java
import java.net.Inet4Address;
import java.util.Arrays;
import java.net.InetAddress;
public class InetDemo2
{
public static void main(String[] arg) throws Exception
{
InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
byte addr[]={72, 3, 2, 12};
System.out.println("ip : "+ip);
System.out.print("\nip1 : "+ip1);
InetAddress ip2 = InetAddress.getByAddress(addr);
System.out.print("\nip2 : "+ip2);
System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
System.out.print("\nHost Address : " +ip.getHostAddress());
System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
System.out.print("\nhashCode : " +ip.hashCode());
System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
}
}
|
What is Java DatagramSocket and DatagramPacket?
|
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP instead of TCP.
Datagram
Datagrams are collection of information sent from one device to another device via the established network. When the datagram is sent to the targeted device, there is no assurance that it will reach to the target device safely and completely. It may get damaged or lost in between. Likewise, the receiving device also never know if the datagram received is damaged or not. The UDP protocol is used to implement the datagrams in Java.
|
What is Java DatagramSocket class?
|
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. It is a mechanism used for transmitting datagram packets over network.`
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
|
What is Commonly used Constructors of DatagramSocket class?
|
-DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
-DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
-DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.
|
Can you give me the Java DatagramSocket Class?
|
Method: void bind(SocketAddress addr)
Description: It binds the DatagramSocket to a specific address and port.
Method: void close()
Description: It closes the datagram socket.
Method: void connect(InetAddress address, int port)
Description:It connects the socket to a remote address for the socket.
Method: void disconnect()
Description: It disconnects the socket.
Method: boolean getBroadcast()
Description: It tests if SO_BROADCAST is enabled.
Method:DatagramChannel getChannel()
Description: It returns the unique DatagramChannel object associated with the datagram socket.
Method: InetAddress getInetAddress()
Description: It returns the address to where the socket is connected.
Method: InetAddress getLocalAddress()
Description: It gets the local address to which the socket is connected.
Method: int getLocalPort()
Description: It returns the port number on the local host to which the socket is bound.
Method: SocketAddress getLocalSocketAddress()
Description: It returns the address of the endpoint the socket is bound to.
Method: int getPort()
Description: It returns the port number to which the socket is connected.
Method: int getReceiverBufferSize()
Description: It gets the value of the SO_RCVBUF option for this DatagramSocket that is the buffer size used by the platform for input on the DatagramSocket.
Method: boolean isClosed()
Description: It returns the status of socket i.e. closed or not.
Method: boolean isConnected()
Description: It returns the connection state of the socket.
Method: void send(DatagramPacket p)
Description: It sends the datagram packet from the socket.
Method: void receive(DatagramPacket p)
Description:It receives the datagram packet from the socket.
|
What is Java DatagramPacket Class?
|
Java DatagramPacket is a message that can be sent or received. It is a data container. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
|
What is Commonly used Constructors of DatagramPacket class?
|
-DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
-DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.
|
Can you give me the Java DatagramPacket Class Methods?
|
Method: InetAddress getAddress()
Description: It returns the IP address of the machine to which the datagram is being sent or from which the datagram was received.
Method: byte[] getData()
Description: It returns the data buffer.
Method: int getLength()
Description: It returns the length of the data to be sent or the length of the data received.
Method: int getOffset()
Description: It returns the offset of the data to be sent or the offset of the data received.
Method: int getPort()
Description: It returns the port number on the remote host to which the datagram is being sent or from which the datagram was received.
Method: SocketAddress getSocketAddress()
Description: It gets the SocketAddress (IP address + port number) of the remote host that the packet is being sent to or is coming from.
Method: void setAddress(InetAddress iaddr)
Description: It sets the IP address of the machine to which the datagram is being sent.
Method: void setData(byte[] buff)
Description: It sets the data buffer for the packet.
Method: void setLength(int length)
Description: It sets the length of the packet.
Method: void setPort(int iport)
Description: It sets the port number on the remote host to which the datagram is being sent.
Method: void setSocketAddress(SocketAddress addr)
Description: It sets the SocketAddress (IP address + port number) of the remote host to which the datagram is being sent.
|
Can you provide an Example of Sending DatagramPacket by DatagramSocket?
|
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}
|
What is Java AWT Tutorial?
|
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.
|
Why AWT is platform independent?
|
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for their native components and AWT directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like a Mac application in the MAC OS.
|
Can you give me the Useful Methods of Component Class?
|
Method: public void add(Component c)
Description: Inserts a component on this component.
Method: public void setSize(int width,int height)
Description: Sets the size (width and height) of the component.
Method:public void setLayout(LayoutManager m)
Description: Defines the layout manager for the component.
Method: public void setVisible(boolean status)
Description: Changes the visibility of the component, by default false.
|
Can you provide the Java AWT Example?
|
To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.
1.By extending Frame class (inheritance)
2.By creating the object of Frame class (association)
|
Can you provide the AWT Example by Inheritance?
|
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.
AWTExample1.java
// importing Java AWT class
import java.awt.*;
// extending Frame class to our class AWTExample1
public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets the position of the awt button.
|
What is Event and Listener (Java Event Handling)?
|
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.
|
Can you give me the Java Event classes and Listener interfaces?
|
Event class: ActionEvent
Listener Interface: ActionListener
Event class: MouseEvent
Listener Interface: MouseListener and MouseMotionListener
Event class: MouseWheelEvent
Listener Interface: MouseWheelListener
Event class: KeyEvent
Listener Interface: KeyListener
Event class: ItemEvent
Listener Interface: ItemListener
Event class: TextEvent
Listener Interface: TextListener
Event class: AdjustmentEvent
Listener Interface:AdjustmentListener
Event class: WindowEvent
Listener Interface: WindowListener
Event class: ComponentEvent
Listener Interface: ComponentListener
Event class: ContainerEvent
Listener Interface: ContainerListener
Event class: FocusEvent
Listener Interface: FocusListener
|
Can you give me the Registration Methods?
|
For registering the component with the Listener, many classes provide the registration methods. For example:
-Button
-public void addActionListener(ActionListener a){}
-MenuItem
-public void addActionListener(ActionListener a){}
-TextField
-public void addActionListener(ActionListener a){}
-public void addTextListener(TextListener a){}
-TextArea
-public void addTextListener(TextListener a){}
-Checkbox
-public void addItemListener(ItemListener a){}
-Choice
-public void addItemListener(ItemListener a){}
-List
-public void addActionListener(ActionListener a){}
-public void addItemListener(ItemListener a){}
|
How to use Java Event Handling Code?
|
We can put the event handling code into one of the following places:
1.Within class
2.Other class
3.Anonymous class
|
Can you give me the Java event handling by implementing ActionListener?
|
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.
|
Can you provide the Java event handling by outer class?
|
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
|
Can you give the Java event handling by anonymous class?
|
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
|
What is Java AWT Button?
|
A button is basically a control component with a label that generates an event when pushed. The Button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed.
When we press a button and release it, AWT sends an instance of ActionEvent to that button by calling processEvent on the button. The processEvent method of the button receives the all the events, then it passes an action event by calling its own method processActionEvent. This method passes the action event on to action listeners that are interested in the action events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface needs to be implemented. The registered new listener can receive events from the button by calling addActionListener method of the button. The Java application can use the button's action command as a messaging protocol.
|
What is AWT Button Class Declaration?
|
public class Button extends Component implements Accessible
|
Can you give me the Button Class Constructors?
|
Following table shows the types of Button class constructors
Sr. no : 1
Constructor:Button( )
Description: It constructs a new button with an empty string i.e. it has no label.
Sr. no : 2
Constructor: Button (String text)
Description: It constructs a new button with given string as its label.
|
Can you give me the Button Class Methods?
|
Sr. no : 1
Method: void setText (String text)
Description: It sets the string message on the button
Sr. no : 2
Method: String getText()
Description:It fetches the String message on the button.
Sr. no : 3
Method: void setLabel (String label)
Description: It sets the label of button with the specified string.
Sr. no : 4
Method: String getLabel()
Description:It fetches the label of the button.
Sr. no : 5
Method: void addNotify()
Description:It creates the peer of the button
Sr. no : 6
Method: AccessibleContext getAccessibleContext()
Description:It fetched the accessible context associated with the button.
Sr. no : 7
Method: void addActionListener(ActionListener l)
Description: It adds the specified action listener to get the action events from the button.
Sr. no : 8
Method: String getActionCommand()
Description: It returns the command name of the action event fired by the button.
Sr. no : 9
Method: ActionListener[ ] getActionListeners()
Description:It returns an array of all the action listeners registered on the button.
Sr. no : 10
Method: T[ ] getListeners(Class listenerType)
Description: It returns an array of all the objects currently registered as FooListeners upon this Button.
Sr. no : 11
Method: protected String paramString()
Description:It returns the string which represents the state of button.
Sr. no : 12
Method: protected void processActionEvent (ActionEvent e)
Description: It process the action events on the button by dispatching them to a registered ActionListener object.
Sr. no : 13
Method: protected void processEvent (AWTEvent e)
Description:It process the events on the button
Sr. no : 14
Method: void removeActionListener (ActionListener l)
Description:It removes the specified action listener so that it no longer receives action events from the button.
Sr. no : 15
Method: void setActionCommand(String command)
Description:It sets the command name for the action event given by the button.
|
Can you provide the Java AWT Button Example?
|
ButtonExample.java
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
To compile the program using command prompt type the following commands
C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
If there's no error, we can execute the code using:
C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
|
What is Java AWT Label?
|
The object of the Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by a programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object of Label class.
|
What is AWT Label Class Declaration?
|
public class Label extends Component implements Accessible
|
What is AWT Label Fields?
|
The java.awt.Component class has following fields:
1.static int LEFT: It specifies that the label should be left justified.
2.static int RIGHT: It specifies that the label should be right justified.
3.static int CENTER: It specifies that the label should be placed in center
|
Can you give me the Label class Constructors?
|
Sr. no :1
Constructor: Label()
Description: It constructs an empty label.
Sr. no :2
Constructor: Label(String text)
Description: It constructs a label with the given string (left justified by default).
Sr. no :3
Constructor: Label(String text, int alignement)
Description: It constructs a label with the specified string and the specified alignment.
|
Can you give me the Label Class Methods?
|
Specified
Sr. no :1
Method name: void setText(String text)
Description:It sets the texts for label with the specified text..
Sr. no :2
Method name: void setAlignment(int alignment)
Description:It sets the alignment for label with the specified alignment.
Sr. no :3
Method name: String getText()
Description:It gets the text of the label
Sr. no :4
Method name: int getAlignment()
Description: It gets the current alignment of the label.
Sr. no :5
Method name: void addNotify()
Description: It creates the peer for the label
Sr. no :6
Method name: AccessibleContext getAccessibleContext()
Description:It gets the Accessible Context associated with the label.
Sr. no :7
Method name: protected String paramString()
Description: It returns the string the state of the label.
|
Can you provide the Java AWT Label Example with ActionListener?
|
In the following example, we are creating the objects of TextField, Label and Button classes and adding them to the Frame. Using the actionPerformed() method an event is generated over the button. When we add the website in the text field and click on the button, we get the IP address of website.
LabelExample2.java
import java.awt.*;
import java.awt.event.*;
// creating class which implements ActionListener interface and inherits Frame class
public class LabelExample2 extends Frame implements ActionListener{
// creating objects of TextField, Label and Button class
TextField tf;
Label l;
Button b;
// constructor to instantiate the above objects
LabelExample2() {
tf = new TextField();
tf.setBounds(50, 50, 150, 20);
l = new Label();
l.setBounds(50, 100, 250, 20);
b = new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);
add(tf);
add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
// defining actionPerformed method to generate an event
public void actionPerformed(ActionEvent e) {
try {
String host = tf.getText();
String ip = java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch (Exception ex) {
System.out.println(ex);
}
}
// main method
public static void main(String[] args) {
new LabelExample2();
}
}
|
What is Java AWT TextField?
|
The object of a TextField class is a text component that allows a user to enter a single line text and edit it. It inherits TextComponent class, which further inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the event is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then the ActionEvent may be fired by pressing return key. The event is handled by the ActionListener interface.
|
What is AWT TextField Class Declaration?
|
public class TextField extends TextComponent
|
Can you give me the TextField Class constructors?
|
Sr. no: 1
Constructor: TextField()
Description: It constructs a new text field component.
Sr. no:2
Constructor: TextField(String text)
Description: It constructs a new text field initialized with the given string text to be displayed.
Sr. no:3
Constructor: TextField(int columns)
Description: It constructs a new textfield (empty) with given number of columns.
Sr. no:4
Constructor: TextField(String text, int columns)
Description: It constructs a new text field with the given text and given number of columns (width).
|
Can you give me the Method Inherited?
|
The AWT TextField class inherits the methods from below classes:
1.java.awt.TextComponent
2.java.awt.Component
3.java.lang.Object
|
Can you provide the Java AWT TextField Example?
|
TextFieldExample1.java
// importing AWT class
import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");
// creating objects of textfield
TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
|
What is Java AWT TextArea?
|
The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area becomes larger than the viewable area, the scroll bar appears automatically which helps us to scroll the text up and down, or right and left.
|
What is AWT TextArea Class Declaration?
|
public class TextArea extends TextComponent
|
Can you provide the Fields of TextArea Class?
|
The fields of java.awt.TextArea class are as follows:
-static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical scrollbars.
-static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal scrollbar.
–static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar.
-static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area.
|
Can you give me the Class constructors?
|
Sr. no: 1
Constructor: TextArea()
Description: It constructs a new and empty text area with no text in it.
Sr. no: 2
Constructor: TextArea (int row, int column)
Description: It constructs a new text area with specified number of rows and columns and empty string as text.
Sr. no: 3
Constructor: TextArea (String text)
Description: It constructs a new text area and displays the specified text in it.
Sr. no: 4
Constructor: TextArea (String text, int row, int column)
Description: It constructs a new text area with the specified text in the text area and specified number of rows and columns.
Sr. no: 5
Constructor: TextArea (String text, int row, int column, int scrollbars)
Description: It construcst a new text area with specified text in text area and specified number of rows and columns and visibility.
|
Can you give me the TetArea Class Methods?
|
Sr. no:1
Method name: void addNotify()
Description:It creates a peer of text area.
Sr. no:2
Method name:void append(String str)
Description: It appends the specified text to the current text of text area.
Sr. no:3
Method name: AccessibleContext getAccessibleContext()
Description: It returns the accessible context related to the text area
Sr. no:4
Method name: int getColumns()
Description: It returns the number of columns of text area.
Sr. no:5
Method name: Dimension getMinimumSize()
Description: It determines the minimum size of a text area.
Sr. no:6
Method name: Dimension getMinimumSize(int rows, int columns)
Description: It determines the minimum size of a text area with the given number of rows and columns.
Sr. no:7
Method name: Dimension getPreferredSize()
Description: It determines the preferred size of a text area.
Sr. no:8
Method name: Dimension preferredSize(int rows, int columns)
Description: It determines the preferred size of a text area with given number of rows and columns.
Sr. no:9
Method name: int getRows()
Description: It returns the number of rows of text area.
Sr. no:10
Method name: int getScrollbarVisibility()
Description: It returns an enumerated value that indicates which scroll bars the text area uses.
Sr. no:11
Method name: void insert(String str, int pos)
Description: It inserts the specified text at the specified position in this text area.
Sr. no:12
Method name: protected String paramString()
Description: It returns a string representing the state of this TextArea.
Sr. no:13
Method name: void replaceRange(String str, int start, int end)
Description: It replaces text between the indicated start and end positions with the specified replacement text.
Sr. no:14
Method name: void setColumns(int columns)
Description: It sets the number of columns for this text area.
Sr. no:15
Method name: void setRows(int rows)
Description: It sets the number of rows for this text area.
|
Can you provide the Java AWT TextArea Example?
|
The below example illustrates the simple implementation of TextArea where we are creating a text area using the constructor TextArea(String text) and adding it to the frame.
TextAreaExample .java
//importing AWT class
import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to javatpoint");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}
|
Can you give me the Java AWT TextArea Example with ActionListener?
|
The following example displays a text area in the frame where it extends the Frame class and implements ActionListener interface. Using ActionListener the event is generated on the button press, where we are counting the number of character and words entered in the text area.
TextAreaExample2.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// our class extends the Frame class to inherit its properties
// and implements ActionListener interface to override its methods
public class TextAreaExample2 extends Frame implements ActionListener {
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
// constructor to instantiate
TextAreaExample2() {
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
// adding ActionListener to button
b.addActionListener(this);
// adding components to frame
add(l1);
add(l2);
add(area);
add(b);
// setting the size, layout and visibility of frame
setSize(400, 450);
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
// main method
public static void main(String[] args) {
new TextAreaExample2();
}
}
|
What is Java AWT Checkbox?
|
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
|
What is AWT Checkbox Class Declaration?
|
public class Checkbox extends Component implements ItemSelectable, Accessible
|
Can you give me the Method inherited by Checkbox?
|
Sr. no:1
Constructor: Checkbox()
Description: It constructs a checkbox with no string as the label.
Sr. no:2
Constructor: Checkbox(String label)
Description: It constructs a checkbox with the given label.
Sr. no:3
Constructor: Checkbox(String label, boolean state)
Description: It constructs a checkbox with the given label and sets the given state.
Sr. no:4
Constructor: Checkbox(String label, boolean state, CheckboxGroup group)
Description: It constructs a checkbox with the given label, set the given state in the specified checkbox group.
Sr. no:5
Constructor: Checkbox(String label, CheckboxGroup group, boolean state)
Description: It constructs a checkbox with the given label, in the given checkbox group and set to the specified state.
|
Can you give me the Checkbox Class Methods?
|
Sr. no: 1
Method name: void addItemListener(ItemListener IL)
Description: It adds the given item listener to get the item events from the checkbox.
Sr. no:2
Method name: AccessibleContext getAccessibleContext()
Description: It fetches the accessible context of checkbox.
Sr. no:3
Method name: void addNotify()
Description: It creates the peer of checkbox.
Sr. no:4
Method name: CheckboxGroup getCheckboxGroup()
Description: It determines the group of checkbox.
Sr. no:5
Method name: ItemListener[] getItemListeners()
Description: It returns an array of the item listeners registered on checkbox.
Sr. no:6
Method name: String getLabel()
Description: It fetched the label of checkbox.
Sr. no:7
Method name: T[] getListeners(Class listenerType)
Description: It returns an array of all the objects registered as FooListeners.
Sr. no:8
Method name: Object[] getSelectedObjects()
Description: It returns an array (size 1) containing checkbox label and returns null if checkbox is not selected.
Sr. no:9
Method name: boolean getState()
Description: It returns true if the checkbox is on, else returns off.
Sr. no:10
Method name: protected String paramString()
Description: It returns a string representing the state of checkbox.
Sr. no:11
Method name: protected void processEvent(AWTEvent e)
Description: It processes the event on checkbox.
Sr. no:12
Method name: protected void processItemEvent(ItemEvent e)
Description: It process the item events occurring in the checkbox by dispatching them to registered ItemListener object.
Sr. no:13
Method name: void removeItemListener(ItemListener l)
Description: It removes the specified item listener so that the item listener doesn't receive item events from the checkbox anymore.
Sr. no:14
Method name: void setCheckboxGroup(CheckboxGroup g)
Description: It sets the checkbox's group to the given checkbox.
Sr. no:15
Method name: void setLabel(String label)
Description: It sets the checkbox's label to the string argument.
Sr. no:16
Method name: void setState(boolean state)
Description: It sets the state of checkbox to the specified state.
|
Can you provide the Java AWT Checkbox Example?
|
In the following example we are creating two checkboxes using the Checkbox(String label) constructo and adding them into the Frame using add() method.
CheckboxExample1.java
// importing AWT class
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
|
Can you give me the Java AWT Checkbox Example with ItemListener?
|
In the following example, we have created two checkboxes and adding them into the Frame. Here, we are adding the ItemListener with the checkbox which displays the state of the checkbox (whether it is checked or unchecked) using the getStateChange() method.
CheckboxExample2.java
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
// constructor to initialize
CheckboxExample2() {
// creating the frame
Frame f = new Frame ("CheckBox Example");
// creating the label
final Label label = new Label();
// setting the alignment, size of label
label.setAlignment(Label.CENTER);
label.setSize(400,100);
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
// adding the checkbox to frame
f.add(checkbox1);
f.add(checkbox2);
f.add(label);
// adding event to the checkboxes
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CheckboxExample2();
}
}
|
What is Java AWT CheckboxGroup?
|
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits the object class.
|
What is AWT CheckboxGroup Class Declaration?
|
public class CheckboxGroup extends Object implements Serializable
|
Can you provide the Java AWT CheckboxGroup Example?
|
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
|
Can you give me the Java AWT CheckboxGroup Example with ItemListener?
|
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
|
What is Java AWT Choice?
|
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits Component class.
|
What is AWT Choice Class Declaration?
|
public class Choice extends Component implements ItemSelectable, Accessible
|
Can you give me the Choice Class constructor?
|
Constructor: Choice()
Description: It constructs a new choice menu.
|
Can you give me the Choice Class Methods?
|
Sr. no:1
Method name: void add(String item)
Description: It adds an item to the choice menu.
.
Sr. no:2
Method name: void addItemListener(ItemListener l)
Description: It adds the item listener that receives item events from the choice menu.
Sr. no:3
Method name: void addNotify()
Description: It creates the peer of choice.
Sr. no:4
Method name: AccessibleContext getAccessibleContext()
Description: It gets the accessbile context related to the choice.
Sr. no:5
Method name: String getItem(int index)
Description: It gets the item (string) at the given index position in the choice menu.
Sr. no:6
Method name: int getItemCount()
Description: It returns the number of items of the choice menu.
Sr. no:7
Method name: ItemListener[] getItemListeners()
Description: It returns an array of all item listeners registered on choice.
Sr. no:8
Method name: T[] getListeners(Class listenerType)
Description: Returns an array of all the objects currently registered as FooListeners upon this Choice.
Sr. no:9
Method name: int getSelectedIndex()
Description: Returns the index of the currently selected item.
Sr. no:10
Method name: String getSelectedItem()
Description: Gets a representation of the current choice as a string.
Sr. no:11
Method name:Object[] getSelectedObjects()
Description: Returns an array (length 1) containing the currently selected item.
Sr. no:12
Method name: void insert(String item, int index)
Description: Inserts the item into this choice at the specified position.
Sr. no:13
Method name: protected String paramString()
Description: Returns a string representing the state of this Choice menu.
Sr. no:14
Method name: protected void processEvent(AWTEvent e)
Description: It processes the event on the choice.
Sr. no:15
Method name: protected void processItemEvent (ItemEvent e)
Description: Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.
Sr. no:16
Method name: void remove(int position)
Description: It removes an item from the choice menu at the given index position.
Sr. no:17
Method name: void remove(String item)
Description: It removes the first occurrence of the item from choice menu.
Sr. no:18
Method name: void removeAll()
Description: It removes all the items from the choice menu.
Sr. no:19
Method name: void removeItemListener (ItemListener l)
Description: It removes the mentioned item listener. Thus is doesn't receive item events from the choice menu anymore.
Sr. no:20
Method name: void select(int pos)
Description: It changes / sets the selected item in the choice menu to the item at given index position.
Sr. no:21
Method name: void select(String str)
Description: It changes / sets the selected item in the choice menu to the item whose string value is equal to string specified in the argument.
|
Can you provide the Java AWT Choice Example?
|
In the following example, we are creating a choice menu using Choice() constructor. Then we add 5 items to the menu using add() method and Then add the choice menu into the Frame.
ChoiceExample1.java
// importing awt class
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
|
Can you give me the Java AWT Choice Example with ActionListener?
|
In the following example, we are creating a choice menu with 5 items. Along with that we are creating a button and a label. Here, we are adding an event to the button component using addActionListener(ActionListener a) method i.e. the selected item from the choice menu is displayed on the label when the button is clicked.
ChoiceExample2.java
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class ChoiceExample2 {
// class constructor
ChoiceExample2() {
// creating a frame
Frame f = new Frame();
// creating a final object of Label class
final Label label = new Label();
// setting alignment and size of label component
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
// creating a button
Button b = new Button("Show");
// setting the bounds of button
b.setBounds(200, 100, 50, 20);
// creating final object of Choice class
final Choice c = new Choice();
// setting bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding 5 items to choice menu
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
// adding above components into the frame
f.add(c);
f.add(label);
f.add(b);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// adding event to the button
// which displays the selected item from the list when button is clicked
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
// main method
public static void main(String args[])
{
new ChoiceExample2();
}
}
|
What is Java AWT List?
|
The object of List class represents a list of text items. With the help of the List class, user can choose either one item or multiple items. It inherits the Component class.
|
What is AWT List class Declaration?
|
public class List extends Component implements ItemSelectable, Accessible
|
Can you give me the AWT List Class Constructors?
|
Sr. no:1
Constructor: List()
Description: It constructs a new scrolling list.
Sr. no:2
Constructor:List(int row_num)
Description:It constructs a new scrolling list initialized with the given number of rows visible.
Sr. no:3
Constructor: List(int row_num, Boolean multipleMode)
Description: It constructs a new scrolling list initialized which displays the given number of rows.
|
Can you give me the List Class Methods?
|
Sr. no:1
Method name: void add(String item)
Description: It adds the specified item into the end of scrolling list.
Sr. no:2
Method name: void add(String item, int index)
Description: It adds the specified item into list at the given index position.
Sr. no:3
Method name: void addActionListener(ActionListener l)
Description: It adds the specified action listener to receive action events from list.
Sr. no:4
Method name: void addItemListener(ItemListener l)
Description: It adds specified item listener to receive item events from list.
Sr. no:5
Method name: void addNotify()
Description: It creates peer of list.
Sr. no:6
Method name: void deselect(int index)
Description: It deselects the item at given index position.
Sr. no:7
Method name: AccessibleContext getAccessibleContext()
Description: It fetches the accessible context related to the list.
Sr. no:8
Method name: ActionListener[] getActionListeners()
Description: It returns an array of action listeners registered on the list.
Sr. no:9
Method name: String getItem(int index)
Description: It fetches the item related to given index position.
Sr. no:10
Method name: int getItemCount()
Description: It gets the count/number of items in the list.
Sr. no:11
Method name: ItemListener[] getItemListeners()
Description: It returns an array of item listeners registered on the list.
Sr. no:12
Method name: String[] getItems()
Description: It fetched the items from the list.
Sr. no:13
Method name:Dimension getMinimumSize()
Description: It gets the minimum size of a scrolling list.
Sr. no:14
Method name: Dimension getMinimumSize(int rows)
Description: It gets the minimum size of a list with given number of rows.
Sr. no:15
Method name: Dimension getPreferredSize()
Description: It gets the preferred size of list.
Sr. no:16
Method name: Dimension getPreferredSize(int rows)
Description: It gets the preferred size of list with given number of rows.
Sr. no:17
Method name: int getRows()
Description: It fetches the count of visible rows in the list.
Sr. no:18
Method name: int getSelectedIndex()
Description: It fetches the index of selected item of list.
Sr. no:19
Method name: int[] getSelectedIndexes()
Description: It gets the selected indices of the list.
Sr. no:20
Method name: String getSelectedItem()
Description: It gets the selected item on the list.
Sr. no:21
Method name:String[] getSelectedItems()
Description: It gets the selected items on the list.
Sr. no:22
Method name: Object[] getSelectedObjects()
Description: It gets the selected items on scrolling list in array of objects.
Sr. no:23
Method name: int getVisibleIndex()
Description: It gets the index of an item which was made visible by method makeVisible()
Sr. no:24
Method name:void makeVisible(int index)
Description: It makes the item at given index visible.
Sr. no:25
Method name: boolean isIndexSelected(int index)
Description: It returns true if given item in the list is selected.
Sr. no:26
Method name: boolean isMultipleMode()
Description: It returns the true if list allows multiple selections.
Sr. no:27
Method name: protected String paramString()
Description: It returns parameter string representing state of the scrolling list.
Sr. no:28
Method name: protected void processActionEvent(ActionEvent e)
Description: It process the action events occurring on list by dispatching them to a registered ActionListener object.
Sr. no:29
Method name: protected void processEvent(AWTEvent e)
Description: It process the events on scrolling list.
Sr. no:30
Method name:protected void processItemEvent(ItemEvent e)
Description: It process the item events occurring on list by dispatching them to a registered ItemListener object.
Sr. no:31
Method name: void removeActionListener(ActionListener l)
Description: It removes specified action listener. Thus it doesn't receive further action events from the list.
Sr. no:32
Method name: void removeItemListener(ItemListener l)
Description: It removes specified item listener. Thus it doesn't receive further action events from the list.
Sr. no:33
Method name: void remove(int position)
Description: It removes the item at given index position from the list.
Sr. no:34
Method name:void remove(String item)
Description: It removes the first occurrence of an item from list.
Sr. no:35
Method name: void removeAll()
Description: It removes all the items from the list.
Sr. no:36
Method name: void replaceItem(String newVal, int index)
Description: It replaces the item at the given index in list with the new string specified.
Sr. no:37
Method name: void select(int index)
Description: It selects the item at given index in the list.
Sr. no:38
Method name:void setMultipleMode(boolean b)
Description: It sets the flag which determines whether the list will allow multiple selection or not.
Sr. no:39
Method name:void removeNotify()
Description: It removes the peer of list.
|
Can you provide the Java AWT List Example?
|
In the following example, we are creating a List component with 5 rows and adding it into the Frame.
ListExample1.java
// importing awt class
import java.awt.*;
public class ListExample1
{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);
// setting the position of list component
l1.setBounds(100, 100, 75, 75);
// adding list items into the list
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
// adding the list to frame
f.add(l1);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ListExample1();
}
}
|
Can you give me the Java AWT List Example with ActionListene?
|
In the following example, we are creating two List components, a Button and a Label and adding them into the frame. Here, we are generating an event on the button using the addActionListener(ActionListener l) method. On clicking the button, it displays the selected programming language and the framework.
ListExample2.java
// importing awt and event class
import java.awt.*;
import java.awt.event.*;
public class ListExample2
{
// class constructor
ListExample2() {
// creating the frame
Frame f = new Frame();
// creating the label which is final
final Label label = new Label();
// setting alignment and size of label
label.setAlignment(Label.CENTER);
label.setSize(500, 100);
// creating a button
Button b = new Button("Show");
// setting location of button
b.setBounds(200, 150, 80, 30);
// creating the 2 list objects of 4 rows
// adding items to the list using add()
// setting location of list components
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
// adding List, Label and Button to the frame
f.add(l1);
f.add(l2);
f.add(label);
f.add(b);
// setting size, layout and visibility of frame
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
// generating event on the button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()) {
data += frame + " ";
}
label.setText(data);
}
});
}
// main method
public static void main(String args[])
{
new ListExample2();
}
}
|
What is Java AWT Canvas?
|
The Canvas class controls and represents a blank rectangular area where the application can draw or trap input events from the user. It inherits the Component class.
|
What is AWT Canvas class Declaration?
|
public class Canvas extends Component implements Accessible
|
What are the Constructors of the Canvas Class?
|
Constructors of Canvas Class
Constructor: Canvas()
Description: It constructs a new Canvas.
Constructor: Canvas(GraphicConfiguration config)
Description: It constructs a new Canvas with the given Graphic Configuration object.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.