0% found this document useful (0 votes)
4 views57 pages

All_in_one_Java

The document provides an overview of Java's primitive data types, buzzwords, arrays, JVM, inheritance, constructors, and polymorphism. It explains the characteristics and significance of each topic, including examples of code for better understanding. Key concepts such as method overloading, method overriding, and different types of inheritance are also discussed.

Uploaded by

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

All_in_one_Java

The document provides an overview of Java's primitive data types, buzzwords, arrays, JVM, inheritance, constructors, and polymorphism. It explains the characteristics and significance of each topic, including examples of code for better understanding. Key concepts such as method overloading, method overriding, and different types of inheritance are also discussed.

Uploaded by

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

Unit-1

1. List the primitive data types available in Java and explain


data types specify the type of data that can be stored inside variables in Java.
Java is a statically-typed language. This means that all variables must be declared before they can
be used. int speed;
Here, speed is a variable, and the data type of the variable is int.

Data type Meaning Memory size Range Default Value

byte Whole numbers 1 byte -128 to +127 0

short Whole numbers 2 bytes -32768 to +32767 0

int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

long Whole numbers 8 bytes 9,223,372,036,854,775,808 to 0L


+9,223,372,036,854,775,807

float Fractional 4 bytes - 0.0f


numbers

double Fractional 8 bytes - 0.0d


numbers

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)

Example:

public class NonPrimitiveDataTypes {


String str;
public static void main(String[] args) {
String name = "BTech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str);
//using addition method
System.out.println(wish.concat(name));
}
}

2. List and explain the Java buzzwords in detail.


Java is the most popular object-oriented programming language. Java has many advanced
features; a list of key features is known as Java Buzz Words. The java team has listed the
following terms as java buzz words.
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming
concepts are similar to C++. In a java programming language, many complicated features like
pointers, operator overloading, structures, unions, etc. have been removed. One of the most
useful features is the garbage collector it makes java more simple.

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.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time, forever". The java provides
JVM (Java Virtual Machine) to to archive architectural-neutral or platform-independent. The JVM
allows the java program created using one operating system can be executed on any other
operating system.

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];

Let's look at the following example program.

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:

final public class FinalClassExample {


// Class members and methods go here
}

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 in java

 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);
}
}

7. What is polymorphism? Explain various forms of polymorphism(compile time(method


overloading) and run time(method overriding))
Polymorphism means defining one entity with multiple behavior's
In java we have following 2 types of poly morphisms.
1. Compile time polymorphism
 Method overloading allows a class to have multiple methods with the same name
but different parameter lists.
 The appropriate method to be called is determined at compile-time based on the
number and types of arguments passed.
 Note: By using the concept of method overloading we can achieve this compile time
poly morphism.
 It is also called as static polymorphism or early binding
Method overloading
Method overloading(Ad hoc Polymorphism) means declaring multiple methods with
same method name but having different method signature.
In method overloading while writing the method signature we have to follow
following 3 Rules
 Method name must be same for all methods
 List of parameters must be different like different type of parameters, different
number of parameters, different order of parameters.
 Return type is not considered in method overloading; it means we never decide
method overloading with return type.
public class MethodOverloadingExample {

// Method with no parameters


public void printMessage() {
System.out.println("Hello, World!");
}
// Method with one parameter of type int
public void printMessage(int num) {
System.out.println("The number is: " + num);
}

// Method with two parameters of type double


public void printMessage(double num1, double num2) {
System.out.println("Sum of two numbers is: " + (num1 + num2));
}

public static void main(String[] args) {


MethodOverloadingExample example = new MethodOverloadingExample();

// Call the overloaded methods


example.printMessage(); // Calls the first method with no parameters
example.printMessage(42); // Calls the second method with an int parameter

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.");
}
}

class Circle extends Shape


{
@Override
void display() {
//super.display();
System.out.println("This is a circle.");
}
}
public class MethodOverridingExample {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.display(); // Calls Circle's overridden method
}
}
class Animal
{
String name = "Animal";
void eat()
{
System.out.println(name + " is eating.");
}
}

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

class Dog extends Animal


{
String name = "Dog";
@Override
void eat()
{
super.eat(); // Calls the eat() method of the superclass
System.out.println(name + " is eating bones.");
}

void displayNames()
{
System.out.println("Superclass name: " + super.name); // Accesses the superclass's name
System.out.println("Subclass name: " + name);
}
}

public class SuperKeywordExample


{
public static void main(String[] args)
{
Dog dog = new Dog();
dog.eat();
dog.displayNames();
}
}
Final keyword
 final is a keyword or modifier which can be used at variables, methods & classes.
 If we declare a variable as final then we can’t modify value of the variable. The variable
acts like a constant. Final field must be initialized when it is declared.
 If we declare a method as final then we can't override that method
 If we declare a class as final then we can't extend from that class. We cannot inherit final
class in Java.

public final class FinalDemo


{
final int a=10; //valid
//b=10; invalid
// final int c; invalid
final void m1()
{
System.out.println("a:"+a);
}

public static void main(String[] args)


{
FinalDemo d=new FinalDemo();
d.m1();
}
}

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

public class ThisKeyword


{
private String name;
private int age;
public ThisKeyword(String name, int age) // Constructor with parameters
{
name = name; // not 'this' to refer to the instance variable
age = age;
}
public void displayInfo() // Method to display information about the person
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[] args)


{
ThisKeyword p1 = new ThisKeyword("Alice", 25);
p1.displayInfo();
}
}

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;
}

public void getInfo()


{
System.out.println("Name: " + ename);
System.out.println("Age: " + eage);
}
}

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

abstract class animal


{
// objects cannot be created
}
class Dog extends animal
{

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

abstract class animal //abstract class


{
public abstract void sound(); //abstract method
}

class Dog extends animal


{
@override
public void sound()
{
System.out.println("Dog is Barking");
}
}

class Lion extends animal


{
@override
public void sound()
{
System.out.println("Lion is roaring");
}
}

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;

Compiling java Package file

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

13. What is CLASSPATH? Discuss about CLASSPATH environment variables(V.imp)


The CLASSPATH is an environment variable in Java that specifies a set of directories or JAR files
where the Java Virtual Machine (JVM) should look for classes and resources when running Java
programs. It essentially defines the locations where the JVM should search for class files when
trying to load a class that is not part of the Java Standard Library or the current working
directory. The CLASSPATH is used to resolve dependencies for Java applications.
Here are some key points about the CLASSPATH environment variable:

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.

a. FileInputStream (Reading from a File)

Here's an example of using FileInputStream to read data from a file:

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {


public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int byteData;

// 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
}

fis.close(); // Close the FileInputStream when done


} catch (IOException e) {
e.printStackTrace();
}
}
}

b. FileOutputStream (Writing to a File)

Now, let's see how to use FileOutputStream to write data to a file:

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {


public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
String data = "Hello, World!";

// Convert the string to bytes and write it to the file


byte[] byteData = data.getBytes();
fos.write(byteData);

fos.close(); // Close the FileOutputStream when done


System.out.println("Data has been written to output.txt.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

15. Explain about Random access file operations with an example(V.imp)


Random access file operations in Java allow you to read and write data at any position within a
file, rather than sequentially from the beginning to the end. This means you can jump to a
specific location within the file and perform read and write operations at that position. Java
provides the RandomAccessFile class to work with random access files.

Here's an explanation of random access file operations with an example:


import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessEx
{
public static void main(String[] args) throws IOException
{
RandomAccessFile raf = new RandomAccessFile("Random.txt","r");
raf.seek(4);
byte[] bytes = new byte[12];
raf.read(bytes);
raf.close();
//String dta=new String(bytes);
//System.out.println(data);
System.out.println(new String(bytes));
}
}
16. Wrire about a) Wrapper classes
a. All the primitive data types in java have defined using the class concept, these classes known
as wrapper classes.
b. In java, every primitive type has its corresponding wrapper class defined in the java.lang
package.
The following table shows the primitive type and its corresponding wrapper class.

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;

public class FileCopyExample {


public static void main(String[] args) {
// Define the source and destination file names
String sourceFileName = "source.txt";
String destinationFileName = "destination.txt";

try {
// Create a FileInputStream for the source file
FileInputStream fis = new FileInputStream(sourceFileName);

// Create a FileOutputStream for the destination file


FileOutputStream fos = new FileOutputStream(destinationFileName);

// Define a buffer to hold the data being copied


byte[] buffer = new byte[1024];
int bytesRead;

// Read data from the source file and write it to the destination file
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}

// Close the FileInputStream and FileOutputStream


fis.close();
fos.close();

System.out.println("File copied successfully.");


} catch (IOException e) {
e.printStackTrace();
}
}
}

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.

Reasons for Exception Occurrence


Several reasons lead to the occurrence of an exception. A few of them are as follows.
• When we try to open a file that does not exist may lead to an exception.
• When the user enters invalid input data, it may lead to an exception.

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.

Example - Unchecked Exceptions


public class UncheckedException {
public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
System.out.println(list[6]); //ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
How exceptions handled in Java?
In java, the exception handling mechanism uses five keywords namely try, catch, finally, throw,
and throws.

The advantages of Exception Handling in Java are as follows:


 Provision to Complete Program Execution.
 Easy Identification of Program Code and Error-Handling Code.
 Propagation of Errors.
 Meaningful Error Reporting.
 Identifying Error Types.
19. Write a program to illustrate the use of multiple catch blocks for a try block which processes the
arithmetic exception, generated by division-by-zero error and other exceptions like
NumberFormatException, ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException

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());
}
}

public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
21. What is meant by re-throwing exception? Demonstrate with a suitable scenario for this.
Re-throwing an exception
Re-throwing an exception in Java refers to the practice of catching an exception in a catch block
and then throwing the same exception (or a different one) to be handled by a higher-level
exception handler or to propagate it up the call stack. Re-throwing is typically done when you
want to add additional information or context to the exception or when you want to handle the
exception at a higher level of your application.
ReThrowExceptionExample
public class ReThrowExceptionExample {
public static void main(String[] args) {
try {
divide(10, 0);
} catch (Exception e) {
System.out.println("Exception caught at the main level: " + e.getMessage());
}
}

static void divide(int a, int b) throws Exception {


try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException ae) {
// Wrap the ArithmeticException and re-throw it as a more general exception
throw new Exception("An error occurred during division.", ae);
}
}
}
22. What is Multitasking? Summarize the differences between thread-based multitasking and
process-based multitasking.
Multitasking: Executing multiple tasks at the same time.
Types of Multitasking
 Process based Multitasking
 Thread based Multitasking

Process-based multitasking Thread-based multitasking

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 is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

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.

Inter process communication is expensive. Inter thread communication is not expensive.

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.

Let's look at each phase in detailed.


New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.
Example
Thread t1 = new Thread();

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().

producer - consumer problem using inter – thread communication


class ItemQueue
{
int item;
boolean valueSet=false;
public synchronized int getItem()
{
while(!valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println("Consumed:"+item);
valueSet=false;
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e);
}
notify();
return item;

}
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 Consumer implements Runnable


{
ItemQueue iq;
public Consumer(ItemQueue iq)
{
this.iq=iq;
Thread c=new Thread(this,"Consumer");
c.start();
}
public void run()
{
while (true)
{
iq.getItem();
}
}
}

class ProducerConsumer1
{
public static void main(String[] args)
{
ProducerConsumer1 pc=new ProducerConsumer1();
new Producer(pc);
new Consumer(pc);
}
}

Unit-4 Collection Frameworks


Java Collection Framework
• Java Collection Framework is a framework which provides some predefined classes and
interfaces to store and manipulate the group of objects.
• Using Java collection framework, you can store the objects as a List or as a Set or as a Queue
or as a Map and perform basic operations like adding, removing, updating, sorting, searching
etc.. with ease.
What is Framework
• A framework is a pre-designed and pre-implemented set of classes, functions, interfaces, and
tools that provide a structured way to build and develop applications.
• Frameworks offer a foundation for developers to build upon, saving time and effort by
providing reusable code, standardized practices, and common functionalities.
• Examples: Spring Framework, Struts, Hibernate • Benefits of using frameworks in
programming
• Abstraction, Reusability, Standardization, Efficiency, Modularity, Scalability, Security etc.
Why Java Collection Framework
• Earlier, arrays are used to store the group of objects. But, arrays are of fixed size. You can’t
change the size of an array once it is defined. It causes lots of difficulties while handling the
group of objects.
• To overcome this drawback of arrays, Java Collection Framework is introduced from JDK 1.2.
Java Collections Hierarchy

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

Write a program to convert an ArrayList into an array.


import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListToArrayExample {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
// Convert ArrayList to an array of integers
int [] arr = arrayList.toArray(int[]);
// Print the original ArrayList
System.out.println("ArrayList: " + arrayList);
// Print the converted array
System.out.println("Array: " + Arrays.toString(arr));
}
}
Cursors of Collection Framework
• cursors are mainly used to access the elements of any collection • we have following 3 types of
cursors in Collection Framework
1.Iterator 2.ListIterator 3.Enumeration
Iterator
• this cursor is used to access the elements in forward direction only
• this cursor can be applied Any Collection (List, Set)
• while accessing the methods we can also delete the elements • Iterator is interface and we
cannot create an object directly.
• if we want to create an object for Iterator, we have to use iterator () method
Creation of Iterator:
Iterator it = c.iterator();
• here iterator() method internally creates and returns an object of a class which implements
Iterator interface.
• Methods
1. boolean hasNext() 2. Object next() 3. void remove()
The other two can be implemented in the similar way
Difference between iterator and Listiterator

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;

public class TreeSetExample {


public static void main(String[] args) {
// Create a TreeSet
Set<String> set = new TreeSet<>();
// Add elements to the TreeSet
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Banana"); // Duplicate, will not be added
// Print the elements of the TreeSet (sorted order)
for (String element : set) {
System.out.println(element);
}
}
}

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;

public class SmileyApplet extends Applet {


public void paint(Graphics g) {
// Draw a yellow circle for the face
g.setColor(Color.yellow);
g.fillOval(50, 50, 200, 200);
// Draw the left eye
g.setColor(Color.black);
g.fillOval(100, 100, 40, 40);
// Draw the right eye
g.fillOval(180, 100, 40, 40);
// Draw the mouth (a smile)
g.drawArc(100, 140, 120, 80, 0, -180);
}
}
To run this applet, you can compile it and then embed it in an HTML file as follows:
<html>
<head>
<title>Smiley Applet</title>
</head>
<body>
<applet code="SmileyApplet.class" width="300" height="300"></applet>
</body>
</html>

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:

 Event Source: An event source is an object or component that generates events.


Examples include buttons, text fields, and windows.
 Event Listener/Handler: An event listener or handler is an object or method that is
responsible for responding to events. Event listeners are registered with event sources to
receive notifications when specific events occur.
 Event Object: An event object represents information about the event, such as the type
of event and the source of the event. It is typically passed to the event handler.
 Event Dispatching: The event source dispatches events to registered event listeners.
When an event occurs, the associated event listener's method is called to handle the
event.

Delegation Event Model (Event Handling):

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:

 Platform Dependency: AWT components rely on native platform implementations, which


can lead to inconsistencies in appearance and behavior across different operating
systems.
 Limited Widget Set: AWT provides a limited set of GUI components, making it
challenging to create complex and modern user interfaces. It lacks advanced
components like tables and tree views.
 Inefficient Drawing: AWT uses a heavyweight component model, where each component
corresponds to a native OS component. This can result in slower performance and
increased memory consumption compared to lightweight component models like Swing.
 No Support for Look and Feel: AWT lacks support for pluggable look and feel, making it
difficult to customize the appearance of GUI components.
 Limited Event Handling: AWT's event handling model is less flexible compared to Swing.
It does not provide comprehensive event delegation, making it more challenging to
handle and manage events in complex applications.
Due to these limitations, Swing, a more advanced GUI framework built on top of AWT, was
introduced to address these issues and provide a more powerful and customizable GUI toolkit
for Java applications.
Difference between AWT and Swings.
28. Demonstrates the different types of Event classes and Event Listeners supported by java.

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:

 Create a GUI Component


 Register Key Listeners
 Implement Key Listener
 Handle 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.

31. What is a Swing? Explain the Component Hierarchy of Swings. (V.Imp)


(a) Design a user interface to collect data from customer for opening an account in a bank. Use
all possible swing components and layout manager for your interface design
(b) Design a user interface to collect data from the student for admission application using
swing components.
Swing is a Java library for creating graphical user interfaces (GUIs) for desktop
applications. It is part of the Java Foundation Classes (JFC) and provides a set of
components and classes that allow developers to create platform-independent and
highly customizable GUIs. Swing offers a rich set of widgets (components) for building
windows, dialog boxes, buttons, text fields, menus, and more.

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.

Lightweight and Heavyweight Components:


Swing uses lightweight components, which are drawn by Java code and do not rely on
native operating system resources. These components are efficient and platform-
independent.
In contrast, AWT components are heavyweight components, which are platform-specific
and rely on native resources. Swing components are designed to be lightweight
replacements for AWT components.

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;

public class SimpleSwingApplication {


public static void main(String[] args) {
// Create a JFrame (window)
JFrame frame = new JFrame("Simple Swing Application");

// Create a JButton (a clickable button)


JButton button = new JButton("Click Me");

// Add an ActionListener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// This code runs when the button is clicked
JOptionPane.showMessageDialog(frame, "Hello, Swing!");
}
});
// Create a JPanel (a container for components)
JPanel panel = new JPanel();
panel.add(button); // Add the button to the panel
// Add the panel to the frame
frame.add(panel);

// Set frame properties


frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true); // Display the frame
}
}
32. Explain about MVC (Model View Controller) architecture. (V.Imp)
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as different
objects.
The MVC pattern architecture consists of three layers:
Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data
that the model contains.
Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the user
requests are processed as follows:

MVC Architecture in Java


A client (browser) sends a request to the controller on the server side, for a page.
The controller then calls the model. It gathers the requested data.
Then the controller transfers the data retrieved to the view layer.
Now the result is sent back to the browser (client) by the view.

The advantages of MVC architecture are as follows:


 MVC has the feature of scalability that in turn helps the growth of application.
 The components are easy to maintain because there is less dependency.
 A model can be reused by multiple views that provides reusability of code.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy