0% found this document useful (0 votes)
2 views

JAVA PROGRAMMING

The document provides a comprehensive overview of Java programming concepts, including command line arguments, branching statements, classes, exception handling, and GUI components like Swing and AWT. It covers various programming principles such as object-oriented vs procedure-oriented programming, constructors, arrays, and event handling mechanisms. Additionally, it discusses applet lifecycle methods, JDBC components, and the use of keywords like 'this' and 'protected' in Java.

Uploaded by

Shiji Mathew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA PROGRAMMING

The document provides a comprehensive overview of Java programming concepts, including command line arguments, branching statements, classes, exception handling, and GUI components like Swing and AWT. It covers various programming principles such as object-oriented vs procedure-oriented programming, constructors, arrays, and event handling mechanisms. Additionally, it discusses applet lifecycle methods, JDBC components, and the use of keywords like 'this' and 'protected' in Java.

Uploaded by

Shiji Mathew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

JAVA PROGRAMMING

2 mark questions

1. Write a short note on command line argument.

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.

2. List out the different branching statements used in Java. V imp

The different types of branching statements used in Java are:

if Statement, if-else Statement, else-if Ladder, and switch Statement.

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.

4. How will you access class members using objects?

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.

5. What is the use of protected keyword in java? V. Imp

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.

7. Explain newborn state of a thread?

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.

8. What is exception handling? Why exception handling is done? V Imp

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.

9. What are differences between Swing and AWT?


Feature AWT (Abstract Window Toolkit) Swing (Java Swing)

Component Type Heavyweight Lightweight

Package java.awt javax.swing

Native Resources Uses native OS resources Written entirely in Java

Look and Feel OS-dependent Pluggable look and feel

Extensibility Limited Highly extensible

Components Basic set (Button, Label, etc.) Rich set (JButton, JLabel, JTable, etc.)

Event Handling Basic event handling More sophisticated event handling

Performance Faster due to native code Can be slower but more flexible

Customization Less customizable Easily customizable

Support for MVC No native MVC support Supports MVC architecture

10. Differentiate between swing and Jpanel. V Imp

Feature Swing JPanel

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.

Provides a wide range of components like


Used primarily for grouping and organizing
Usage JButton, JLabel, JTextField, JTable, and many
other Swing components.
more.

Extends java.awt.Component indirectly


Inheritance Directly extends javax.swing.JComponent.
through javax.swing.JComponent.

Highly customizable with support for look and


Can be customized by overriding its
Customization feel, pluggable UIs, and various advanced
methods or using layout managers.
components.

Acts as a container to organize and layout


Provides overall framework and components
Functionality components, can also perform custom
for building GUIs.
painting.

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.

11. Discuss various sections of web page.

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.

12. What is JDBC ResultSet?

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.

1. Differentiate between object oriented and procedure oriented programming.

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

Emphasizes on procedures and


Main Focus Emphasizes on objects and data
functions

Encapsulation: Data is hidden and accessed through Data is global and accessible
Data Handling
methods from any function

Lower modularity, structured


Modularity Higher modularity through classes and objects
around procedures

Promotes code reuse through inheritance and


Reuse Less emphasis on code reuse
polymorphism

Design Approach Bottom-up approach Top-down approach

Limited abstraction through


Abstraction Supports abstraction through classes and interfaces
procedures

Complexity Harder to manage complexity in


Easier to manage complexity due to modular design
Management large programs

Examples of
Java, C++, Python, C# C, Pascal, Fortran
Languages

Supports inheritance, allowing derived classes to


Inheritance No inheritance concept
share properties
Procedure-Oriented
Feature Object-Oriented Programming (OOP)
Programming (POP)

Supports polymorphism, enabling methods to do


Polymorphism No polymorphism concept
different things based on the object

Strong encapsulation through access specifiers like No direct support for


Encapsulation
private, protected, and public encapsulation

2. Explain the use of continue statement.

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.

3. Define classes and objects.

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.

Feature Classes Objects

A blueprint for creating objects, defining An instance of a class, representing a specific


Definition
their structure and behavior. entity with a state and behavior.

Created multiple times from a class using the


Creation Defined once in the program.
new keyword.

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.

Car myCar = new Car(); myCar.color = "Red";


Example class Car { String color; void drive() { ... } }
myCar.drive();

4. What are constructors? V Imp

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.

6. What is two dimensional array?

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.

7. What is nested try statement ?

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.

8. Why swing component are called lightweight components?

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.

9. Define Window Event Class.

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.

11. Distinguish between init() and distroy() methods in applet.

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.

Feature init() Method destroy() Method

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

Example init() { System.out.println("Initialized"); } destroy() { System.out.println("Destroyed"); }

12. How parameters can be passed to applet using tag?

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.

1. Differentiate between numeric literal and non numeric literal.

Feature Numeric Literal Non-Numeric Literal

Definition Represents numerical values Represents non-numerical values

Types Integer, floating-point (decimal) Character, string, boolean


Feature Numeric Literal Non-Numeric Literal

Examples 10, 3.14, 0x1A (hexadecimal) 'A' (character), "Hello" (string), true (boolean)

Usage Used for mathematical calculations Used for textual data, logical conditions, etc.

Can include integers, decimals, hexadecimal,


Representation Can include characters, strings, booleans
octal

Stored as numeric data types (int, float, Stored as character, string, or boolean data
Storage
double, etc.) types

String operations (concatenation), logical


Operations Arithmetic operations (+, -, *, /, %)
operations

2. Differentiate between the operators = and ==

Feature = (Assignment Operator) == (Equality Operator)

Purpose Assigns a value to a variable Compares two values for equality

Usage Used to set or update the value of a variable Used to check if two values are equal

Example int x = 5; if (x == 5) { ... }

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

Returns true if values are equal, otherwise


Result The variable is updated with the new value
false

Common Can accidentally use = when intending to Mistakenly using == when assignment is
Mistake use == intended

3. What is the use of this keyword in Java? V Imp

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.

4. What is constructor overloading?

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.

5. What is a derived class?

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.

8. What is Delegation event model?

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

9. Write a short note on Jcheckbox.

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.

10. Define a Layout Manager. List different Layout Managers.

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.

11. Distinguish between init() and start() methods of an applet.

Feature init() Method start() Method

Purpose Initialization of the applet. Starts or resumes the applet's execution.

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.

12. What are the JDBC API components?

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.

1. Define the term exception in Java

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.

3. Use of interface in Java- V Imp


In Java, an interface is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Interfaces are a powerful feature in
Java that enable us to write flexible, reusable, and maintainable code.

4. Syntax of switch statement in Java. V imp


The switch statement in Java provides a way to execute different parts of code based on the value of an
expression. It's a more elegant alternative to a series of if-else statements when there are multiple
possible values for a single variable.
Syntax:
switch (expression) {
switch(expression)
{
case value1 :
// Statements
break; //

case value2 :
// Statements
break; //
....
....
....
default :
// default Statement
}

5. What do you mean by stream in Java. Name 2 stream classes. V Imp


Streams in Java are part of the Java Collections Framework introduced in Java 8. They provide a
modern and efficient way to process collections of data in a declarative manner. Streams support
operations such as filtering, mapping, and reducing, allowing for more readable and maintainable
code.
In Java, the stream classes are part of the java.io package and provide a mechanism for reading and
writing data. The two commonly used stream classes are FileInputStream and FileOutputStream.

6. Write any 2 constructors of TextArea Class in Java


The TextArea class in Java is part of the java.awt package and provides a multi-line area for displaying
text. Here are two constructors of the TextArea class:
TextArea() and TextArea(String text).
7. Compilation of Java program
Compiling a Java program involves translating the high-level Java source code into bytecode, which the
Java Virtual Machine (JVM) can execute. Here’s a step-by-step overview of the compilation process:
1. Write the Java Source Code
2. Save the File
3. Open Command Prompt or Terminal
4. Navigate to the Directory
5. Compile the Java Program
6. Check for Errors
7. Run the Compiled Program

8. One dimensional array in Java


A one-dimensional array in Java is a data structure that stores a sequence of elements of the same
type in a linear arrangement. Arrays are commonly used to store multiple values in a single variable,
instead of declaring separate variables for each value.

9. Methods to set and retrieve thread priority


In Java, threads have a priority that indicates the relative importance of a thread. The thread priority
can be set and retrieved using methods provided by the Thread class.
The syntax for set priority is thread.setPriority(int newPriority);
The syntax for get priority is int priority = thread.getPriority();

10. Polymorphism in Java – V Imp


Polymorphism is one of the core concepts of object-oriented programming (OOP) in Java. It allows
objects of different classes to be treated as objects of a common superclass. There are two types of
polymorphism in Java: compile-time polymorphism (Method Overloading) and runtime polymorphism
(Method Overriding).

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.

12. Dynamic method dispatch in Java – V Imp


Dynamic method dispatch, also known as runtime polymorphism or dynamic binding, is a process in
Java where the method to be invoked is determined at runtime rather than compile time. This
mechanism allows a call to an overridden method to be resolved at runtime, depending on the object
type that is being referred to by the reference variable. It is a fundamental feature of object-oriented
programming that enables polymorphism in Java.

13. Use of extends keyword


In Java, the extends keyword is used to create a new class that inherits properties and behaviors (fields
and methods) from an existing class. This process is known as inheritance. The class being inherited
from is called the superclass (or parent class), and the class that inherits is called the subclass (or child
class). The extends keyword is fundamental to object-oriented programming in Java, enabling the
creation of hierarchical class structures that promote reuse, maintainability, and flexibility.

14. Short note on GridLayout in Java


GridLayout is a layout manager in Java's AWT (Abstract Window Toolkit) and Swing libraries, which
arranges components in a grid of equally sized cells. Each component takes up exactly one cell in the
grid, and all cells are of equal size, both horizontally and vertically. GridLayout simplifies the creation
of grid-based layouts, ensuring uniformity and consistency in component placement.

15. Syntax on how to define an interface in Java


An interface is a reference type, similar to a class, that can contain only abstract methods, default
methods, static methods, and constants. It cannot contain instance fields or constructors. Here’s the
syntax for defining an interface:

const MyInterface = {
method1: function () { },
method2: function (param1, param2) { },
};

16. Use of final keyword in Java – V Imp


In Java, the final keyword is used to define an entity that cannot be modified after it is initialized. It can
be applied to variables, methods, and classes, each with distinct implications. Using the final keyword
enhances code stability and security by preventing unintended modifications and inheritance.

17. Functions of button class in Java


The Button class in Java is part of the AWT (Abstract Window Toolkit) package and is used to create a
clickable button in a graphical user interface (GUI). It provides various functions to create, modify, and
interact with buttons. Some key functions of the Button class are Constructors, Label Management,
Event Handling, Enabling and Disabling, and Visibility.

18. Syntax of try… catch statement in Java. V Imp


The try statement defines the code block to run (to try). The catch statement defines a code block to
handle any error. The finally statement defines a code block to run regardless of the result.
Syntax:

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
}

19. Java program to generate n Fibonacci numbers in Java

import java.util.Scanner;

public class Fibonacci {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of Fibonacci numbers to generate: ");
int n = scanner.nextInt();
scanner.close();

int first = 0, second = 1;


System.out.print("First " + n + " Fibonacci numbers: ");

for (int i = 1; i <= n; ++i) {


System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}

20. Uses of break statement in Java

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.

21. What is an applet?

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.

22. Difference between Text- field and Text-area controls

Feature TextField TextArea

Input Type Single-line Multi-line

Class java.awt.TextField java.awt.TextArea

Typical Usage Short text inputs (e.g., names, emails) Long text inputs (e.g., comments, notes)

Methods setText(), getText(), setEditable() setText(), getText(), append(), setEditable()

Both TextField and TextArea provide methods for setting and getting text, as well as controlling whether the
text is editable.

23. What is meant by method over riding? V Imp

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.

24. How to make a picture as a background on web page?

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 {

background-image: url('background.jpg'); /* Path to your image file */

background-size: cover; /* Ensures the image covers the entire background */

background-position: center; /* Centers the image */

background-repeat: no-repeat; /* Prevents the image from repeating */

25. Difference between constructor and a method. V Imp


Aspect Constructor Method

Purpose Initialize objects Define behavior

Name Same as class Any valid identifier

Return Type No return type Must have a return type (or void)

Invocation Called automatically when object is created Called explicitly

Types Default, parameterized Instance, static

Inheritance Not inherited Inherited and can be overridden

26. Define 2 color class constructors. V Imp

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

1) Color(int r, int g, int b)

Syntax: Color color = new Color(int r, int g, int b);

2) Color(int r, int g, int b, int a)

Syntax: Color color = new Color(int r, int g, int b, int a);

27. What are the various access specifiers in Java

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

Outside Package Outside Package


Access Specifier Within Class Within Package
(Subclass) (Non-Subclass)

public Yes Yes Yes Yes

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

28. Give 2 selection statements in Java

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

30. What is the use of this pointer? V Imp

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.

31. How are arrays defined in Java? V Important

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

Syntax: type[] arrayName;

2) Create an Array by using the new keyword followed by the type and the number of elements the
array will hold.

Syntax: arrayName = new type[size];

3) Initialize the array either at the time of declaration or separately after declaration

Syntax: int[] numbers = {1, 2, 3, 4, 5};

4) Access Array Elements using the index, which starts from 0

Eg. int firstNumber = numbers[0]; // Accesses the first element

numbers[2] = 10; // Sets the third element to 10

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.

Syntax: throw new ExceptionType("Error Message");

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.

Syntax: returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ...

33. Use of super keyword in Java

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.

34. Use of finally clause in Java. Discuss with example. V Imp


In Java, the finally clause is used in conjunction with try and catch blocks to ensure that certain code is always
executed, regardless of whether an exception is thrown or not. It is typically used for cleanup activities, such as
closing files, releasing resources, or performing other tasks that must be done whether an exception occurs or
not.

Eg:

public class FinallyExample {

public static void main(String[] args) {

try {

int[] numbers = {1, 2, 3};

System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index is out of bounds!");

} finally {

System.out.println("This block always executes.");

System.out.println("Code after try-catch-finally block.");

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

36. What is a byte stream?

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:

// Code to be executed if expression equals value1

break;

case value2:

// Code to be executed if expression equals value2

break;

// Add more cases as needed

default:

// Code to be executed if expression doesn't match any case

38. What is a static or class variable

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.

39. What do you mean by parameterized constructor?

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.

40. Use of throw statement

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.

41. Thread class methods

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.

5. getName() - Returns this thread's name.

6. setName(String name) - Changes the name of the thread.

7. setPriority(int newPriority) - Changes the priority of the thread.

8. getPriority() - Returns this thread's priority.

9. getId() - Returns the identifier of the thread.

42. Label control

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.

43. Structure of Java applet program. V Imp

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

44. Java data types – V Imp

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:

1. Primitive Data Types

These are the most basic data types built into Java. There are 8 primitive data types:

Data Type Size Description Example Value

byte 1 byte Stores whole numbers from -128 to 127 100


Data Type Size Description Example Value

short 2 bytes Stores whole numbers from -32,768 to 32,767 10000

int 4 bytes Stores whole numbers from -2^31 to 2^31-1 100000

long 8 bytes Stores whole numbers from -2^63 to 2^63-1 100000L

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

boolean 1 bit Stores true or false values true

char 2 bytes Stores a single 16-bit Unicode character 'A'

2. Non-Primitive Data Types

These are also known as reference types, as they reference objects. Some examples include:

• String: Represents a sequence of characters. Example: String s = "Hello, World!";

• Arrays: Used to store multiple values of the same type. Example: int[] arr = {1, 2, 3, 4};

• Classes: A user-defined blueprint from which objects are created.

• Interfaces: Used to specify what a class must do but not how.

• Enumerations (enum): Represents a group of constants. Example: enum Color { RED, GREEN, BLUE };

45. Features of constructors

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

46. Packages in Java

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.

47. Event classes in Java

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

48. List class in Java

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.

49. Method overloading

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.

50. Operators in Java

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

51. Looping statements in Java

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.

52. Importance of update function in Java

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.

53. What is Byte code

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.

54.How to run an applet code

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.

55. What is a literal? V Imp

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.

56. How to declare an array in Java? V Imp

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.

57. What is an event

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.

58. Use of finalize method

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.

59. How to set priority for a thread

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.

60. Write the syntax of do…while loop

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

61. Define a user defined class in Java

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.

62. Write a program to plot a point on an applet

Creating a Java applet to plot a point involves using the Applet class and the Graphics class to draw on the
applet's canvas.

Eg. import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Color;

public class PlotPointApplet extends Applet {

@Override

public void paint(Graphics g) {

// Set the color for the point

g.setColor(Color.RED);
// Plot the point at (50, 50)

g.drawLine(50, 50, 50, 50);

63. What is a frame?

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.

65. How to define a method in Java

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

66. Structure of simple Java program

A typical Java program consists of the following components:

1. Package Declaration (optional)

2. Import Statements (optional)

3. Class Declaration

4. Main Method

5. Statements

Eg. // 1. Package Declaration (optional)

package com.example;

// 2. Import Statements (optional)

import java.util.Scanner;

// 3. Class Declaration

public class SimpleJavaProgram {

// 4. Main Method

public static void main(String[] args) {

// 5. Statements
System.out.println("Hello, World!");

// Example of using a Scanner to read user input

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.println("Hello, " + name + "!");

scanner.close();

67. What is data hiding?

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.

68. What is a thread?

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.

69. What is a package in Java?

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.

Commonly Used Java Packages

• 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.io: Provides classes for input and output operations.

• java.net: Contains classes for networking applications.

• java.awt and javax.swing: Provides classes for creating graphical user interfaces (GUI).

70. Constructors of label class

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.

71. Define an interface. Give eg.


An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors.
They are used to specify a set of methods that a class must implement, providing a form of abstraction and
multiple inheritance.

Example of defining an interface in Java:

public interface Animal {

// Abstract method

void sound();

// Default method

default void sleep() {

System.out.println("Sleeping...");

72. Syntax of for loop in Java

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.

Syntax of for Loop:

for (initialization; condition; increment/decrement) {

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

public class PalindromeCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = scanner.nextLine();

// Create a StringBuffer object

StringBuffer stringBuffer = new StringBuffer(input);

// Reverse the string


stringBuffer.reverse();

// Convert the reversed StringBuffer to a string

String reversedString = stringBuffer.toString();

// Check if the original string is equal to the reversed string

if (input.equals(reversedString)) {

System.out.println("The string is a palindrome.");

} else {

System.out.println("The string is not a palindrome.");

scanner.close();

74. Explain checkbox class

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.

76. Write a Java program to create thread by implementing runnable interface

// Implementing the Runnable interface

public class MyRunnable implements Runnable {

@Override

public void run() {

// Code to be executed in the thread

for (int i = 1; i <= 5; i++) {

System.out.println(Thread.currentThread().getName() + " - Count: " + i);

try {

Thread.sleep(1000); // Pausing for 1 second

} catch (InterruptedException e) {

e.printStackTrace();

}
}

public static void main(String[] args) {

// Creating instances of the Runnable implementation

MyRunnable myRunnable1 = new MyRunnable();

MyRunnable myRunnable2 = new MyRunnable();

// Creating threads and passing the Runnable instances to the Thread constructor

Thread thread1 = new Thread(myRunnable1, "Thread-1");

Thread thread2 = new Thread(myRunnable2, "Thread-2");

// Starting the threads

thread1.start();

thread2.start();

77. Constructors of list interface

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.

Common Implementations of the List Interface are ArrayList, LinkedList, or Vector.

78. Life cycle of thread

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.

Following are the stages of the life cycle −

• 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.

79. Explain choice control

"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.

80. Explain buffered writer class

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.

81. Write a Java program to implement Applet concept

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

@Override

public void paint(Graphics g) {

// Display a string in the applet window

g.drawString("Hello, Applet!", 20, 20);

82. Explain interfaces with syntax and example

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:

public interface InterfaceName {

// Abstract method

void method1();
// Default method (introduced in Java 8)

default void method2() {

System.out.println("Default method");

// Static method (introduced in Java 8)

static void method3() {

System.out.println("Static method");

// Constant

int CONSTANT_NAME = 100;

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;

public class DrawShapes extends JPanel {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

// Set color for drawing

g.setColor(Color.BLUE);

// Draw a rectangle

g.drawRect(50, 50, 100, 60);

// Draw an oval

g.drawOval(200, 50, 100, 60);


// Draw a circle (an oval with equal width and height)

g.drawOval(350, 50, 60, 60);

// Draw an arc

g.drawArc(50, 150, 100, 60, 0, 180);

public static void main(String[] args) {

JFrame frame = new JFrame("Draw Shapes");

DrawShapes panel = new DrawShapes();

// Set up the frame

frame.add(panel);

frame.setSize(500, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

You might also like