JAVA PROGRAMMING
JAVA PROGRAMMING
2 mark questions
Command line arguments are parameters passed to a program when it is executed from a command-line
interface (CLI). They allow users to provide input to the program in the form of strings and customize its
behaviour at runtime. It is used in various applications and tools to customize behaviour, such as setting file
paths, options, and flags.
Branching statements are fundamental for controlling the flow of a program, allowing you to execute different
sections of code based on various conditions.
3. Define a class.
In object-oriented programming (OOP), a class is a blueprint for creating objects. It defines a set of attributes
and methods that the objects created from the class will have.
In Java, we can access class members (attributes and methods) using objects created from that class. To Access
Class Members Using Objects, we have to define the class, instantiate the class and then use the dot (.)
operator to access attributes and call methods on the object.
In Java, the protected keyword is an access modifier used to control the visibility of class members (attributes,
methods, and constructors). The protected keyword helps in achieving encapsulation and inheritance, allowing
controlled access to class members while keeping certain details hidden from other parts of the program.
6. What is Array?
An array is a data structure that stores a collection of elements, typically of the same type, in a contiguous
block of memory. Each element in the array can be accessed by its index, which represents its position in the
array. Arrays are widely used in programming for their efficiency in storing and accessing data.
In Java, a thread has several states during its lifecycle. One of these states is the newborn state, which occurs
when a thread is first created but has not yet started executing. A thread enters the newborn state when it is
instantiated using the Thread class or implementing the Runnable interface.
Exception handling is a crucial aspect of programming that allows developers to manage and respond to
runtime errors in a controlled and predictable manner. Exception handling is essential for creating robust,
reliable, and user-friendly software applications and error recovery.
Components Basic set (Button, Label, etc.) Rich set (JButton, JLabel, JTable, etc.)
Performance Faster due to native code Can be slower but more flexible
A part of the Java Foundation Classes (JFC) that A component in Swing used as a container
Definition
provides a set of lightweight GUI components. to hold and organize other components.
Component Refers to the entire set of GUI components A specific class within the Swing
Type provided by the javax.swing package. framework.
Example JButton, JLabel, JTextField, JComboBox, JTable, Itself is a component that can contain other
Components JTree, etc. components.
More sophisticated and comprehensive event- Inherits event handling capabilities from
Event Handling
handling mechanisms. JComponent.
Feature Swing JPanel
Manages the rendering of lightweight Uses the painting mechanism to render its
Rendering
components in Java. children components.
A web page is typically composed of several distinct sections, each serving a unique purpose in delivering
content and functionality to users. These include header, hero section, main content, sidebar, footer, banner,
navigation menu, Call to Action (CTA), Forms and Media. These sections helps in designing and organizing web
pages effectively, ensuring a seamless and engaging user experience.
In Java Database Connectivity (JDBC), a ResultSet is an object that holds the data retrieved from a database
after executing a SQL query. It acts as a table of data representing the result of the query, which can be
navigated and read through various methods provided by the ResultSet interface.
OOP focuses on objects and data, promotes code reuse and encapsulation, and is suitable for complex and
large applications. POP, on the other hand, emphasizes functions and procedures, is more linear and
simpler, and is generally suitable for smaller and less complex programs.
Procedure-Oriented
Feature Object-Oriented Programming (OOP)
Programming (POP)
Based on functions or
Concept Based on objects and classes
procedures
Encapsulation: Data is hidden and accessed through Data is global and accessible
Data Handling
methods from any function
Examples of
Java, C++, Python, C# C, Pascal, Fortran
Languages
The continue statement in Java is used to skip the current iteration of a loop and proceed to the next iteration.
It is particularly useful for controlling the flow of loops when certain conditions are met, without terminating
the entire loop.
A class is a blueprint for creating objects. It defines a set of properties (attributes) and methods (behaviors)
that the objects created from the class will have.
An object is an instance of a class. It represents a real-world entity with a specific state and behavior, as
defined by the class.
Contains attributes (fields) that define the Has specific values assigned to the attributes
Attributes
properties of the objects. defined in the class.
Contains methods that define the Can call methods defined in the class to perform
Methods
behaviors of the objects. actions.
Memory Does not occupy memory for its attributes Occupies memory for its attributes once it is
Allocation until objects are created. instantiated.
Constructors are special methods in object-oriented programming (OOP) used to initialize objects of a class.
They are called when an object is created and can set initial values for the object's attributes, perform setup
procedures, or allocate resources. Constructors ensure objects are properly initialized when they are created,
perform set up operations necessary for the object to function correctly and allows for different ways of
creating and initializing objects through constructor overloading.
A two-dimensional array is a data structure in programming that can store data in a tabular form consisting of
rows and columns. It’s like an array of arrays, where each element in the primary array
represent game boards (e.g., chess, tic-tac-toe) and to represent pixel data in digital images.
In Java, a nested try statement refers to a try block that is enclosed within another try block. This structure
allows us to handle different levels of exceptions separately, providing more precise control over error
handling.
Swing components are called lightweight components because they are written entirely in Java and do not rely
on the native operating system's resources for their rendering. Swing's lightweight nature provides significant
advantages in terms of flexibility, customizability, and performance, making it a preferred choice for building
complex and modern Java-based GUIs.
In Java, the WindowEvent class is part of the java.awt.event package and represents events that occur to a
window, such as opening, closing, activating, deactivating, and so on. This class is used to handle window-
specific events in graphical user interface (GUI) applications.
In Java applets, the init()initializes the applet. This method is called once, when the applet is first loaded. Used
to set up any resources needed by the applet, such as initializing variables, loading images, or setting up the
user interface.
destroy() cleans up resources before the applet is destroyed. This method is called once, when the applet is
being unloaded and ensures that resources are properly released when the applet is no longer needed.
Purpose Initializes the applet Cleans up resources before the applet is destroyed
Functionality Sets up resources needed by the applet Releases resources allocated in init() or start()
Invocation Called when the applet is first loaded Called when the applet is being unloaded
Timing Invoked before the start() method Invoked after the stop() method
In Java applets, parameters can be passed using the <param> tag within the HTML code. These parameters are
then accessed within the applet code using the getParameter() method. It helps us to customize the
behaviour and display of your applets based on input values provided in the HTML.
Examples 10, 3.14, 0x1A (hexadecimal) 'A' (character), "Hello" (string), true (boolean)
Usage Used for mathematical calculations Used for textual data, logical conditions, etc.
Stored as numeric data types (int, float, Stored as character, string, or boolean data
Storage
double, etc.) types
Usage Used to set or update the value of a variable Used to check if two values are equal
Operation Changes the state of a variable Returns a boolean value (true or false)
Side Effects Alters the value stored in the variable No side effects, only checks for equality
Common Can accidentally use = when intending to Mistakenly using == when assignment is
Mistake use == intended
In Java, the this keyword is a reference to the current object—the object whose method or constructor is being
called. It is used for Referencing Instance Variables, Calling Other Constructors, Returning the Current Object,
Passing the Current Object as a Parameter, and Accessing Overridden Methods. Understanding and using the
this keyword effectively is crucial for writing clear, concise, and bug-free Java code.
Constructor overloading in Java allows a class to have multiple constructors, each with a different parameter
list. This enables the creation of objects in different ways, providing flexibility and reusability. By defining
multiple constructors, we can initialize objects with different sets of data, making our code more versatile.
In object-oriented programming, a derived class (also known as a subclass or child class) is a class that is based
on another class, called the base class (or parent class). The derived class inherits attributes and methods from
the base class, and can also have additional attributes and methods or override existing ones. Derived classes
allow for a hierarchical organization of classes, promoting code reuse and making it easier to manage and
extend complex systems.
6. Define a Package.
In Java, a package is a namespace that organizes a set of related classes and interfaces. Packages are used to
group related classes together, control access, and avoid naming conflicts. They serve as a way to manage and
structure your codebase effectively, making it easier to maintain and navigate.
The Delegation Event Model is a mechanism used in Java for handling events in Graphical User Interface (GUI)
programming. The main advantage of Delegation Event Model is that the application logic is separated from
the interface logic, making the code more modular and easier to maintain. Event listeners can be added or
removed independently of the components they listen to, providing greater flexibility. This model allows for
easy extension to handle different types of events
A JCheckBox is a Swing component in Java that provides a graphical way for users to make a binary choice—
such as selecting or deselecting an option. It is part of the javax.swing package and is widely used in graphical
user interfaces (GUIs) to offer multiple options to the user, where each option can be selected independently.
A Layout Manager in Java is an object that implements the LayoutManager interface and is used to arrange
components within a container. It defines how components are placed, sized, and aligned within a container,
such as a JFrame or JPanel. Layout Managers allow you to build complex GUIs without needing to handle
absolute positioning of components. Different Layout Managers in Java are FlowLayout, BorderLayout,
GridLayout, CardLayout, GridBagLayout and BoxLayout.
When
Called once when the applet is loaded. Called each time the applet becomes active.
Called
Typical Uses Initializing resources, setting up the UI. Starting animations, threads, or resuming operations.
Called only once in the applet's Can be called multiple times during the applet's
Frequency
lifecycle. lifecycle.
Java Database Connectivity (JDBC) is an API that allows Java applications to interact with various databases.
The JDBC API provides a set of interfaces and classes that facilitate connection to a database, execution of SQL
statements, and retrieval and update of data. The key components of the JDBC API are DriverManager, Driver,
Connection, Statement. PreparedStatement, CallableStatement, ResultSet and SQLException.
An exception in Java is an event that occurs during the execution of a program that disrupts the normal
flow of instructions. It is a mechanism for handling runtime errors, which allows a program to manage
unexpected conditions and maintain a smooth flow. Types of exceptions are Checked Exceptions, Handling
Exceptions, Finally Block, Throw Keyword and Throws Clause.
2. Explain JVM
The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run Java
programs and programs written in other languages that are also compiled to Java bytecode. Its key
functions are Execution of Bytecode, Platform Independence, Memory Management, Security and
Class Loading.
case value2 :
// Statements
break; //
....
....
....
default :
// default Statement
}
11. What are event listeners? Use of event listeners in Java. V Imp
In Java, event listeners are interfaces that define methods to handle specific types of events. They
are used to handle events generated by user interactions with graphical user interface (GUI)
components, such as clicking a button, entering text in a field, or selecting an item from a menu.
Event listeners are part of the delegation event model and play a crucial role in building interactive
and responsive applications. Event listeners in Java are essential for creating interactive and
responsive GUIs.
const MyInterface = {
method1: function () { },
method2: function (param1, param2) { },
};
try {
tryCode - Code block to run
}
catch(err) {
catchCode - Code block to handle errors
}
finally {
finallyCode - Code block to be executed regardless of the try result
}
import java.util.Scanner;
The break statement in Java is used to terminate the execution of a loop or switch statement
prematurely. It immediately transfers control to the statement following the loop or switch. It is
used for exiting a Loop, terminating a switch Statement and exiting Nested Loops.
An applet is a small application designed to be executed within a web browser or applet viewer. It is a Java
program that extends the java.applet.Applet class and is embedded in an HTML page. Applets are primarily
used to provide interactive features to web applications that cannot be provided by HTML alone.
Typical Usage Short text inputs (e.g., names, emails) Long text inputs (e.g., comments, notes)
Both TextField and TextArea provide methods for setting and getting text, as well as controlling whether the
text is editable.
Method overriding in Java is a feature that allows a subclass to provide a specific implementation of a method
that is already defined in its superclass. When a method in a subclass has the same name, return type, and
parameters as a method in its superclass, the subclass method overrides the superclass method. This enables
polymorphism, allowing for dynamic method dispatch at runtime.
To set an image as the background of a web page, we can use CSS (Cascading Style Sheets). CSS allows us to
apply styling to HTML elements, and one of the properties we can use is background-image
body {
Return Type No return type Must have a return type (or void)
The Color class in Java is part of the java.awt package and is used to encapsulate colors in the default sRGB
color space or colors in arbitrary color spaces identified by ColorSpace objects. The two constructors of the
Color class are
In Java, access specifiers (or access modifiers) are keywords that set the accessibility levels for classes,
methods, and variables. They help to control the visibility and scope of a class's members, ensuring that they
are only accessible where appropriate. The four main access specifiers in Java are public, private, protected and
default (package-private).
private Yes No No No
In Java, selection statements are used to make decisions and execute different blocks of code based on certain
conditions. The two commonly used selection statements are if-else Statement and switch Statement.
29. What is a checkbox? How would you put a checkbox on an applet? V Imp
A checkbox is a GUI (graphical user interface) component that allows users to make a binary choice, such as
selecting or deselecting an option. Each checkbox operates independently, which means we can select or
deselect multiple checkboxes at the same time.
In Java, checkboxes are represented by the Checkbox class, part of the java.awt package. To add a checkbox to
an applet, we can use the Checkbox class and add it to the applet’s layout
In Java, the this keyword (often referred to as a "pointer" in other programming languages) is a reference
variable that refers to the current object. It is used to distinguish Instance Variables from Parameters, Invoke
Current Class Constructor, Return the Current Object and Pass the Current Object as an Argument. The this
keyword is a fundamental part of Java that enhances clarity and functionality, making it easier to work with
object-oriented code.
In Java, an array is a container object that holds a fixed number of values of a single type. To define an array,
we need to
1) declare an array by specifying the type of elements it will hold and use square brackets to indicate
that it is an array
2) Create an Array by using the new keyword followed by the type and the number of elements the
array will hold.
3) Initialize the array either at the time of declaration or separately after declaration
32. Describe throw and throws clause and give their uses. V Imp
The throw keyword is used to explicitly throw an exception from a method or a block of code. We use the
throw keyword to manually throw an exception, typically when a certain condition is met within our code.
The throws clause is used in a method signature to declare that a method might throw one or more exceptions,
informing the calling code to handle them.
In Java, the super keyword is used within a subclass to refer to members (fields, methods, and constructors) of
its superclass. Key uses of super keyword are Access Superclass Constructors, Access Superclass Methods, and
Access Superclass Fields. The super keyword is crucial for managing inheritance hierarchies, allowing
subclasses to leverage and extend the functionality of their superclasses effectively.
Eg:
try {
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
35. Explain string class functions that can be used for character extraction.
The String class in Java provides several methods for extracting characters from a string. These methods are
useful for various operations, such as parsing, analyzing, and manipulating strings. The key methods for
character extraction are charAt(int index), getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin),
toCharArray() and substring(int beginIndex, int endIndex).
In Java, a byte stream is used for input and output of 8-bit binary data. The byte stream classes provide a way
to read and write raw bytes, making them suitable for handling binary data such as images, audio files, and
other media. They are part of the java.io package.
37. Syntax of switch statement
The switch statement in Java is used to execute one block of code among many based on the value of an
expression. It's an alternative to using multiple if-else statements and can make your code more readable and
efficient when handling multiple possible values of a variable.
Syntax:
switch (expression) {
case value1:
break;
case value2:
break;
default:
In Java, a static variable (also known as a class variable) is a variable that belongs to the class itself rather than
to any specific instance of the class. This means that all instances of the class share the same static variable,
and any changes made to the variable are reflected across all instances. Static variables are a powerful feature
in Java that enable us to maintain shared data among instances of a class, making your programs more efficient
and easier to manage.
A parameterized constructor in Java is a constructor that takes one or more parameters. These parameters are
used to initialize the object with specific values at the time of creation. Unlike the default constructor, which
does not take any arguments, a parameterized constructor allows for more flexible and meaningful
initialization of object instances. It enables precise and customized initialization of objects, thus enhancing
flexibility and functionality in object-oriented programming.
In Java, the throw statement is used to explicitly throw an exception from a method or any block of code. This
allows us to create and handle exceptions based on specific conditions within your program. The throw
statement helps us to signal an error condition or an unexpected situation that should be managed using Java's
exception handling framework.
The Thread class provides methods to manage and control threads. Some common methods are:
1. start() - This method causes the thread to begin execution; the Java Virtual Machine calls the run
method of this thread.
2. run() - If this thread was constructed using a separate Runnable object, then that Runnable object's
run method is called.
3. join() - This method waits for the thread to die. There are overloaded versions with timeouts as
parameters.
4. yield() - This method causes the currently executing thread object to temporarily pause and allow
other threads to execute.
A Label control is a graphical user interface element commonly used in programming for displaying text to the
user. It's a non-editable control, meaning users cannot modify the text within it. The primary use of a label is to
provide information, such as descriptions, instructions, or data values.
A Java applet is a small application written in Java, designed to be embedded within a web page and executed
by a web browser. The basic structure is shown in the below figure
In Java, data types specify the different sizes and values that can be stored in a variable. Java is a statically-
typed language, meaning all variables must be declared before they can be used. Here are the main categories:
These are the most basic data types built into Java. There are 8 primitive data types:
float 4 bytes Stores fractional numbers, sufficient for storing 6 to 7 decimal digits 10.5f
double 8 bytes Stores fractional numbers, sufficient for storing 15 decimal digits 10.5d
These are also known as reference types, as they reference objects. Some examples include:
• Arrays: Used to store multiple values of the same type. Example: int[] arr = {1, 2, 3, 4};
• Enumerations (enum): Represents a group of constants. Example: enum Color { RED, GREEN, BLUE };
Constructors in Java are special methods used to initialize objects. The key features of constructors:
1. Same Name as the Class - A constructor's name must exactly match the name of the class in which it is
defined.
2. No Return Type- Constructors do not have a return type, not even void. If a method has a return type, it is
not a constructor.
3. Automatic Invocation - Constructors are automatically called when an instance of the class is created. This
allows objects to be set up with initial values.
4. Types of Constructors
• Default Constructor: A constructor with no parameters. If no constructor is defined in a class, the Java
compiler automatically provides a default constructor.
• Parameterized Constructor: A constructor that takes one or more arguments. It allows the object to be
initialized with specific values.
5. Overloading Constructors - Constructors can be overloaded by defining multiple constructors with different
parameter lists. This allows for different ways to initialize objects of the class.
6. Constructor Chaining - Constructor chaining occurs when a constructor calls another constructor in the
same class (using this()) or in the parent class (using super()). This helps to reuse code and streamline object
initialization.
Features of constructors – V Imp
Constructors in Java are special methods used to initialize objects. They have several important features and
characteristics that make them crucial for object-oriented programming. Here are the key features of
constructors:
1. Same Name as the Class - A constructor's name must exactly match the name of the class in which it is
defined. This is what distinguishes it from other methods.
2. No Return Type - Constructors do not have a return type, not even void. If a method has a return type, it is
not a constructor.
3. Automatic Invocation - Constructors are automatically called when an instance of the class is created. This
allows objects to be set up with initial values.
4. Types of Constructors
• Default Constructor: A constructor with no parameters. If no constructor is defined in a class, the Java
compiler automatically provides a default constructor.
• Parameterized Constructor: A constructor that takes one or more arguments. It allows the object to be
initialized with specific values.
5. Overloading Constructors - Constructors can be overloaded by defining multiple constructors with different
parameter lists. This allows for different ways to initialize objects of the class.
6. Constructor Chaining - Constructor chaining occurs when a constructor calls another constructor in the
same class (using this()) or in the parent class (using super()). This helps to reuse code and streamline object
initialization.
7. Initialization Block - Constructors can use initialization blocks to share common initialization code across
multiple constructors.
8. Cannot be Inherited - Constructors are not inherited by subclasses, but a subclass can call a superclass
constructor using super().
Packages in Java are used to group related classes, interfaces, and sub-packages, providing a hierarchical
structure that helps organize the code and avoid naming conflicts. They also provide access protection and
control over how classes are accessed.
In Java, event handling is a key part of creating interactive applications. Events are actions or occurrences
recognized by software, often originated by the user, such as clicks, key presses, or mouse movements. Event
classes are part of the java.awt.event package and are used to represent different types of events. Common
event classes are ActionEvent, MouseEvent, KeyEvent, FocusEvent, WindowEvent etc
The List interface in Java is part of the Java Collections Framework and represents an ordered collection (also
known as a sequence). The List interface is implemented by various classes, the most commonly used being
ArrayList, LinkedList, and Vector.
Method overloading in Java allows a class to have more than one method with the same name, provided their
parameter lists (number, types, or both) are different. This is a key feature of polymorphism in Java, allowing
methods to perform different tasks based on the inputs they receive. Method overloading improves code
readability and reusability by using the same method name for similar actions. It makes the code more flexible
and easier to maintain.
Operators in Java are special symbols that perform specific operations on one, two, or three operands, and
then return a result. The various categories of operators in Java are
Arithmetic Operators - Addition (+), Subtraction (-), Multiplication (*), Division (/), and Modulus (%)
Relational Operators - Equal to (==), Not equal to (!=), Greater than (>), Less than (<), Greater than or equal to
(>=), Less than or equal to (<=)
Logical Operators - Logical AND (&&) Logical OR (||), Logical NOT (!)
Bitwise Operators- AND (&) , OR (|), XOR (^) , Complement (~), Left shift (<<), Right shift, Unsigned right shift
(>>>)
Assignment Operators - Assignment (=), Addition assignment (+=), Subtraction assignment (-=), Multiplication
assignment (*=), Division assignment (/=), Modulus assignment (%=)
Other operators are : Unary Operators, Conditional (Ternary) Operator, and Instanceof Operator
Looping statements in Java are used to execute a block of code multiple times, either for a specific number of
iterations or until a certain condition is met. Java provides several types of loops: for Loop, while Loop, do-
while Loop, Enhanced for Loop (for-each Loop), Break and Continue Statements and Nested Loops.
The update function allows us to separate the logic that changes the state of objects from the logic that draws
the objects or handles user input. This modular design makes the code easier to understand and maintain. It is
used to manage and update the state of an object. For example, in a game, an update function can handle
changes in the positions of characters, health levels, scores, etc.
In Java, bytecode is the intermediate representation of your Java code, which is processed by the Java
compiler. When we compile a Java program, it is transformed from human-readable source code into bytecode,
which is stored in .class files. Bytecode is designed to be platform-independent. It can run on any platform that
has a Java Virtual Machine (JVM), making Java a "write once, run anywhere" language.
Running a Java applet involves a few steps, from writing the code to embedding it in a web page. First we have
to Write the Applet Code and then Compile the Applet Code. The next step is to Create an HTML File to Embed
the Applet. Once done, we can Run the Applet by opening the index.html file in a web browser that supports
Java applets, or by using an applet viewer tool.
In Java, a literal is a fixed value that appears directly in the code and represents a value of a primitive data
type, string, or a constant. Literals are used to assign values to variables or constants. The different types of
literals in Java are Integer Literals, Floating-point Literals, Character Literals, String Literals, Boolean Literals and
Null Literal.
Arrays are a fundamental part of Java programming, offering a straightforward way to store and manipulate
collections of data. Declaring an array in Java involves specifying the type of elements the array will hold,
followed by square brackets [], and then giving the array a name.
Declaration With Initial Values: We can declare, create, and initialize an array with values all at once.
int[] myArray = {1, 2, 3, 4, 5}; // Creates and initializes an array with five elements.
An event is a signal that an action has occurred, such as a user clicking a button, pressing a key, or receiving
data from a network. Events are crucial for creating interactive applications, especially in graphical user
interfaces (GUIs) and real-time systems. They allow the program to respond to user actions and other dynamic
occurrences efficiently and effectively.
The finalize method in Java is part of the Object class and is used to perform cleanup operations before an
object is garbage collected. It's a method that can be overridden in classes to release resources such as file
handles, network connections, or database connections before the object is reclaimed by the garbage collector.
We can set the priority of a thread to influence the order in which threads are scheduled for execution. Thread
priority is an integer value ranging from Thread.MIN_PRIORITY (which is 1) to Thread.MAX_PRIORITY (which is
10), with Thread.NORM_PRIORITY (which is 5) being the default priority for all threads.
The do...while loop in Java is used to execute a block of code at least once, and then repeatedly execute the
block as long as a specified condition is true. The key difference between do...while and while loops is that
do...while evaluates the condition after executing the block of code.
Syntax:
do {
// Statements to be executed
} while (condition);
Defining a user-defined class in Java involves creating a new class that serves as a blueprint for objects. It
involves Defining the Class, Defining the Fields (Attributes), and Defining the Methods.
Creating a Java applet to plot a point involves using the Applet class and the Graphics class to draw on the
applet's canvas.
import java.awt.Graphics;
import java.awt.Color;
@Override
g.setColor(Color.RED);
// Plot the point at (50, 50)
In Java, a frame refers to an instance of the JFrame class from the Swing package. A JFrame is a top-level
window with a title and a border that serves as the main window for a GUI application. It provides the basic
structure to which other GUI components (such as buttons, text fields, and labels) can be added.
In Java, defining a method involves specifying a set of instructions that can be called upon to perform a specific
task. Components needed to define a method is Return Type, Method Name, Parameters, and Method Body.
Syntax:
returnType methodName(parameters) {
// Method body
3. Class Declaration
4. Main Method
5. Statements
package com.example;
import java.util.Scanner;
// 3. Class Declaration
// 4. Main Method
// 5. Statements
System.out.println("Hello, World!");
scanner.close();
Data hiding in Java refers to the concept of restricting access to certain details and components of an object.
This is achieved by making the attributes (fields) of a class private and providing public methods to access and
modify them. The primary purpose of data hiding is to protect the integrity of the data and to ensure
controlled access.
A thread in Java (and in computer programming in general) is a small unit of process execution. Threads allow a
program to operate more efficiently by performing multiple tasks simultaneously. In Java, the Thread class and
the Runnable interface are used to create and manage threads.
A package in Java is a mechanism used to group related classes, interfaces, and sub-packages. It helps organize
your code and makes it more modular and maintainable. Packages also provide access control and help to
avoid name conflicts.
• java.lang: Contains fundamental classes such as String, Math, Integer, etc. Automatically imported.
• java.util: Contains utility classes such as collections framework, date and time facilities.
• java.awt and javax.swing: Provides classes for creating graphical user interfaces (GUI).
The Label class in the java.awt package is used to create a text label in a Java AWT GUI application. Labels are
typically used to display static text, although we can update the text dynamically. The Label class provides
several constructors to create labels with different initial settings such as Default Constructor, Constructor with
Text, Constructor with Text and Alignment.
// Abstract method
void sound();
// Default method
System.out.println("Sleeping...");
The for loop in Java is a control flow statement that allows code to be executed repeatedly based on a given
boolean condition. The for loop is particularly useful when you know in advance how many times you want to
execute a statement or a block of statements.
// Statements to be executed
73. Write a program in Java to check a string is palindrome or not using string buffer class
Below is a Java program that checks whether a given string is a palindrome using the StringBuffer class:
import java.util.Scanner;
if (input.equals(reversedString)) {
} else {
scanner.close();
The Checkbox class in the java.awt package represents a graphical component that can be in either an "on"
(checked) or "off" (unchecked) state. Checkboxes are typically used to let the user select one or more options
from a set.
The checkboxes are created using different constructors to demonstrate various initial states. They are added
to the frame using a flow layout. The itemStateChanged method handles item events, printing the state of the
checkbox when it is clicked.
@Override
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Creating threads and passing the Runnable instances to the Thread constructor
thread1.start();
thread2.start();
The List interface in Java is part of the java.util package and is a subtype of the Collection interface. It
represents an ordered collection (also known as a sequence). These constructors allow you to create lists in
various ways, depending on your needs for capacity, initial content, and specific behavior.
The life cycle of a thread in Java consists of several states, representing the different stages a thread goes
through from its creation to its termination.
• New − A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or when the
event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
"Choice control" in programming, particularly in Java's Abstract Window Toolkit (AWT), refers to the Choice
class, which provides a pop-up menu of choices. A Choice control allows users to select one item from a drop-
down list.
The BufferedWriter class in Java is part of the java.io package and is used for writing text to character output
streams, buffering the characters to provide efficient writing of single characters, arrays, and strings. By using a
buffer, it minimizes the interaction with the disk, improving performance when writing large amounts of data.
import java.applet.Applet;
import java.awt.Graphics;
@Override
An interface in Java is a reference type that is similar to a class. It is a collection of abstract methods and
constants. Interfaces are used to specify a set of methods that a class must implement, providing a way to
enforce certain behaviors across different classes.
Syntax:
// Abstract method
void method1();
// Default method (introduced in Java 8)
System.out.println("Default method");
System.out.println("Static method");
// Constant
83. Write a Java program to draw oval, rectangle, circle, arc etc
Below is a Java program that uses the Graphics class to draw an oval, rectangle, circle, and arc on a frame.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
@Override
super.paintComponent(g);
g.setColor(Color.BLUE);
// Draw a rectangle
// Draw an oval
// Draw an arc
frame.add(panel);
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);