2 MARK JAVA
2 MARK JAVA
A numeric literal is a number that represents a constant value directly in code, such as
123, 45.67, or 0xAB (hexadecimal). Non-numeric literals are constants that represent
non-numeric values, such as characters ('a'), strings ("hello"), and boolean values
(true or false).
Example:
java
Copy code
int num = 100; // numeric literal
char letter = 'A'; // non-numeric literal
The = operator is used for assignment, i.e., it assigns a value to a variable. The ==
operator is used for comparison, i.e., it checks if two values are equal.
Example:
java
Copy code
int a = 5; // '=' assigns value 5 to a
if (a == 5) { // '==' checks if a is equal to 5
System.out.println("a is 5");
}
The this keyword refers to the current object within a method or constructor. It is used
to distinguish between instance variables and parameters with the same name or to
invoke other constructors of the same class.
Example:
java
Copy code
class Person {
String name;
Person(String name) {
this.name = name; // 'this' refers to the instance variable
}
}
Constructor overloading occurs when a class has multiple constructors with different
parameter lists. This allows creating objects in different ways depending on the number
or type of arguments passed.
Example:
java
Copy code
class Person {
String name;
int age;
A derived class (also known as a subclass) is a class that inherits properties and
behaviors from another class, called the base class (superclass). The derived class can
extend or modify the functionality of the base class.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
6. Define a Package.
Example:
java
Copy code
package mypackage;
class MyClass {
// Class code here
}
7. What is exception handling?
Example:
java
Copy code
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("This block runs regardless of exception.");
}
The Delegation event model is used in Java's GUI programming to handle events. In this
model, an event listener (delegated) is registered to listen for events like clicks or key
presses, and the listener delegates the event handling to methods defined in the class.
Example:
java
Copy code
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
}
JCheckBox is a Swing component that allows the user to choose one or more options
from a set. It provides a checkbox with two states: selected (checked) and unselected
(unchecked).
Example:
java
Copy code
JCheckBox checkBox = new JCheckBox("Accept Terms and Conditions");
checkBox.setSelected(true); // Set checkbox as checked
Example:
java
Copy code
setLayout(new FlowLayout()); // Setting FlowLayout for the
container
In an applet, the init() method is called once when the applet is loaded, used for
initialization, such as setting up resources. The start() method is called each time
the applet becomes visible or starts, useful for tasks like starting animations or threads.
The & operator is a bitwise AND operator that works on individual bits, while && is a
logical AND operator that evaluates expressions and returns true only if both operands
are true.
Example:
java
Copy code
// Bitwise AND
int result1 = 5 & 3; // 0101 & 0011 = 0001
// Logical AND
boolean result2 = (5 > 3) && (8 < 10); // true
The switch statement is used to execute one out of many possible blocks of code
based on the value of a variable.
Example:
java
Copy code
int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid day");
}
In Java, a class is a blueprint or template for creating objects, which defines properties
(variables) and methods (functions) that the objects will have. An object is an instance
of a class, representing a specific entity that is created from the class template.
Example:
java
Copy code
class Car {
String brand;
int year;
void displayInfo() {
System.out.println(brand + " " + year);
}
}
Java does not support multiple inheritance directly through classes to avoid complexity
and ambiguity. If a class were to inherit from two classes that have the same method, it
would cause confusion. However, Java supports multiple inheritance through
interfaces, which avoids such issues.
Example:
java
Copy code
abstract class Animal {
abstract void sound(); // Abstract method without
implementation
}
Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // One-dimensional array
System.out.println(numbers[0]); // Access first element
A package in Java is used to group related classes and interfaces together. It helps in
organizing the code, avoiding name conflicts, and providing access protection and
easier maintenance.
Example:
java
Copy code
package utilities; // Package declaration
Swing is a GUI toolkit in Java that is part of the Java Foundation Classes (JFC). It
provides a rich set of components like buttons, labels, tables, and text fields for
building window-based applications. Swing components are lightweight and platform-
independent.
Example:
java
Copy code
import javax.swing.*;
The ComponentEvent class in Java is part of the AWT (Abstract Window Toolkit) event
handling mechanism. It is used for handling events related to component changes,
such as resizing or moving a window.
Example:
java
Copy code
import java.awt.*;
import java.awt.event.*;
Swing is a part of Java’s GUI toolkit, while JPanel is a container used to group
components together. JPanel is often used as a child container inside a frame to
organize the layout of components.
Example:
java
Copy code
import javax.swing.*;
drawRect() is used to draw a rectangle's outline, while fillRect() fills the entire
rectangle with a specified color. drawRect() only draws the border, and fillRect()
fills the interior.
Example:
java
Copy code
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawRect(50, 50, 100, 50); // Draws rectangle outline
g.fillRect(200, 50, 100, 50); // Fills rectangle with color
Command line arguments are passed to the Java program at the time of running it. They
are stored in an array of String objects and can be used to pass data to the program
from the command prompt.
Example:
java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg); // Prints each command line
argument
}
}
}
26. List out the different branching statements used in Java.
A class is a blueprint or template in Java that defines the properties (fields) and
behaviors (methods) of objects. A class is used to create instances (objects) and is
fundamental to object-oriented programming.
Example:
java
Copy code
class Car {
String model;
void displayModel() {
System.out.println(model);
}
}
Class members (fields and methods) can be accessed using an object by referencing
the class instance. The dot operator (.) is used to access them.
Example:
java
Copy code
Car car = new Car(); // Creating an object
car.model = "Toyota"; // Accessing the class member 'model'
car.displayModel(); // Calling the method using the object
29. What is the use of protected keyword in Java?
The protected keyword in Java is used to specify that a member (variable or method)
can be accessed within the same package or by subclasses (even if they are in different
packages).
Example:
java
Copy code
class Animal {
protected void sound() {
System.out.println("Animal sound");
}
}
An array in Java is a data structure that stores multiple values of the same type in a
single variable. Arrays are indexed and the elements can be accessed using their index.
Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // Declare and initialize an array
System.out.println(numbers[2]); // Accessing the third element (3)
31. Explain newborn state of a thread?
In Java, the newborn state (also called the "new state") is the state when a thread is
created but has not yet started execution. The thread is in this state after invoking the
Thread class constructor but before calling start().
The ResultSet in JDBC represents the result set of a database query. It provides
methods to iterate through the data, retrieve values, and update rows in the result set.
Example:
java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
Example: In OOP, classes like Car and Person might interact with each other, whereas
in POP, the program might contain functions like moveCar() or driveCar().
The continue statement in Java is used to skip the current iteration of a loop and move
to the next iteration. It is useful when you want to skip specific conditions during a loop
without exiting the loop.
Example:
java
Copy code
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip printing 3
}
System.out.println(i);
}
38. Define classes and objects.
A class in Java is a template or blueprint for creating objects. It defines the properties
(variables) and behaviors (methods) that the objects created from it will have. An object
is an instance of a class, created using the new keyword.
Example:
java
Copy code
class Animal {
String name;
void speak() {
System.out.println(name + " says Hello!");
}
}
A constructor in Java is a special method used to initialize objects. It has the same
name as the class and does not have a return type. It is called automatically when an
object is created using the new keyword.
Example:
java
Copy code
class Car {
String brand;
// Constructor
Car(String b) {
brand = b;
}
void displayBrand() {
System.out.println("Brand: " + brand);
}
}
The protected keyword in Java is used to specify that a member (variable or method)
of a class can be accessed within the same package or by subclasses, even if they are
in different packages. It offers more access than private but less than public.
Example:
java
Copy code
class Animal {
protected void sound() {
System.out.println("Some sound");
}
}
An array in Java is a collection of elements of the same data type stored in a contiguous
memory location. It allows you to store multiple values in a single variable and access
them using indices.
Example:
java
Copy code
int[] numbers = {10, 20, 30, 40}; // Array initialization
System.out.println(numbers[1]); // Accessing the second element
(20)
In Java, the newborn state refers to the state of a thread when it is created but has not
yet started running. The thread is in this state immediately after calling the Thread
class constructor, but before invoking the start() method.
Example:
java
Copy code
try {
int division = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
}
44. What are differences between Swing and AWT?
• AWT (Abstract Window Toolkit) is Java’s original GUI toolkit, using native
components, which makes it platform-dependent.
• Swing is a more modern GUI toolkit that provides a richer set of components
and is platform-independent, as it uses lightweight components (not tied to
native OS components).
1. Header: Contains meta-information like the title, logo, and navigation links.
2. Body: Holds the main content of the page such as text, images, forms, and
tables.
3. Footer: Includes additional information such as contact details, copyright, or
social media links.
A ResultSet in JDBC represents the result set of a database query. It provides methods
for accessing data returned by a query, allowing you to iterate over rows and extract
column values.
Example:
java
Copy code
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("username"));
}
java
Copy code
int num = 10; // Numeric literal
String name = "John"; // Non-numeric literal
Example:
java
Copy code
int a = 5; // Assignment using '='
if (a == 5) { // Comparison using '=='
System.out.println("a is equal to 5");
}
The this keyword in Java refers to the current instance of the class. It is used to refer to
the current object, especially when distinguishing between class fields and parameters
with the same name.
Example:
java
Copy code
class Car {
String model;
Car(String model) {
this.model = model; // 'this' refers to the current
object's 'model'
}
}
Constructor overloading in Java refers to the ability to define multiple constructors with
different parameter lists within the same class. This allows objects of the class to be
created with different initial values.
Example:
java
Copy code
class Car {
String model;
Car() {
model = "Unknown";
}
Car(String model) {
this.model = model;
}
}
A derived class is a class that inherits properties and behaviors from a base class (also
called a superclass). The derived class can add or modify methods and fields from the
base class.
Example:
java
Copy code
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
Example:
java
Copy code
package mypackage; // User-defined package
Example:
java
Copy code
try {
int result = 10 / 0; // Dividing by zero will throw an
exception
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("Finally block executed");
}
The Delegation Event Model in Java is a way of handling events by delegating the event
handling task to a specific object (usually a listener). In this model, components (like
buttons) do not handle events directly but instead delegate the task to an event listener
class, which processes the event.
Example:
java
Copy code
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
}
A JCheckBox in Java Swing is a component that allows the user to select one or more
options from a set of choices. It can have two states: selected and unselected. When a
JCheckBox is selected, it indicates a positive choice, and when unselected, it indicates
a negative choice.
Example:
java
Copy code
JCheckBox checkBox = new JCheckBox("Accept Terms and Conditions");
checkBox.setSelected(true); // Sets the checkbox as selected
1. FlowLayout: Components are arranged in a line, and once the line is filled, a
new line is created.
2. BorderLayout: Divides the container into five sections: North, South, East,
West, and Center.
3. GridLayout: Components are arranged in a grid with equal-sized cells.
4. CardLayout: Manages a set of components that can be flipped between.
5. GridBagLayout: A flexible layout that arranges components in a grid with varying
row and column spans.
• init(): It is called only once when the applet is loaded for the first time. It is used
to initialize the applet and set up its environment.
• start(): It is called after the init() method and whenever the applet becomes
visible. It is typically used for tasks that need to run when the applet is active,
like animation or processing.
The JDBC (Java Database Connectivity) API components allow Java programs to
interact with relational databases. The key components include:
• & (bitwise AND operator): It is a bitwise operator that operates on individual bits
of two operands.
• && (logical AND operator): It is a logical operator used in conditional
statements. It returns true only if both conditions are true, and it short-circuits,
meaning it stops evaluating once the first condition is false.
Example:
java
Copy code
int a = 5, b = 10;
if (a > 0 && b > 0) { // Logical AND (&&)
System.out.println("Both are positive");
}
The switch case structure allows you to execute one of many blocks of code based on
the value of a variable. It is typically used as an alternative to multiple if-else
statements.
Syntax:
java
Copy code
switch (variable) {
case value1:
// Code to be executed if variable == value1
break;
case value2:
// Code to be executed if variable == value2
break;
default:
// Code to be executed if no case matches
}
A class in Java is a blueprint for creating objects. It defines properties (fields) and
behaviors (methods) that the objects created from it will have. An object is an instance
of a class, and it holds actual values for the properties defined by the class.
Example:
java
Copy code
class Car {
String color;
void start() {
System.out.println("Car started!");
}
}
Java does not support multiple inheritance (a class inheriting from more than one
class) because it can lead to ambiguity. For example, if two parent classes have the
same method, the child class might not know which one to inherit. Java uses interfaces
to achieve multiple inheritance without ambiguity.
63. What is an abstract method?
Example:
java
Copy code
abstract class Animal {
abstract void sound(); // Abstract method
}
Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // One-dimensional array
System.out.println(numbers[2]); // Output: 3
A package in Java is used to group related classes and interfaces together, which helps
avoid class name conflicts. It also provides access control and organizes files in a
project efficiently. Java has built-in packages (e.g., java.util, java.io) and user-
defined packages.
66. Define Swing.
Swing is a GUI toolkit for Java that provides a richer set of components than AWT
(Abstract Window Toolkit). Swing components are lightweight, meaning they are not
dependent on the platform's native windowing system, making them platform-
independent.
Example:
java
Copy code
JButton button = new JButton("Click Me");
• Swing is a GUI toolkit in Java that provides lightweight components and is built
on top of AWT.
• JPanel is a specific container in Swing that is used to group multiple
components together inside a window.
Example:
java
Copy code
JPanel panel = new JPanel(); // JPanel to group components
JButton button = new JButton("Button");
panel.add(button);
69. Discuss various steps involved in loading and running a remote
applet.
Example:
java
Copy code
Graphics g = getGraphics();
g.drawRect(50, 50, 100, 60); // Draw an empty rectangle
g.fillRect(200, 50, 100, 60); // Fill a rectangle with color
Command line arguments in Java are values passed to a program when it is executed.
They are accessible within the main method as an array of String values. These
arguments allow users to provide input directly from the command line.
Example:
java
Copy code
public class CommandLine {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
The this reference in Java refers to the current instance of the class. It is commonly
used to differentiate between instance variables and method parameters when they
have the same name.
Example:
java
Copy code
class Car {
String model;
Car(String model) {
this.model = model; // 'this' refers to the instance
variable
}
}
The continue statement in Java is used inside loops to skip the current iteration and
proceed with the next iteration of the loop. It is typically used when you want to skip
certain conditions and continue processing the loop.
Example:
java
Copy code
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is 3
}
System.out.println(i);
}
Output: 1, 2, 4, 5 (3 is skipped)
The super keyword in Java refers to the immediate parent class of a subclass. It can be
used to access:
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
A static variable in Java is a class-level variable shared by all instances (objects) of the
class. It is initialized only once, at the start of the program, and its value is shared
among all instances of the class.
Example:
java
Copy code
class Counter {
static int count = 0; // Static variable
Counter() {
count++;
}
}
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 have instance fields and can only provide method signatures.
Classes implement interfaces to define the behavior promised by the interface.
Example:
java
Copy code
interface Animal {
void sound(); // Abstract method
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
Java provides many API packages for building applications. Some of the key Java API
packages are:
Example:
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
• Swing is part of the Java Foundation Classes (JFC) and provides a richer set of
GUI components, including features like pluggable look-and-feel and better
performance. Swing components are lightweight and do not rely on the
platform’s native GUI.
• AWT (Abstract Window Toolkit) is Java’s original GUI library. It provides basic
GUI components, but AWT components are heavyweight, meaning they rely on
the underlying platform’s windowing system.
Example:
java
Copy code
// Swing Example
JButton swingButton = new JButton("Swing Button");
// AWT Example
Button awtButton = new Button("AWT Button");
Swing provides a wide range of GUI components. Some key Swing components include:
Example:
java
Copy code
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, World!");
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Example:
java
Copy code
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the current iteration when i is 3
}
System.out.println(i);
}
Output: 1, 2, 4, 5 (3 is skipped)
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Example:
java
Copy code
class Counter {
static int count = 0; // Static variable
Counter() {
count++;
}
}
An interface in Java defines a contract for what a class can do, but
not how it does it. It contains abstract methods that the
implementing class must define. Interfaces can also include default
methods with implementation and static methods. They allow multiple
inheritance of method signatures.
Example:
java
Copy code
interface Animal {
void sound(); // Abstract method
}
Java provides many API packages that provide pre-built classes and
interfaces for various tasks. Some of the key Java API packages are:
Example:
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
Example:
java
Copy code
// AWT Button
Button awtButton = new Button("AWT Button");
// Swing Button
JButton swingButton = new JButton("Swing Button");
Example:
java
Copy code
class Car {
String model;
Car(String model) {
this.model = model; // 'this' refers to the current
instance variable
}
}