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

java

A thread is the smallest unit of execution within a process, allowing for concurrent operations. Its lifecycle includes states such as New, Runnable, Running, Blocked, and Waiting, each representing different stages of execution. Additionally, the document discusses types of errors in programming, including syntax, runtime, and logical errors, along with Java's exception handling mechanisms.

Uploaded by

asandeepay
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

A thread is the smallest unit of execution within a process, allowing for concurrent operations. Its lifecycle includes states such as New, Runnable, Running, Blocked, and Waiting, each representing different stages of execution. Additionally, the document discusses types of errors in programming, including syntax, runtime, and logical errors, along with Java's exception handling mechanisms.

Uploaded by

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

define thread and explain its lifecycle

ans: A thread is the smallest unit of execution in a program. It is a lightweight process that
runs within the context of a larger process and shares the process’s resources (such as
memory and file handles). Multiple threads within the same process can execute
concurrently, allowing efficient multitasking.

Threads are used to perform multiple operations simultaneously, like handling user input
while performing calculations or downloading data in the background.

New (Created)

• A thread is in this state when it is created using a constructor, like Thread t = new
Thread();

• The thread object exists, but it hasn't started executing yet.

• Method not called yet: start()

Example (Java):

java

CopyEdit

Thread t = new Thread(); // New state

2. Runnable

• The thread is ready to run and is waiting for CPU time.

• When you call start(), the thread enters the Runnable state.

3. Running

• The thread is now actively executing code in its run() method.

• Only one thread can run on a core at a time, but many can be in the Runnable pool.

4. Blocked

• A thread enters the Blocked state when it tries to access a synchronized section of
code that's locked by another thread.
5. Waiting

• A thread is in the Waiting state when it waits indefinitely for another thread to
perform a task (e.g., notify it).

• It will not return to Runnable unless explicitly signaled (notify() or notifyAll()).

Que 2:

1. Syntax Errors

Definition:
Errors that occur when the rules (syntax) of the programming language are violated.

• Detected during compilation (in compiled languages like Java, C++).

• Prevent the program from running.

Examples:

java

CopyEdit

int a = 5 // Missing semicolon → Syntax Error

python

CopyEdit

print("Hello" # Missing closing parenthesis → Syntax Error

2. Runtime Errors

Definition:
Errors that occur while the program is running.

• These are typically caused by illegal operations (e.g., dividing by zero, accessing
invalid memory).

• Can be handled using exception handling mechanisms in most languages.

Examples:

• Division by zero
• Null reference errors

• File not found

• Array index out of bounds

Java Example:

java

CopyEdit

int a = 5 / 0; // Runtime Error: ArithmeticException

Python Example:

python

CopyEdit

x = int("abc") # Runtime Error: ValueError

3. Logical Errors

Definition:
Errors where the program runs without crashing but produces incorrect or unexpected
results.

• Hardest to detect, because there's no error message.

• Caused by flaws in logic or algorithm.

Example:

java

CopyEdit

// Trying to calculate area but used wrong formula

int area = length + breadth; // Logical Error (should be length * breadth)

python

CopyEdit

# Wrong formula used, no error thrown

def square(n):

return n + n # Logical Error: should be n * n


In Java: Additional Types of Errors

Java has two major categories of error-like conditions:

A. Errors (in java.lang.Error)

• Serious issues the application should not try to handle.

• Examples: OutOfMemoryError, StackOverflowError

B. Exceptions (in java.lang.Exception)

• Can be caught and handled.

• Split into:

o Checked Exceptions (e.g., IOException)

o Unchecked Exceptions (e.g., NullPointerException)

Que 3: public class TryCatchExample {

public static void main(String[] args) {

try {

int a = 10;

int b = 0;

int result = a / b; // This will throw ArithmeticException

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero!");

System.out.println("Program continues after try-catch block.");

}
Que 4:

Que 5:

Que 6:

AWT Components (java.awt.*)

• Button

• Label

• TextField

• TextArea

• Checkbox

• CheckboxGroup

Swing Components (javax.swing.*)

• JButton

• JLabel

• JTextField

• JText
Que 7:

import javax.swing.*;

import java.awt.event.*;

public class ComboBoxExample {

public static void main(String[] args) {

// Create frame

JFrame frame = new JFrame("JComboBox Example");

// Create combo box with items

String[] fruits = {"Apple", "Banana", "Mango", "Orange"};

JComboBox<String> comboBox = new JComboBox<>(fruits);

comboBox.setBounds(50, 50, 150, 30);

// Create label to show selected item

JLabel label = new JLabel("Select a fruit");

label.setBounds(50, 100, 200, 30);

// Add ActionListener to combo box

comboBox.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String selected = (String) comboBox.getSelectedItem();

label.setText("You selected: " + selected);

});
// Add components to frame

frame.add(comboBox);

frame.add(label);

frame.setSize(300, 200);

frame.setLayout(null);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Que 8:
9:

A proxy server is an intermediate server that sits between a client (user) and the
destination server (like a website). It receives the client's request, forwards it to the
destination, gets the response, and sends it back to the client.

11:

URL Class – Important Methods (in java.net package)

1. getProtocol()

o Returns the protocol used (e.g., http, https, ftp).

2. getHost()

o Returns the host name (e.g., www.example.com).

3. getPort()

o Returns the port number (e.g., 443).

o Returns -1 if no port is specified.

4. getDefaultPort()

o Returns the default port for the protocol (e.g., 443 for HTTPS).

5. getPath()

o Returns the file path in the URL (e.g., /folder/file.html).

6. getFile()

o Returns the path + query string if any (e.g., /file.html?name=test).

7. getQuery()

o Returns the query part of the URL (after ?, like name=test).

8. getRef()

o Returns the reference/fragment part (after #, like section1).

9. openConnection()

o Opens a connection to the URL for reading data.


10. toURI()

• Converts the URL object to a URI object.

11. toString() / toExternalForm()

• Returns the full URL as a String.

12

The finally block is a part of Java's exception handling mechanism that is used to execute
important code like cleanup code, resource releasing, and closing files or connections.

It is executed after the try and catch blocks, regardless of whether an exception was
thrown or not.

ensure resources are closed properly:

• Files

• Database connections

• Network sockets

To run important cleanup code, even if an error happens.

To avoid code duplication in catch blocks for cleanup.

You might also like