All_in_one_Java
All_in_one_Java
Example:
Secure
Java is said to be more secure programming language because it does not have pointers concept,
java provides a feature "applet" which can be embedded into a web application. The applet in
java does not allow access to other parts of the computer, which keeps away from harmful
programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide
variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object.
It supports all the features of the object-oriented programming paradigm. The primitive data
types java also implemented as objects using wrapper classes, but still, it allows primitive data
types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java
has a strong memory management mechanism (garbage collector), java is a strictly typed
language, it has a strong set of exception handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code so that it
runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its
simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI),
this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
3. What is an array? How do you declare the array in java? Give examples
An array is a collection of similar data values with a single name. An array can also be defined as,
a special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in
java is organized using index values. The index value of an array starts with '0' and ends with
'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
Creating an array
One Dimensional Array
In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the
following syntax to create an array.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example
public class ArrayExample {
public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax
to create two-dimensional array.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
4. Write the significance of Java Virtual Machine(Diagram) and Byte Code.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
The JVM performs following operation:
Loads code, Verifies code, Executes code,Provides runtime environment
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
5. What is inheritance ? Demonstrate various forms of inheritance with suitable program segments.
How to prevent a class from inheritance?
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows one
class (subclass or derived class) to inherit properties and behaviors (fields and methods)
from another class (superclass or base class).
Java supports inheritance, which enables you to create a hierarchy of classes, promoting
code reuse and extending the functionality of existing classes.
The subclass can add its own fields and methods or override the superclass's methods.
Syntax:
class Subclass extends Superclass
{
// Subclass members
}
A subclass constructor can call a superclass constructor using super(...).If the subclass
constructor doesn't explicitly call super(...), the default no-argument constructor of the
superclass is called automatically.
Subclasses can override (provide a new implementation for) methods inherited from the
superclass.
Public and protected members of the superclass are accessible in the subclass.
We can prevent a class from being inherited (i.e., make it "final") by declaring the class with
the final keyword. When a class is marked as final, it cannot be extended by any other class.
Syntax:
Types of Inheritance
Single Inheritance:
A subclass inherits from only one superclass. Java supports single inheritance directly.
Example:
class GrandParent
{
private String gname;
public void eat(String s)
{
gname=s;
System.out.println(gname);
System.out.println("eat method of Grandparent class executed");
}
}
class Child extends GrandParent
{
protected String cname="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
Child men=new Child();
men.eat("ali");
men.drink();
System.out.println("Grandparent name:"+men.gname);
System.out.println("Child name:"+men.cname);
}
}
Multiple Inheritance (Through Interfaces):
Java does not support multiple inheritance directly, where a class inherits from multiple classes.
However, multiple inheritance-like behavior can be achieved through interfaces,
Multilevel Inheritance:
A class inherits from another class, which in turn inherits from another class. It creates a chain of
inheritance relationships.
Example:
class GrandParent
{
private String gname;
public void eat(String s)
{
gname=s;
System.out.println(gname);
System.out.println("eat method of Grandparent class executed");
}
}
class Child extends GrandParent
{
protected String cname="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class GrandChild extends Child
{
String gcname="anthony";
public void sleep()
{
System.out.println("sleep method of Grandchild class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
GrandChild men=new GrandChild();
men.eat("ali");
men.drink();
men.sleep();
//System.out.println("Grandparent name:"+men.gname);
System.out.println("Child name:"+men.cname);
System.out.println("GrandpChild name:"+men.gcname);
System.out.println("Main method");
}
}
Hierarchical Inheritance:
multiple classes inherit from a single superclass. This creates a branching hierarchy, with several
subclasses deriving from a common superclass.
class Parent
{
private String pname;
public void eat(String s)
{
pname=s;
System.out.println(pname);
System.out.println("eat method of parent class executed");
}
}
class Child1 extends Parent
{
protected String cname1="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class Child2 extends Parent
{
String cname2="anthony";
public void sleep()
{
System.out.println("sleep method of Grandchild class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
Child1 men1=new Child1();
men1.eat("ali");
men1.drink();
Child2 men2=new Child2();
men2.eat("ali");
men2.sleep();
System.out.println("parent name:"+men1.pname);
System.out.println("Child1 name:"+men1.cname1);
System.out.println("Child2 name:"+men2.cname2);
}
}
6. What is the purpose of constructor in Java programming? Explain constructor overloading in java
Constructor
Constructor is a special type of method that is used for initializing objects when they are
created.
Constructors have the same name as the class and do not have a return type, not even
void. They are called automatically when an object is created using the new keyword.
Constructors can take one or more parameters.
Constructors can have access modifiers.
If you don't define any constructors in your class, Java provides a default constructor
with no arguments.
You can define multiple constructors in a class, and one constructor can call another
using this(keyword).
Constructors of a subclass must call a constructor of the superclass either explicitly using
super(...) or implicitly.
Constructor overloading means defining two or more constructors within the same class.
In this case the constructors are said to be overloaded and the process is called
constructor overloading.
Now the question arises how Java determines which constructor to call, It is done by
determining the type of arguments and the number of arguments in the constructor’s
definition.
Constructor overloading is similar to method overloading, but it involves constructors
instead.
ConstructorOverloadingExample
public class ConsOver
{
int age;
String name;
public ConsOver(int a, String n)
{
age = a;
name = n;
}
public ConsOver(String n)
{
name = n;
}
public static void main(String[] args)
{
ConsOver u1 = new ConsOver(20, "Ali");
System.out.println("Age:" + u1.age);
System.out.println("Name:" + u1.name);
ConsOver u2 = new ConsOver("Ahmed");
System.out.println("Age:" + u2.age);
System.out.println("Name:" + u2.name);
}
}
example.printMessage(3.5, 2.7); // Calls the third method with two double parameters
}
}
2. Runtime Polymorphism
Method overriding occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass.
Note: By using the concept of method overriding we can achieve this runtime poly
morphism.
It is also called as Dynamic polymorphism or late binding.
Method overriding
If we want to achieve the run time polymorphism then we have to use method
overriding.
Method overriding means declaring 2 methods with same method signature in 2
different classes which are having IS-A relation.
While Method overriding and writing the method signature, we must follow
following rules.
• Method name must be same
• List of parameters must be same
• Return type must be same
• Private, final and static methods cannot be overridden.
• There must be an IS-A relationship between classes (inheritance).
MethodOverridingExample
class Shape
{
void display() {
System.out.println("This is a shape.");
}
}
8. With suitable program segments examine the usage of “super‟ “final” and “this” keywords.
Super keyword
The super keyword in Java is used to refer to the immediate parent class or superclass of
a derived (subclass) class.
It is primarily used to access members (fields and methods) of the superclass that may
be overridden or hidden by members in the subclass.
The super keyword is often used in scenarios where there is a need to differentiate
between the members of the subclass and the members of the superclass.
SuperKeywordExample
void displayNames()
{
System.out.println("Superclass name: " + super.name); // Accesses the superclass's name
System.out.println("Subclass name: " + name);
}
}
This keyword
The this keyword in Java is a reference to the current instance of the class in which it's
used.
It's used to differentiate between instance variables (fields) and parameters or local
variables with the same name.
The this keyword is commonly used in constructors and instance methods to access and
manipulate instance variables and methods.
ThisKeyword
9. What is encapsulation and how is it achieved in java. Explain the significance of default,public,
protected and private access specifiers in inheritance.
The binding of data (attributes or fields) and methods into a single unit is called encapsulation.
In Java, encapsulation is achieved by using access modifiers to control the visibility of fields and
methods within a class.
There are four types of access modifiers in Java:
public: The member is accessible from any other class.
protected: The member is accessible within its own package and by subclasses.
default (no modifier): The member is accessible only within its own package.
private: The member is accessible only within its own class.
Encapsulation provides a mechanism for controlling access to data and methods, Data
Hiding, promoting code organization, reusability, maintainability, and security in your
object-oriented programming
EncapsulationExample
class Student
{
public String ename; // private field
private int eage; // private field
public void setInfo(String name, int age)
{
ename = name;
eage=age;
}
class EncapsulationEx
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.setInfo("Arjun",20);
s1.getInfo();
//System.out.println(s1.ename);
//System.out.println(s1.eage);
Unit-2
10. What is meant by data abstraction? How to achieve data abstraction(abstract classes and
interfaces) in java. How to inherit an extend interface to another?(V.imp) (or)
11. What is interface? Write a java program to illustrate the use of interface(V.imp)
Abstraction
Abstraction in Java is a process of hiding the implementation details from the user and showing
only the functionality to the user.
Abstraction in Java can be achieved using
a. Abstract classes
In Java a class preceded by abstract keyword is called abstract class.
An abstract class may or may not have abstract methods.
We cannot create object for abstract class.
It is used to achieve abstraction but it does not provide 100% abstraction because it can have
concrete methods.
It can have abstract and non-abstract methods.
Abstract methods should be present inside abstract class only.
Abstract class need to be inherited by other class (extended) and its abstract methods need to
be overridden. Hence in abstract class only the abstract methods are overridden.
Abstract class can contain constructors and static methods too but they are not declared
abstract.
Note : Remember that abstract class cannot be instantiated , i.e. we can’t create an object of an
abstract class , but can only create a reference variable to refer to other class object which is
helpful in run-time polymorphism.
o Syntax : abstract class class_name {
}
AbstractClassExample
class AbstractClassEx
{
public static void main(String[] args)
{
animal r=new Dog(); // superclass has capability of storing childclass objects
}
}
Abstract method
Method that are declared without any body within an abstract class are called abstract method.
Syntax: abstract return_type function_name (); //No definition
The method body will be defined by its subclass.
Abstract method can never be final and static. Any class that extends an abstract class must
implement all the abstract methods.
AbstractMethodExample
class AbstractMethodEx
{
public static void main(String[] args)
{
Dog d=new Dog();
d.sound();
Lion l=new Lion();
l.sound();
}
}
b. Interfaces
Interface in Java is the way to achieve complete abstraction. Also interface in Java is used to
achieve multiple inheritance by implementing interfaces.
Interface is similar to class and contains only public, abstract methods and public, static and final
fields. Interfaces differ from class in the way that interface cannot contains constructors and non
– abstract methods. Also interfaces cannot be instantiated.
Interfaces should be implemented by using implements The class that implements the interface
should define all the methods of interface and the method should be declared public.
Interface only tells what a class contains and the behavior is defined in the class that implements
it. Advantages
Reduces complexity, Avoid code duplication, Eases the burden of maintenance,Increase security
and confidentiality
Interface Example
import java.util.Scanner;
interface client
{
void input(); //public and abstract methods
void output();
}
class Customer implements client
{
String name; double salary;
public void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter your name:");
name=s.nextLine();
System.out.println("Enter your salary:");
salary=s.nextInt();
}
public void output()
{
System.out.println("Enter your name:"+name);
System.out.println("Enter your salary:"+salary);
}
}
class InterfacesEx
{
public static void main(String[] args)
{
client c=new Customer();
c.input();
c.output();
}
}
12. Define a package. How to import packages? Explain with illustrations. (V.imp)
Packages in java are like container which keeps classes, interfaces and sub-packages in an
organized way. You can visualize packages as folders in your computer. Folder houses sub-folders
and other files.
Similarly, Java package contains collection of related classes, interfaces and sub-packages.
Advantages:
The main objectives of packages are:
a. To resolve name confects.
b. To improve modularity of the application.
c. To provide security.
d. Easy to locate the related classes
e. Reuse the existing classes in packages
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Some of the existing packages in Java are −
1. java.lang: Contains language support classes(e.g classed which defines primitive data
types,math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support; for Date / Time operations.
Import statement
import: This is the Java keyword used to indicate that you are importing a class or
package.
packageName: This is the name of the package containing the class you want to import.
ClassName: This is the name of the class (or other type) you want to import from the
specified package.
the import statement is used to bring classes, interfaces, and other types defined in
other packages into the current file's scope.
It simplifies the usage of classes from different packages by allowing you to refer to
them directly by their simple names, rather than their fully qualified names (which
include the package name).
Syntax: import java.packageName.ClassName;
package com.datasciencea;
class Packages
{
public static void main(String[] args)
{
System.out.println("Package demonstration");
}
}
compiling Java programs Inside packages
javac -d . Packages.java
Executing java Package file
Fully qualified path we should write inorder to execute.
java com/datasciencea/Packages
a. Purpose: The primary purpose of CLASSPATH is to tell the JVM where to find user-
defined classes and resources that are not part of the standard Java library.
b. Search Order: When a Java program attempts to load a class, the JVM looks for it in the
directories and JAR files specified in the CLASSPATH. It searches for classes in the order
they are listed in the CLASSPATH.
c. Default Value: If you do not explicitly set the CLASSPATH, the JVM uses a default
classpath, which includes the current directory (.). However, it's considered a best
practice to set the CLASSPATH explicitly for your application to avoid unexpected
behavior.
d. Setting CLASSPATH: You can set the CLASSPATH in several ways:
Environment Variable: You can set it as an environment variable on your system.
14. Demonstrate about File Input Stream and File Output Stream (V.imp)
In Java, FileInputStream and FileOutputStream are classes that allow you to read data from a file
(input) and write data to a file (output), respectively. They are part of the java.io package and are
commonly used for working with files. Below, I'll provide examples of how to use
FileInputStream and FileOutputStream to read from and write to a file.
import java.io.FileInputStream;
import java.io.IOException;
// Read bytes from the file until the end is reached (-1 indicates end of file)
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData); // Convert byte to char and print
}
import java.io.FileOutputStream;
import java.io.IOException;
b) Auto Boxing
The process of converting a primitive type value into its corresponding wrapper class object is
called autoboxing or simply boxing. For example, converting an int value to an Integer class
object.
The compiler automatically performs the autoboxing when a primitive type value has assigned to
an object of the corresponding wrapper class.
17. Write java program to copy content of one file to another file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
try {
// Create a FileInputStream for the source file
FileInputStream fis = new FileInputStream(sourceFileName);
// Read data from the source file and write it to the destination file
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
Unit-3
18. What is an Exception? Explain about the different types of exceptions (Checked and UnChecked
Exceptions)used in Java. How is an Exception handled in JAVA? Give example. And also write the
advantages of using Exception handling mechanism in a program.
Exception
An exception in java programming is an abnormal situation that is raised during the
program execution. In simple words, an exception is a problem that arises at the time of
program execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We
use the exception handling mechanism to avoid abnormal termination of program
execution.
Java programming language has the following class hierarchy to support the exception handling
mechanism.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
• Checked Exception - An exception that is checked by the compiler at the time of
compilation is called a checked exception.
• Unchecked Exception - An exception that cannot be caught by the compiler but occurs
at the time of program execution is called an unchecked exception.
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
• IOException
• FileNotFoundException
• ClassNotFoundException
• SQLException
• DataAccessException
• InstantiationException
• UnknownHostException
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions
import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use of
resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
• ArithmeticException
• NullPointerException
• NumberFormatException
• ArrayIndexOutOfBoundsException
• StringIndexOutOfBoundsException
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
class ExceptionEx1
{
public static void main(String[] args)
{
int a=100,b=0,c;
String str="sphn";
try
{
c=a/b; // risky code
int d=Integer.parseInt(str);
int arr[]={10,20,30};
System.out.println(c);
System.out.println(d);
System.out.println(arr[5]);
}
catch (ArithmeticException e1)
{
System.out.println("Error1 occurred");
}
catch(NumberFormatException e2)
{
System.out.println("Error2 occurred");
}
catch(ArrayIndexOutOfBoundsException e3)
{
System.out.println("Error3 occurred");
}
catch(Exception e4)
{
System.out.println(e4);
}
}
}
20. Explain how to create your own exception in Java program with an example
Creating own exception sub classes:
The Java programming language allow us to create our own exception classes which are basically
subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in Exception class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
Let's look at the following Java code that illustrates the creation of user-defined exception.
import java.util.Scanner;
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg);
}
}
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
It allows the computer to run two or more It allows the computer to run two or more threads
programs concurrently concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process requires seperate address space for each. Threads share same address space.
Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.
23. What is thread? How to create multiple threads in a program? List the benefits of multi-threaded
programming? Explain with an example.
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is a light weight process.
The java programming language provides two methods to create threads, and they are listed
below.
• Using Thread class (by extending Thread class)
• Uisng Runnable interface (by implementing Runnable interface)
Benefits of multi-threaded programming.
Example
class MultiDemo extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
System.out.println("We are learning Multi-threading");
}
}
class Remedial2
{
public static void main(String[] args) throws InterruptedException
{
MultiDemo t1=new MultiDemo();
MultiDemo t2=new MultiDemo();
t1.setName("Mithil");
t1.start();
Thread.sleep(2000);
t2.setName("Sai Teja");
t2.start();
Thread.sleep(2000);
System.out.println("Main Thread");
}
}
24. Explain the Java thread model (Life Cycle of a Thread). Illustrate with an example.
Life Cycle of a Thread
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is shown
in the following figure.
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep(
) method called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called,
resume( ) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.
25. What is synchronization? How to implement synchronization in Java. Justify the producer -
consumer problem using inter – thread communication.
Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. In the Multithreading concept, multiple threads try to access the shared resources at a
time to produce inconsistent results. The synchronization is necessary for reliable
communication between threads.
The main advantage of synchronization is we can resolve date inconsistency problems but the
disadvantage of synchronizion is it increases waiting time of the Thread and affects performance
of the system.
Inter – Thread communication
Inter – Thread communication or cooperation is a communication of two or more threads with
each other. It can be done by using the following methods.
wait(), notify(), notifyAll().
}
public synchronized int putItem(int item)
{
while (valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println(e);
}
this.item=item;
valueSet=true;
System.out.println("Produced:"+item);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e);
}
notify();
}
}
class Producer implements Runnable
{
ItemQueue iq;
public Producer(ItemQueue iq)
{
this.iq=iq;
Thread p=new Thread(this,"Producer");
p.start();
}
public void run()
{
int i=0;
while (true)
{
iq.putItem(i++);
}
}
}
class ProducerConsumer1
{
public static void main(String[] args)
{
ProducerConsumer1 pc=new ProducerConsumer1();
new Producer(pc);
new Consumer(pc);
}
}
List Interface
• It is the child interface of Collection
• If we want to represent a group of individual objects where duplicates are allowed and insertion
order is preserved. Then we should go for List.
• We can differentiate duplicate Objects and we can maintain insertion order by means of index
hence "index plays important role in List"
ArrayList Class
• ArrayList is an implementation class of Collection interface
• The underlying data structure is resizable (Internally it will use Array to store data)
• Duplicate Objects are allowed • Insertion order is preserved
• Heterogeneous Objects are allowed • Null insertion is possible
import java.util.ArrayList;
class ArrayListEx
{
public static void main(String[] args)
{
ArrayList<String> str= new ArrayList<String>();
str.add("Sphoorthy");
str.add("Engineering");
str.add("College");
System.out.println(str);
str.add(1,"University");
System.out.println(str);
str.remove(1);
str.set(2,"University");
System.out.println(str.get(2));
for (String s:str )
{
System.out.println(s);
}
str.clear();
System.out.println(str);
}
}
LinkedList Class
• LinkedList is one of the implementation classes of Collection interface • The underlying data
structure is double LinkedList.
• If our frequent operation is insertion or deletion in the middle then LinkedList is the best
choice.
• If our frequent operation is retrieval then LinkedList is not best option. • Duplicate Objects are
allowed and Insertion order is preserved.
• Heterogeneous Objects are allowed. • NULL insertion is possible.
• Implements Serializable and Cloneable interfaces but not RandomAccess.
• Note: Usually we can use linked list to implement Stacks and Queues.
LinkedListExample
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Create a LinkedList of strings
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to the LinkedList
linkedList.add("Alice");
linkedList.add("Bob");
linkedList.add("Charlie");
linkedList.add("David");
// Display the LinkedList
System.out.println("LinkedList: " + linkedList);
// Adding elements at specific positions
linkedList.addFirst("Eve"); // Add at the beginning
linkedList.addLast("Frank"); // Add at the end
linkedList.add(2, "Grace"); // Add at index 2
// Display the modified LinkedList
System.out.println("Modified LinkedList: " + linkedList);
// Accessing elements
String firstElement = linkedList.getFirst();
String lastElement = linkedList.getLast();
String elementAtIndex3 = linkedList.get(3);
System.out.println("First Element: " + firstElement);
System.out.println("Last Element: " + lastElement);
System.out.println("Element at Index 3: " + elementAtIndex3);
// Removing elements
linkedList.removeFirst();
linkedList.removeLast();
linkedList.remove(2);
// Display the final LinkedList
System.out.println("Final LinkedList: " + linkedList);
}
}
Vector Class
• Vector is the implementation class of List interface which is also used to store group of
individual objects where duplicate values are allowed.
• Vector is exactly similar to ArrayList but ArrayList is not a synchronized class where Vector is
a synchronized class
• Vector is also called legacy class because it is available from java 1.0 version.
import java.util.Vector;
import java.util.Iterator;
public class VectorExample {
public static void main(String[] args) {
// Create a Vector of strings
Vector<String> vector = new Vector<>();
// Adding elements to the Vector
vector.add("Alice");
vector.add("Bob");
vector.add("Charlie");
vector.add("David");
// Display the Vector
System.out.println("Vector: " + vector);
// Accessing elements using an enhanced for loop (for-each loop)
for (String element : vector) {
System.out.println("Element: " + element);
}
// Updating an element at a specific index
vector.set(2, "Eve");
// Removing an element
vector.remove(3);
// Display the modified Vector
System.out.println("Modified Vector: " + vector);
// Checking if an element exists in the Vector
String searchElement = "Charlie";
boolean containsElement = vector.contains(searchElement);
System.out.println(searchElement + " exists in Vector: " + containsElement);
}
}
Stack Class
• Stack is a child class of Vector and implements List interface
• Stack stores a group of objects b using a mechanism called LIFO
• LIFO stands for Last in first out , it means last inserted element deleted first.
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// Create a Stack of integers
Stack<Integer> stack = new Stack<>();
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
// Display the stack
System.out.println("Stack: " + stack);
// Pop elements from the stack
int poppedElement = stack.pop();
System.out.println("Popped Element: " + poppedElement);
// Peek at the top element without removing it
int topElement = stack.peek();
System.out.println("Top Element: " + topElement);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("Is Stack Empty: " + isEmpty);
// Search for an element in the stack
int searchElement = 30;
int position = stack.search(searchElement);
if (position != -1) {
System.out.println(searchElement + " found at position " + position + " from the top of
the stack.");
} else {
System.out.println(searchElement + " not found in the stack.");
}
}
}
Difference between ArrayList and Vector
Set Interface
• A set is a collection that does not allow duplicate elements.
• It models the mathematical set abstraction and provides a useful way to manage a group of
unique objects.
• Sets do not guarantee any specific order of elements. The order in which elements are stored
may not be the same as the order in which they were added.
• There are several classes that implement the Set interface in Java, with HashSet,
LinkedHashSet, and TreeSet being the most commonly used ones.
Here's how you can use these implementations:
1. HashSet Implementation:
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> set = new HashSet<>();
// Add elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Banana"); // Duplicate, will not be added
// Print the elements of the HashSet
for (String element : set) {
System.out.println(element);
}
}
}
2. LinkedHashSet Implementation:
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Create a LinkedHashSet
Set<String> set = new LinkedHashSet<>();
// Add elements to the LinkedHashSet
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Banana"); // Duplicate, will not be added
// Print the elements of the LinkedHashSet
for (String element : set) {
System.out.println(element);
}
}
}
3. TreeSet Implementation:
import java.util.Set;
import java.util.TreeSet;
Unit-5
26. What is an Applet? Draw Applet Hierarchy and Create a simple applet to display a smiley picture
using Graphics class methods.
Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Applet cannot be executed independently. Applets can only be executed inside a Java
compatible container, such as a browser or Appletviewer.
Applets can be embedded in HTML pages and downloaded over the Internet.
Applet code is refreshed automatically each time the user revisits the hosting website.
Therefore, keeps full application up to date on each client desktop on which it is running.
Applet Hierarchy
Applet Code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
27. What is Event Handling? Write a short note on delegation event model or Event Handling.
Draw Java AWT Hierarchy, Limitations of AWT. Difference between AWT and Swings.
Event Handling:
Event handling is a crucial aspect of graphical user interfaces (GUIs) in software development. It
involves the management and response to events or user interactions, such as mouse clicks,
keyboard inputs, button presses, and window resizing. Event handling allows developers to
create interactive applications that respond to user actions.
In Java, event handling is typically associated with GUI frameworks like AWT (Abstract Window
Toolkit) and Swing. The process involves the following key components:
The Delegation Event Model is the event-handling mechanism used in Java's AWT and Swing
libraries. It is based on the concept of event delegation, where the responsibility for handling
events is delegated to specific event listeners rather than being handled directly by the event
source.
In this model:
Event sources (e.g., buttons, components) do not handle events themselves.
Event sources maintain a list of registered event listeners (also called event listeners or
event handlers).
When an event occurs, the event source dispatches the event to the appropriate event
listener by calling the listener's event-handling method.
For example, when you click a button in a Swing application, the button does not directly handle
the click event. Instead, it delegates the event to a registered ActionListener, which responds to
the event by executing a specific action, such as opening a dialog or updating the user interface.
Java AWT Hierarchy:
Limitations of AWT:
Java's AWT (Abstract Window Toolkit) is one of the earliest GUI frameworks in Java. While AWT
provides basic functionality for creating graphical user interfaces, it has several limitations:
29. How the events of the mouse and keyboard can be handled? Explain with an example(V.Imp)
In Java, events of the mouse and keyboard can be handled using event listeners and
event handlers provided by GUI libraries like AWT and Swing. Here's an overview of how
to handle mouse and keyboard events in Java:
Mouse Events Handling:
Mouse events in Java typically include events like mouse clicks, mouse movements, and
mouse drags You can handle these events by following these steps
Create a GUI Component
Register Mouse Listeners
Implement Mouse Listeners
Handle Events
import java.awt.*;
import java.awt.event.*;
class MouseListenerImpl implements MouseListener
{
public void mousePressed(MouseEvent me)
{
System.out.println("Mouse Pressed["+me.getX()+","+me.getY()+"]");
}
public void mouseReleased(MouseEvent me)
{
System.out.println("Mouse Released["+me.getX()+","+me.getY()+"]");
}
public void mouseClicked(MouseEvent me)
{
System.out.println("Mouse Clicked["+me.getX()+","+me.getY()+"]");
}
public void mouseEntered(MouseEvent me)
{
System.out.println("Mouse Entered["+me.getX()+","+me.getY()+"]");
}
public void mouseExited(MouseEvent me)
{
System.out.println("Mouse Exited["+me.getX()+","+me.getY()+"]");
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Mouse Events Example");
this.setBackground(Color.yellow);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
this.addMouseListener(new MouseListenerImpl());
}
}
class MouseEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}
Keyboard Events Handling:
Keyboard events in Java involve handling events like key presses and key releases. Here's how you can
handle keyboard events:
import java.awt.*;
import java.awt.event.*;
class KeyListenerImpl implements KeyListener
{
public void keyPressed(KeyEvent ke)
{
System.out.println("KeyPressed["+ke.getKeyChar()+"]");
}
public void keyTyped(KeyEvent ke)
{
System.out.println("KeyTyped["+ke.getKeyChar()+"]");
}
public void keyReleased(KeyEvent ke)
{
System.out.println("KeyReleased["+ke.getKeyChar()+"]");
}
}
class MyFrame extends Frame
{
MyFrame()
{
this.setVisible(true);
this.setSize(500,500);
this.setTitle("Key Events Example");
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
this.addKeyListener(new KeyListenerImpl());
}
}
class KeyEventsEx
{
public static void main(String[] args)
{
MyFrame mf=new MyFrame();
}
}
30. What is a layout manager? Explain various layout managers in JAVA. (V.Imp)
In Java GUI programming, a layout manager is a mechanism that controls the positioning
and sizing of components (such as buttons, labels, text fields, etc.) within a container
(such as a JFrame or JPanel). Layout managers are essential for creating visually
appealing and platform-independent user interfaces. They help ensure that components
are arranged and resized appropriately, regardless of the screen size or platform.
Java provides several layout managers as part of the Abstract Window Toolkit (AWT) and
Swing libraries, each with its own way of arranging components. Here are some common
layout managers in Java:
FlowLayout:
a. FlowLayout arranges components in a left-to-right flow, filling each row before
moving to the next row.
b. It's useful for creating simple, horizontally oriented layouts.
c. Components are centered within their respective cells.
BorderLayout:
a. BorderLayout divides the container into five regions: NORTH, SOUTH, EAST,
WEST, and CENTER.
b. Components added to these regions are positioned accordingly.
c. It's suitable for creating a simple main content area with optional headers and
footers.
GridLayout:
a. GridLayout arranges components in a grid of rows and columns, with each cell
having the same size.
b. It's useful for creating uniform, grid-like layouts.
GridBagLayout:
a. GridBagLayout is a powerful and flexible layout manager that allows you to
create complex layouts with varying cell sizes.
b. It uses GridBagConstraints to specify how components are placed and sized
within the grid.
c. It's suitable for creating intricate, custom layouts.
CardLayout:
a. CardLayout manages multiple components stacked on top of each other, like a
deck of cards.
b. Only one component is visible at a time, and you can switch between them
dynamically.
c. It's useful for creating wizards, tabbed interfaces, or multi-step forms.
The choice of layout manager depends on the specific requirements of your GUI design.
Different layout managers are suitable for different use cases, and you can even combine
them within a single container to achieve complex layouts. Understanding the strengths
and limitations of each layout manager is important for effective GUI design in Java.
Here's an overview of the Swing component hierarchy, which represents the inheritance
structure of Swing components:
java.awt.Component:
At the root of the Swing component hierarchy is the Component class from the java.awt
package. It serves as the base class for all GUI components in both AWT and Swing.
Common methods include those for handling events, painting, and managing
component visibility.
javax.swing.JComponent:
JComponent is a subclass of Component and serves as the base class for most Swing
components.
It adds more advanced functionality, such as support for Swing's look-and-feel (L&F)
customization, double buffering, and keyboard input.
Commonly used Swing components, such as JButton, JTextField, JLabel, and JPanel, are
direct or indirect subclasses of JComponent.
Containers:
Swing containers are components that can contain and manage other components. They
are used to structure the GUI layout.
Common Swing containers include:
javax.swing.JPanel: A generic container for grouping and organizing components.
javax.swing.JFrame: A top-level window that can contain other components.
javax.swing.JDialog: A dialog box that can display messages or receive user input.
javax.swing.JApplet: A container for creating applets.
javax.swing.JWindow: A top-level window without decorations.
Custom Components:
Developers can create custom Swing components by extending JComponent or one of its
subclasses. This allows for the creation of highly specialized and reusable GUI elements.
Layout Managers:
Layout managers (such as FlowLayout, BorderLayout, GridLayout, etc.) are used to
control the arrangement and sizing of components within Swing containers.
They help in achieving flexible and platform-independent GUI layouts.
Look and Feel (L&F):
Swing components support different look-and-feel (L&F) styles, allowing you to
customize the appearance of your application. Swing provides default L&Fs like Metal,
Nimbus, and Windows, and you can create custom L&Fs if needed.
Event Handling:
Swing components are event-driven. Event listeners and handlers are used to respond to
user interactions and system events.
Event handling in Swing is based on the Java event delegation model, where
components delegate event handling to registered listeners.
In summary, Swing is a versatile GUI library in Java, offering a wide range of components
and capabilities for creating desktop applications. It provides a well-defined component
hierarchy, and Swing components are lightweight and customizable, making them
suitable for various GUI design needs.
Example of Swing
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;