0% found this document useful (0 votes)
2 views9 pages

Opp Java

The document provides an overview of Object-Oriented Programming (OOP) concepts, including encapsulation, abstraction, inheritance, and polymorphism, along with a comparison to Procedure-Oriented Programming (POP). It also explains command-line arguments in Java, control statements, operators, and access control mechanisms. Additionally, it covers constructors, method overloading, and method overriding, illustrating these concepts with code examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Opp Java

The document provides an overview of Object-Oriented Programming (OOP) concepts, including encapsulation, abstraction, inheritance, and polymorphism, along with a comparison to Procedure-Oriented Programming (POP). It also explains command-line arguments in Java, control statements, operators, and access control mechanisms. Additionally, it covers constructors, method overloading, and method overriding, illustrating these concepts with code examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object-Oriented Programming (OOP) is a method of programming in which What is command-line arguments?

Write a program to accept two numbers


programs are structured using objects that represent real-world entities, allowing and display their sum using command-line arguments.
for modular, reusable, and organized code. In Java, command-line arguments are values passed to a program at the time of
Features or characteristics of Object-Oriented Programming execution from the command prompt or terminal. These values are stored in the
1. Encapsulation: Encapsulation means binding data and methods together into a args array of the main() method.
single unit (class) and restricting direct access to some of the object's They allow users to input data without using Scanner or input methods inside
components. Example: A bank account class hiding its balance from direct the program.
modification. public class SumCommandLine {
2. Abstraction public static void main(String[] args) {
Abstraction means showing only essential details and hiding complex internal
implementation. Example: Using a “car” without knowing how the engine works // Convert command-line arguments (String) to integers
internally. int num1 = [Link](args[0]);
3. Inheritance: Inheritance allows one class (child) to inherit properties and int num2 = [Link](args[1]);
behaviors of another class (parent). Example: A “Dog” class inheriting from an
“Animal” class. // Calculate sum
4. Polymorphism: Polymorphism means one interface, multiple implementations. int sum = num1 + num2;
Example: A function “draw()” behaving differently for Circle, Rectangle, etc.
6. Dynamic Binding: Dynamic binding means that the method to be executed is // Display result
determined at runtime rather than compile time. [Link]("Sum = " + sum);
Procedure-Oriented Programming Object-Oriented Programming }
(POP) (OOP) }
Procedure-Oriented Programming Object-Oriented Programming Explain the operators available in Java programming.
(POP) focuses on functions and step- (OOP) focuses on objects and In Java, operators are symbols used to perform operations on variables and
by-step procedures to solve problems classes that combine data and values. They are classified into several types:
in a simple way. behavior together. 1. Arithmetic Operators
In POP, data and functions are In OOP, data and methods are Used for basic mathematical operations.
separate and follow a top-down encapsulated and follow a bottom- • + (addition)
approach, making programs easier but up approach, making programs
• - (subtraction)
less flexible. more organized.
POP has less security and limited code OOP provides better security and • * (multiplication)
reuse because data can be accessed high code reuse through • / (division)
globally. encapsulation and inheritance. • % (modulus – remainder)
POP is suitable for small and simple OOP is suitable for large and Example: a + b
programs. complex programs. 2. Relational (Comparison) Operators
Example: C language (POP) vs Java, Example: C language (POP) vs Java, Used to compare two values and return true or false.
Python, C++ (OOP). Python, C++ (OOP). • == (equal to)
Explain different types of control statements used in java.
1. Selection (Decision-Making) Statements
• != (not equal to)
These statements allow the program to choose different paths based on • > (greater than)
conditions. • < (less than)
• if statement → executes a block if condition is true • >= (greater than or equal to)
• if-else statement → chooses between two blocks • <= (less than or equal to)
• else-if ladder → checks multiple conditions Example: a > b
3. Logical Operators
• switch statement → selects one case from many options
Used to combine multiple conditions.
Example: Checking whether a number is positive or negative.
2. Iteration (Looping) Statements: These statements are used to repeat a block of • && (AND)
code multiple times. • || (OR)
• for loop → used when number of iterations is known • ! (NOT)
• while loop → repeats while condition is true Example: (a > b && b > c)
• do-while loop → executes at least once, then checks condition 4. Assignment Operators
Example: Printing numbers from 1 to 10. Used to assign values to variables.
3. Jump (Branching) Statements: These statements are used to transfer control • = (simple assignment)
from one part of the program to another. • +=, -=, *=, /=, %= (compound assignments)
• break → exits loop or switch Example: a += 5
• continue → skips current iteration and continues loop 5. Increment & Decrement Operators
Used to increase or decrease a value by 1.
• return → exits from a method and returns a value
Example: Breaking a loop when a specific value is found. • ++ (increment)
Applications of Object-Oriented Programming (OOP) Language: • -- (decrement)
1. Software Development – Widely used to build large and complex Example: a++
applications like enterprise systems and management software.
2. Web Development – Used in backend frameworks and web 6. Bitwise Operators
applications for better structure and scalability. Operate on bits of data.
3. Game Development – Helps in designing characters, objects, and • &, |, ^, ~, <<, >>
interactions efficiently. Example: a & b
4. Mobile App Development – Used in Android and iOS apps for organized
7. Ternary Operator
and reusable code.
A shorthand for if-else condition.
5. Real-Time Systems – Applied in systems like banking, traffic control,
and simulations where reliability is important. • condition ? value1 : value2
Example: (a > b) ? a : b
Fundamentals of Classes in Java Encapsulation in Java
A class is a blueprint used to create objects. It defines data (variables) and Encapsulation is the process of binding data (variables) and methods (functions)
methods (functions) that work on that data. into a single unit (class) and restricting direct access to data using access
1. Simple Class modifiers.
A simple class contains variables and methods. Features
class Student { • Data and methods are combined in one class
int id;
• Provides data security using private variables
String name;
} • Access is controlled using getter and setter methods
Here, Student is a class with two data members. • Improves code maintainability and flexibility
2. Creating Class Instances (Objects) • Helps in hiding internal data from outside access
An object is created using the new keyword. Example (Code)
Student s1 = new Student(); class Student {
s1 is an instance (object) of class Student. private int id;
3. Adding Methods to a Class private String name;
Methods define behavior inside a class.
class Student { // setter method
int id; public void setData(int i, String n) {
String name; id = i;
name = n;
void display() { }
[Link](id + " " + name);
} // getter method
} public void display() {
4. Calling Methods [Link](id + " " + name);
Methods are called using the object. }
public class Main { }
public static void main(String[] args) {
public class Main {
Student s1 = new Student(); public static void main(String[] args) {
[Link] = 101; Student s = new Student();
[Link] = "Ram"; [Link](101, "Ram");
[Link]();
[Link](); // method call }
} }
} Output: 101 Ram
Output : 101 Ram
Abstraction in Java Using this keyword in Java
Abstraction is the process of hiding implementation details and showing only The this keyword is a reference variable that refers to the current object of a
essential features to the user. class. It is mainly used to distinguish between instance variables and local
Features variables when they have the same name.
• Hides internal implementation Features
• Shows only important information • Refers to current object
• Reduces complexity • Resolves naming conflict between variables
• Improves security and clarity • Used to call current class methods
• Achieved using abstract class and interface • Used to call constructors in the same class
Example (Code) • Improves code clarity
abstract class Animal { Example (Code)
abstract void sound(); class Student {
} int id;
String name;
class Dog extends Animal {
void sound() { void setData(int id, String name) {
[Link]("Bark"); [Link] = id;
} [Link] = name;
} }

public class Main { void display() {


public static void main(String[] args) { [Link](id + " " + name);
Animal a = new Dog(); }
[Link](); }
}
} public class Main {
Output: Bark public static void main(String[] args) {
Student s = new Student();
[Link](101, "Ram");
[Link]();
}
}
Output: 101 Ram
Constructors in Java 2. Passing by Reference (Concept)
A constructor is a special method used to initialize objects. It has the same name In true “pass by reference”, the original value can be changed. Java does not
as the class and does not have a return type. support true pass by reference, but objects behave similarly because their
1. Default Constructor references are passed by value.
A default constructor is a constructor that does not take any parameters. It is Example (Object behavior)
automatically called when an object is created. class Student {
Example int id = 10;
class Student { }
int id;
String name; public class Main {
public static void update(Student s) {
// default constructor [Link] = 50;
Student() { }
id = 0;
name = "Unknown"; public static void main(String[] args) {
} Student st = new Student();
update(st);
void display() { [Link]([Link]);
[Link](id + " " + name); }
} }
} Output: 50
Object data can be changed through reference.
public class Main { Access Control in Java
public static void main(String[] args) { Access control is the mechanism used to restrict or allow access to classes,
Student s = new Student(); variables, and methods in a program using access modifiers. It helps in data
[Link](); security and encapsulation.
} Types of Access Control (Modifiers)
} 1. private
Output: 0 Unknown • Accessible only within the same class
2. Parameterized Constructor
A parameterized constructor is a constructor that takes arguments (parameters)
• Highest level of security
class Test {
to initialize objects with different values.
private int a = 10;
Example
}
class Student {
2. default (no keyword)
int id;
String name; • Accessible only within the same package
class Test {
// parameterized constructor int a = 20; // default
Student(int i, String n) { }
id = i; 3. protected
name = n; • Accessible within the same package and in child classes
} class Test {
protected int a = 30;
void display() { }
[Link](id + " " + name); 4. public
} • Accessible from anywhere in the program
} class Test {
public int a = 40;
public class Main { }
public static void main(String[] args) {
Student s = new Student(101, "Ram"); Polymorphism means “many forms”. It allows a single method or action to
[Link](); behave differently depending on the situation or input.
} Types of Polymorphism
} 1. Compile-time Polymorphism (Method Overloading)
Output: 101 Ram It occurs when multiple methods have the same name but different parameters in
Passing by Value, Passing by Reference & Access Control in Java the same class.
1. Passing by Value Example
In Java, arguments are always passed by value, meaning a copy of the value is class Demo {
sent to the method. Changes inside the method do not affect the original variable.
Example void show(int a) {
class Test { [Link]("Integer: " + a);
void change(int x) { }
x = 100;
} void show(String b) {
[Link]("String: " + b);
public static void main(String[] args) { }
int a = 50;
Test t = new Test(); public static void main(String[] args) {
[Link](a); Demo d = new Demo();
[Link](a); [Link](10);
} [Link]("Hello");
} }
Output: 50 }
Original value remains unchanged. 2. Run-time Polymorphism (Method Overriding)
It occurs when a child class provides a specific implementation of a method
already defined in the parent class.
Example
class Animal {
void sound() {
[Link]("Animal makes sound"); public static void main(String[] args) {
} Dog d = new Dog();
} [Link](); // from superclass
[Link](); // from subclass
class Dog extends Animal { }
void sound() { }
[Link]("Dog barks"); Output
} Eating...
} Barking...
The super keyword is used to refer to the immediate parent class object. It is
public class Main { mainly used to access parent class variables, methods, and constructors when
public static void main(String[] args) { they are overridden or hidden in the child class. It helps remove confusion
Animal a = new Dog(); between parent and child class members with the same name. It can also be
[Link](); used to call the parent class constructor using super().
} Example of super
} class Animal {
Output: Dog barks void sound() {
Inheritance is a feature of OOP in which a new class (child class) acquires the [Link]("Animal makes sound");
properties and behaviors of an existing class (parent class). It helps in code }
reusability. }
Features
• Promotes code reusability class Dog extends Animal {
void sound() {
• Represents IS-A relationship (e.g., Dog IS-A Animal)
[Link](); // calling parent class method
• Supports method overriding [Link]("Dog barks");
• Makes program easier to maintain }
• Helps in hierarchical classification }
Types of Inheritance in Java
1. Single inheritance public class Main {
2. Multilevel inheritance public static void main(String[] args) {
3. Hierarchical inheritance Dog d = new Dog();
(Multiple inheritance is not directly supported in Java using classes) [Link]();
Example (Code) }
class Animal { }
void eat() { Output
[Link]("Eating..."); Animal makes sound
} Dog barks
} Method overriding is a feature in Java where a child class provides a specific
implementation of a method that is already defined in the parent class. The
class Dog extends Animal { method name, return type, and parameters must be the same in both classes. It is
void bark() { used to achieve runtime polymorphism.
[Link]("Barking..."); Example of Overriding
} class Animal {
} void sound() {
[Link]("Animal sound");
public class Main { }
public static void main(String[] args) { }
Dog d = new Dog();
[Link](); // inherited method class Dog extends Animal {
[Link](); void sound() {
} [Link]("Dog barks");
} }
Output }
Eating...
Barking... public class Main {
Superclass and Subclass in Java public static void main(String[] args) {
A superclass (parent class) is the class whose properties and methods are Animal a = new Dog();
inherited by another class. A subclass (child class) is the class that inherits those [Link]();
properties and can also have its own additional features. }
Features }
Output
• Superclass is also called parent/base class
Dog barks
• Subclass is also called child/derived class
• Subclass can access non-private members of superclass
• Supports code reusability
• Helps in achieving inheritance
Example (Code)
class Animal { // Superclass
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal { // Subclass


void bark() {
[Link]("Barking...");
}
}
public class Main {
Exception Handling in Java }
Basic Exceptions }
Exceptions are unexpected errors that occur during program execution and
disrupt normal flow. Common basic exceptions include: public static void main(String[] args) {
• ArithmeticException → division by zero check(15);
}
• NullPointerException → accessing null object
}
• ArrayIndexOutOfBoundsException → invalid array index Rethrowing Exception
Proper use of Exceptions Rethrowing means catching an exception and throwing it again to be handled at a
Exceptions should be used to handle runtime errors gracefully instead of higher level.
stopping the program. Proper use means: Example
• Avoid crashing the program class Main {
• Show meaningful error messages public static void test() {
try {
• Maintain normal program flow
int a = 10 / 0;
• Use exception handling only for exceptional cases, not regular logic }
User Defined Exceptions catch (ArithmeticException e) {
Java allows creating custom exceptions by extending the Exception class. These [Link]("Caught in method");
are used when built-in exceptions are not enough. throw e; // rethrowing
class AgeException extends Exception { }
AgeException(String msg) { }
super(msg);
} public static void main(String[] args) {
} test();
}
public class Main { }
public static void main(String[] args) throws AgeException { finally Clause (Cleanup Block)
int age = 15; The finally block is used to execute important code whether an exception occurs
or not. It is mainly used for cleanup tasks like closing files or releasing resources.
if (age < 18) { Example
throw new AgeException("Age is less than 18"); public class Main {
} else { public static void main(String[] args) {
[Link]("Eligible"); try {
} int a = 10 / 0;
} }
} catch (ArithmeticException e) {
Catching Exceptions (try, catch) [Link]("Exception handled");
The try block contains risky code, and the catch block handles the error if it }
occurs. finally {
public class Main { [Link]("Finally block always executes");
public static void main(String[] args) { }
try { }
int a = 10 / 0; }
} Output
catch (ArithmeticException e) { Exception handled
[Link]("Cannot divide by zero"); Finally block always executes
} A String is a sequence of characters used to store text. In Java, Strings are objects
of the String class and are immutable (cannot be changed after creation).
[Link]("Program continues..."); Common String Methods
} 1. length(): Returns the number of characters in a string.
} public class Main {
Output public static void main(String[] args) {
Cannot divide by zero String s = "Hello";
Program continues... [Link]([Link]());
Throwing and Rethrowing Exceptions in Java }
throw keyword }
The throw keyword is used to explicitly create and throw an exception in a 2. toUpperCase() / toLowerCase(): Converts string to uppercase or lowercase.
program. It is used when we want to generate an exception based on a condition. String s = "Java";
Example [Link]([Link]());
public class Main { [Link]([Link]());
public static void main(String[] args) { 3. charAt(): Returns character at a specific index.
int age = 15; String s = "Hello";
[Link]([Link](1));
if (age < 18) { 4. substring(): Extracts part of a string.
throw new ArithmeticException("Not eligible to vote"); String s = "Programming";
} [Link]([Link](0, 4));
5. equals(): Compares two strings for equality.
[Link]("Eligible"); String a = "Java";
} String b = "Java";
} [Link]([Link](b));
throws keyword 6. contains(): Checks whether a string contains a specific sequence.
The throws keyword is used in a method declaration to declare exceptions that a String s = "Hello World";
method might throw. It passes responsibility of handling the exception to the [Link]([Link]("World"));
caller.
Example
class Test {
static void check(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not eligible");
A thread is a lightweight sub-process that allows a program to perform multiple
tasks simultaneously. Java supports multithreading to improve performance and [Link](s);
efficiency. [Link]();
Ways to Create a Thread
1. By Extending Thread Class [Link]("Object Serialized");
We create a class that extends the Thread class and override the run() method. }
class MyThread extends Thread { }
public void run() { Deserialization
[Link]("Thread is running..."); Deserialization is the process of converting a byte stream back into an object.
} Example
import [Link].*;
public static void main(String[] args) {
MyThread t1 = new MyThread(); // instantiate thread public class Main {
[Link](); // start thread public static void main(String[] args) throws Exception {
}
} FileInputStream fis = new FileInputStream("[Link]");
2. By Implementing Runnable Interface ObjectInputStream ois = new ObjectInputStream(fis);
We implement Runnable interface and pass it to a Thread object.
class MyRunnable implements Runnable { Student s = (Student) [Link]();
public void run() { [Link]();
[Link]("Runnable thread is running...");
} [Link]([Link] + " " + [Link]);
}
public static void main(String[] args) { }
MyRunnable r = new MyRunnable(); Arrays
Thread t1 = new Thread(r); // instantiate thread An array is a fixed-size data structure used to store multiple values of the same
[Link](); // start thread type in a continuous memory location.
} Example:
} int[] a = {10, 20, 30, 40};
Thread Multithreading [Link](a[0]);
A thread is a single lightweight Multithreading is the process of executing Collection Framework
sub-process used to execute multiple threads simultaneously within a The Java Collection Framework is a group of interfaces and classes used to store
a task. single program. and manage dynamic groups of objects. It includes List, Set, and Map.
It focuses on performing one It allows multiple tasks to run at the same List Interface
task at a time. time. List is an interface that stores ordered elements (sequence maintained) and
A thread is created using Multithreading is achieved by creating and allows duplicate values.
Thread class or Runnable managing multiple threads. Common Implementations:
interface. • ArrayList
It does not fully utilize CPU It improves CPU utilization and program • LinkedList
resources. efficiency. Example:
Example: A single thread Example: One thread printing numbers while import [Link].*;
printing numbers. another prints letters at the same time.
public class Main {
String StringBuffer public static void main(String[] args) {
String is an immutable class, StringBuffer is a mutable class, List<String> list = new ArrayList<>();
meaning its value cannot be meaning its value can be modified after
changed after creation. creation. [Link]("Ram");
Every modification creates a new Modifications are done in the same [Link]("Sita");
object in memory. object, so it is memory efficient. [Link]("Ram");
Slower in performance when Faster in performance for repeated
frequent changes are made. modifications. [Link](list);
Used when data is fixed and does Used when data changes frequently }
not change often. (like string manipulation). }
Example: String s = "Java"; s = s + " Example: StringBuffer sb = new Set Interface
Program"; StringBuffer("Java"); [Link](" Set is an interface that stores unique elements only (no duplicates allowed).
Program"); Common Implementations:
Serialization is the process of converting an object into a byte stream so that it • HashSet
can be saved in a file or transferred over a network. To make a class serializable, it • LinkedHashSet
must implement the Serializable interface.
• TreeSet
Serialization means saving object state into a file or sending it over a network.
Example:
Example
import [Link].*;
import [Link].*;
public class Main {
class Student implements Serializable {
public static void main(String[] args) {
int id;
Set<Integer> set = new HashSet<>();
String name;
[Link](10);
Student(int id, String name) {
[Link](20);
[Link] = id;
[Link](10);
[Link] = name;
}
[Link](set);
}
}
public class Main {
}
public static void main(String[] args) throws Exception {
Map Interface
Student s = new Student(101, "Ram");
Map stores data in key-value pairs where each key is unique.
Common Implementations:
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos); • HashMap
• TreeMap
[Link](400, 300);
• LinkedHashMap
[Link](null);
Example:
[Link](true);
import [Link].*;
}
}
public class Main {
MVC Pattern (Model–View–Controller): MVC is a software design pattern used to
public static void main(String[] args) {
separate an application into three main parts:
Map<Integer, String> map = new HashMap<>();
Model, View, and Controller
It helps make code clean, organized, and easy to maintain.
[Link](1, "Ram");
1. Model
[Link](2, "Sita");
Handles data and business logic
[Link](3, "Hari");
• Stores data
[Link](map); • Performs calculations or rules
} • Does NOT care about UI
} Example:
AWT (Abstract Window Toolkit) Swing
• User data (name, age)
AWT is an older GUI toolkit in Java. Swing is a modern GUI toolkit built on
top of AWT. • Database operations
It uses native platform components It uses lightweight components (pure class StudentModel {
(OS-dependent). Java). private String name;
Less flexible and limited More flexible and provides rich
public void setName(String name) {
components. components.
[Link] = name;
GUI looks different on different GUI looks same on all platforms
}
operating systems. (platform-independent).
Performance is slower due to native Generally faster and more efficient.
public String getName() {
dependency.
return name;
Package: [Link] Package: [Link]
}
Swing Components (Java): Java Swing is used to create graphical user interfaces }
(GUI) for desktop applications. 2. View
1. JLabel Handles user interface (UI)
Used to display text or images on the screen.
It cannot take input from the user. • Displays data to user
JLabel label = new JLabel("Hello World"); • Takes input visually
2. JTextField • No logic
Used to take single-line input from the user. ✔ Example:
Example: name, email, username.
JTextField textField = new JTextField(20);
• Swing UI (JFrame, JButton, JTextField)
3. JButton • Web pages
Used to create a clickable button. 3. Controller
It performs an action when clicked. Acts as a bridge between Model and View
JButton button = new JButton("Click Me"); • Takes user input from View
Event Handling in Swing • Updates Model
Event handling means responding to user actions like clicking a button, typing
text, or selecting an option.
• Updates View
Example:
Example: Button Click Event
import [Link].*; • Button click handling
import [Link].*; • Form submission logic

public class MyApp { class StudentController {


public static void main(String[] args) { private StudentModel model;
private StudentView view;
JFrame frame = new JFrame("Swing Example");
public StudentController(StudentModel model, StudentView view) {
JLabel label = new JLabel("Enter name:"); [Link] = model;
[Link](50, 50, 100, 30); [Link] = view;
}
JTextField textField = new JTextField();
[Link](150, 50, 150, 30); public void setStudentName(String name) {
[Link](name);
JButton button = new JButton("Submit"); [Link]([Link]());
[Link](150, 100, 100, 30); }
}
JLabel result = new JLabel(); How MVC Works
[Link](150, 150, 200, 30); 1. User interacts with View
2. View sends request to Controller
// Event Handling 3. Controller updates Model
[Link](new ActionListener() { 4. Model sends data back to View
public void actionPerformed(ActionEvent e) { 5. View updates UI
String name = [Link]();
[Link]("Hello " + name);
}
});

[Link](label);
[Link](textField);
[Link](button);
[Link](result);
Define Stream. Write a program in java to copy the content from one file to int Integer
another. char Character
A stream in Java is a sequence of data used to perform input and output (I/O) float Float
operations. double Double
It is used to: boolean Boolean
• Read data from a source (file, keyboard, network) byte Byte
• Write data to a destination (file, console, network) short Short
import [Link]; long Long
import [Link]; Important Methods of Wrapper Classes
import [Link]; 1. valueOf()
Converts primitive or String into wrapper object.
public class FileCopy { Integer a = [Link](10);
public static void main(String[] args) { [Link](a);
2. parseInt() / parseDouble()
try { Converts String into primitive type.
FileInputStream input = new FileInputStream("[Link]"); int num = [Link]("100");
FileOutputStream output = new FileOutputStream("[Link]"); [Link](num);
3. intValue(), doubleValue()
int data; Converts wrapper object into primitive type.
Integer a = 50;
while ((data = [Link]()) != -1) { int x = [Link]();
[Link](data); [Link](x);
} 4. toString()
Converts wrapper object into String.
[Link](); Integer a = 100;
[Link](); String s = [Link]();
[Link](s);
[Link]("File copied successfully!"); List and explain any five swing controls with their uses.
Swing provides many GUI components to build user interfaces. These controls are
} catch (IOException e) { lightweight and flexible.
[Link]("Error: " + [Link]()); 1. JButton
} Description
} A JButton is used to create a clickable button in a GUI.
} Use
Define AWT. Explain different types of Layout Managers in java. • Used to perform actions when clicked (submit, save, cancel)
AWT (Abstract Window Toolkit) is a Java API used to create Graphical User Example
Interface (GUI) applications. It provides classes for components like buttons, JButton btn = new JButton("Click Me");
labels, text fields, and also supports event handling and layout management for 2. JLabel
building window-based programs. Description
Layout Managers in Java JLabel is used to display text or images on the screen.
Layout Managers are used to arrange GUI components inside a container Use
automatically. They control the size and position of components without using
manual positioning. • Showing messages, headings, or labels for fields
Example
1. FlowLayout
JLabel label = new JLabel("Enter Name:");
• Arranges components from left to right in a row 3. JTextField
• If space is full, it moves to the next line Description
• Default layout for Panel JTextField is used to take single-line user input.
2. BorderLayout Use
• Divides container into five regions: North, South, East, West, Center • Input fields like name, email, age
Example
• Each region can hold one component
JTextField tf = new JTextField(20);
3. GridLayout
4. JCheckBox
• Arranges components in rows and columns (grid form) Description
• All components have equal size JCheckBox allows users to select multiple options.
4. CardLayout Use
• Works like a deck of cards (one screen at a time) • Selecting hobbies, preferences, options
• Only one component is visible at a time Example
JCheckBox cb = new JCheckBox("Java");
• Used for forms and multi-page interfaces
5. JRadioButton
5. GridBagLayout
Description
• Most flexible layout manager JRadioButton is used to select only one option from a group.
• Allows components of different sizes and positions Use
• Complex but powerful • Gender selection, choosing one option among many
Define Collection Class. Explain different Wrapper classes and associated Example
methods in java. JRadioButton rb = new JRadioButton("Male");
Collection Class and Wrapper Classes in Java
Definition of Collection Class
A Collection class is part of the Java Collection Framework that provides ready-
made classes and interfaces to store, manage, and manipulate groups of objects
efficiently. It allows dynamic storage where size can grow or shrink at runtime.
Examples include: ArrayList, LinkedList, HashSet, HashMap.
Wrapper Classes
Wrapper classes are used to convert primitive data types into objects. Java
provides a wrapper class for each primitive type so they can be used in collections
and object-based operations.
List of Wrapper Classes and Their Primitive Types
Primitive Type Wrapper Class
Define JDBC. Write a program to display all records from a table of database.
JDBC (Java Database Connectivity) is an API in Java used to connect and interact
with a database. It allows Java programs to execute SQL queries, retrieve data,
and update records in a database.
JDBC Program to Display All Records from a Table
Example (Assume MySQL Database)
import [Link].*;
public class DisplayRecords {
public static void main(String[] args) {
try {
// Step 1: Load Driver
[Link]("[Link]");

// Step 2: Establish Connection


Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
// Step 3: Create Statement
Statement stmt = [Link]();
// Step 4: Execute Query
ResultSet rs = [Link]("SELECT * FROM student");

// Step 5: Display Records


while ([Link]()) {
[Link](
[Link](1) + " " +
[Link](2) + " " +
[Link](3)
);
}
// Step 6: Close Connection
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Abstract Class Interface
An abstract class is a class that An interface contains only abstract
can have abstract and non- methods (before Java 8) and default/static
abstract methods. methods (modern Java).
It is declared using the abstract It is declared using the interface keyword.
keyword.
It can have constructors and It cannot have constructors and mainly
instance variables. contains constants.
Supports single inheritance Supports multiple inheritance (a class can
(one class can extend one implement multiple interfaces).
abstract class).
Used when classes are closely Used to define a contract/blueprint for
related. unrelated classes.

You might also like