0% found this document useful (0 votes)
33 views8 pages

Unit - I: Core Java

The document discusses core Java concepts including identifiers, variables, data types, control flow statements like if-else and switch, and object-oriented programming concepts like classes, interfaces, and inheritance. It covers these topics across three units - the first unit discusses identifiers, variables, and applications that can be developed in Java. The second unit covers nested if statements, switch statements, and the static keyword. The third unit discusses multiple inheritance in Java through implementing multiple interfaces, and compares the differences between arrays and vectors.

Uploaded by

inshah876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views8 pages

Unit - I: Core Java

The document discusses core Java concepts including identifiers, variables, data types, control flow statements like if-else and switch, and object-oriented programming concepts like classes, interfaces, and inheritance. It covers these topics across three units - the first unit discusses identifiers, variables, and applications that can be developed in Java. The second unit covers nested if statements, switch statements, and the static keyword. The third unit discusses multiple inheritance in Java through implementing multiple interfaces, and compares the differences between arrays and vectors.

Uploaded by

inshah876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CORE JAVA

UNIT - I

1. What are Identifiers, keywords? What are the rules?


Ans. Identifiers : Identifiers are user-defined names for various program elements like variables,
functions, and classes.
Examples of identifiers:
i. Variable: counter
ii. Function: calculate_sum
iii. Class: Person
iv. Module: math_utils
v. Constant (usually in uppercase): PI
Keywords : Keywords are predefined words in a programming language with specific meanings and
purposes. They cannot be used as identifiers.
Examples of keywords vary depending on the programming language. Here are some common ones in
Python:
i. I. if: Used for conditional statements.
ii. while: Used for loops.
iii. for: Used for loops.
iv. class: Used to define classes.
v. import: Used to import modules.
-> Rules for Identifiers and Keywords:
i. Identifiers should start with a letter or underscore.
ii. They can contain letters, digits, and underscores.
iii. Identifiers are usually case-sensitive (e.g., myVar and myvar are treated differently).
iv. Keywords are reserved and cannot be used as identifiers.
v. Adhere to language-specific conventions and limits for identifiers.
These rules ensure that your code is readable and follows the syntax of the programming language
you're using while preventing conflicts with reserved words.

2. What are variables and their types?


Ans. Variables are used to store and manage data in computer programs. They act as symbolic names
for values that can be changed or manipulated during the execution of a program. Variables are a
fundamental concept in programming and come in various types depending on the kind of data they
can hold.
Here are the common types of variables:
i. Numeric: Hold numbers (integers, floating-point, double).
->Example: age = 25, salary = 50000.50
ii. Text: Store sequences of characters (strings).
->Example: name = "Alice", message = "Hello"
iii. Boolean: Represent binary values (True or False).
->Example: is_student = True, is_adult = False
iv. Containers: Hold collections of items (lists, tuples, dictionaries, sets).
->Example: fruits = ['apple', 'banana'], student_info = {'name': 'Alice'}
v. Other Types: Constants (uppercase, rarely changed) and None (absence of a value).
->Example: PI = 3.14159, empty_value = None

3. Types of application that can be developed using java language.


Ans. Java is a versatile programming language that can be used to develop a wide range of
applications across different domains. Java's platform independence, extensive libraries and
frameworks, strong community support, and performance make it suitable for a wide range of
application development projects in various industries. Here are some types of applications that can
be developed using Java:
i. Web Applications: Java is commonly used for building web applications, both on the server-side
and client-side. Server-side web applications can be created using Java frameworks like Spring,
JavaServer Faces (JSF), and Java Servlets. These applications handle server logic, database
connectivity, and the generation of dynamic web content.
CORE JAVA

ii. Enterprise Applications: Java is a popular choice for developing enterprise-level applications,
including Customer Relationship Management (CRM) systems, Enterprise Resource Planning
(ERP) systems, and Human Resource Management (HRM) systems.
iii. Mobile Applications (Android): Java is one of the primary programming languages for developing
Android applications. Developers use Java to write Android apps using the Android Studio IDE
and the Android SDK.
iv. Desktop Applications: Java can be used to create cross-platform desktop applications with
graphical user interfaces (GUIs) using libraries like JavaFX and Swing. These applications can run
on different operating systems without modification.
v. IoT (Internet of Things) Applications: Java can be used for developing IoT applications, especially
for devices with more processing power and memory. It provides the advantage of platform
independence and security features.

UNIT - II
1. Nested if statement with example.
Ans. Nested if statements are a way to create more complex conditional logic in programming by
placing one or more if statements inside another if statement. This allows you to make decisions
based on multiple conditions.
-> For example:
public class NestedIfExample {
public static void main(String[] args) {
int age = 25;
int income = 50000;

if (age >= 18) {


System.out.println("You are an adult.");

if (income > 30000) {


System.out.println("You have a decent income.");
} else {
System.out.println("You have a lower income.");
}
} else {
System.out.println("You are a minor.");
}
}
}
-> Output:
You are an adult.
You have a decent income.

2. Switch statement with example.


Ans. A switch statement in programming is used to perform different actions based on different
conditions or values of an expression. It's often used as an alternative to a long chain of if-else
statements when you need to make decisions based on the value of a single variable.
-> For example:
public class SwitchExample {
public static void main(String[] args) {
int dayOfWeek = 3;

switch (dayOfWeek) {
case 1:
System.out.println("It's Monday.");
break;
case 2:
System.out.println("It's Tuesday.");
CORE JAVA

break;
case 3:
System.out.println("It's Wednesday.");
break;
case 4:
System.out.println("It's Thursday.");
break;
case 5:
System.out.println("It's Friday.");
break;
case 6:
System.out.println("It's Saturday.");
break;
case 7:
System.out.println("It's Sunday.");
break;
default:
System.out.println("Invalid day of the week.");
}
}
}
-> Output:
It's Wednesday.

3. Static keyword in Core Java.


Ans. In Core Java, the static keyword is used to define class-level members and methods, which are
associated with the class itself rather than with instances (objects) of the class. Here are the main
uses of the static keyword in Core Java:
i. Static Variables: Shared among all instances of a class.
-> Example:
static int count = 0;
ii. Static Methods: Belong to the class, not instances.
-> Example:
static int add(int a, int b) {
return a + b;
}
iii. Static Initialization Blocks: Initialize static variables when the class is loaded.
-> Example:
static int x;
static {
x = 42;
}
iv. Static Nested Classes: Nested classes associated with the outer class.
-> Example:
static class StaticNestedClass {
// Static nested class members
}
v. Static Import: Import static members directly.
-> Example:
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
The `static` keyword is used to define class-level elements that are shared or associated with the class
itself, not individual instances.
CORE JAVA

UNIT - III

1. Multiple inheritance.
Ans. In Java, multiple inheritance of behavior is achieved through interfaces. A class can implement
multiple interfaces, inheriting their method signatures. Java does not support multiple inheritance in
the way some other programming languages like C++ do, where a class can inherit from multiple base
classes directly. However, Java does provide a form of multiple inheritance through interfacess.
-> Example:
interface Walkable {
void walk();
}

interface Swimmable {
void swim();
}

class Dog implements Walkable, Swimmable {


@Override
public void walk() {
System.out.println("Dog is walking.");
}

@Override
public void swim() {
System.out.println("Dog is swimming.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.walk();
dog.swim();
}
}
In this example, the `Dog` class implements both `Walkable` and `Swimmable` interfaces, inheriting
their methods.

2. Difference between vector and array.


Ans.
Aspect Array Vector(ArrayList in Java)
Size Fixed size, defined at creation. Dynamic, can grow or shrink as
needed.
Synchronization Not synchronized by default. Synchronized by default in Java.
Performance Generally better performance. May have performance overhead due
to synchronization.
Usage Suitable for fixed-sized collections. Used when dynamic resizing is
needed and thread safety is required.
Adding elements Fixed sized, you need to copy Dynamic, elements can be added
elements to resize. without resizing.
Removing elements Requires shifting elements when Elements can be removed efficiently
removed from the middle. without shifting.
Acessing elements Elements can be accessed directly by Elements can be accessed directly by
index. index.
Length/size Accessed using ‘length’ property. Accessed using ‘size()’ method.
CORE JAVA

Type Safety Less type-safe, as elements can be More type-safe, as it can be


of different types. parameterized to hold a specific type.
Compatibility with Older arrays are not compatible with Fully compatible with generics.
Generics generics.
Declaration Int[] arr = new int[5]; ArrayList<Integer> list = new
ArrayList<>();

3. Advantages of vector class over java arrays.


Ans. Following are some advantages of using vector class over java arrays:
i. Dynamic Sizing: One of the primary advantages of using the `Vector` class is its dynamic sizing
capability. Unlike traditional arrays, where you must specify the size at the time of creation,
vectors can grow or shrink as needed. This dynamic sizing makes vectors more flexible when you
don't know the exact size of the collection in advance.
ii. Automatic Resizing: Vectors automatically handle resizing behind the scenes. When a vector
reaches its capacity, it efficiently resizes itself to accommodate additional elements. This
automatic resizing saves developers from the manual and error-prone task of managing the size
of the collection.
iii. Ease of Use: Vectors provide a range of convenient methods for adding, removing, and accessing
elements. These methods, such as `add()`, `remove()`, `get()`, and `size()`, simplify common
operations and reduce the need for low-level array manipulation. This leads to more concise and
readable code.
iv. Type Safety: Vectors can be parameterized with a specific data type, making them type-safe. This
means you can create a Vector of a particular class or data type, and the Java compiler ensures
type correctness. This reduces the risk of runtime errors related to incompatible data types.
v. Synchronization: Vectors are synchronized by default. In a multi-threaded environment, multiple
threads can safely access and modify a vector without worrying about race conditions. This
inherent synchronization ensures data integrity, which is crucial in scenarios where concurrent
access is possible.

UNIT - IV

1. Explain file class with example.


Ans. In Java, the File class is part of the java.io package and is used to work with files and directories
on the file system. It allows you to perform various file-related operations, such as check the
existence of a file, retrieve its information, and rename it. Here's an example of using the File class to
check the existence of a file, retrieve its information, and rename it:
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File file = new File("C:\\myfolder\\myfile.txt");
if (file.exists()) {
System.out.println("File Name: " + file.getName());
System.out.println("File Path: " + file.getAbsolutePath());
System.out.println("File Size: " + file.length() + " bytes");
File newFile = new File("C:\\myfolder\\newname.txt");
if (file.renameTo(newFile)) {
System.out.println("File renamed to: " + newFile.getName());
} else {
System.out.println("File renaming failed.");
}
} else {
System.out.println("File does not exist.");
}
}
}
CORE JAVA

2. Advantages of Multi-threading.
Ans. Multi-threading is a programming technique that allows a computer's CPU to execute multiple
threads or tasks concurrently, sharing the same resources and running in parallel. This approach
offers several advantages in software development and system performance:
i. Improved Performance: One of the most significant advantages of multi-threading is improved
performance. By splitting a program into multiple threads that can run concurrently, you can
fully utilize the CPU's processing power. This leads to faster execution times and more efficient
resource utilization.
ii. Parallelism: Multi-threading enables parallelism, where multiple tasks are executed
simultaneously. This is particularly beneficial for computationally intensive or time-consuming
operations, such as data processing, rendering, and simulations.
iii. Responsiveness: In graphical user interfaces (GUIs) and interactive applications, multi-threading
can help maintain responsiveness. By running time-consuming tasks in separate threads, the
main UI thread remains responsive to user input, providing a smoother user experience.
iv. Concurrency: Multi-threading allows for concurrency, enabling different parts of a program to
make progress independently. This is valuable in scenarios where multiple tasks need to run
concurrently, such as in server applications handling multiple client requests.
v. Resource Sharing: Threads within the same process share memory and resources, reducing the
overhead of inter-process communication (IPC). This simplifies data sharing and communication
between different parts of an application.

3. Checked and Unchecked exceptions.


Ans. In Java, exceptions are categorized into two main types: checked exceptions and unchecked
exceptions (also known as runtime exceptions). These categories determine how the compiler and the
runtime environment handle them.
i. Checked Exceptions:
- Definition: Checked exceptions are exceptions that the Java compiler requires you to handle
explicitly. These exceptions are typically caused by external factors outside the control of the program,
such as I/O errors, network issues, or database problems.
- Handling: You must either catch and handle checked exceptions using a `try-catch` block or declare
that your method throws the exception using the `throws` keyword. Failure to handle or declare
these exceptions results in a compilation error.
- Examples: `IOException`, `FileNotFoundException`, `SQLException`.
try {
// Code that may throw a checked exception
} catch (IOException e) {
// Handle the exception
}
ii. Unchecked Exceptions (Runtime Exceptions):
- Definition: Unchecked exceptions, also known as runtime exceptions, are exceptions that the Java
compiler does not require you to handle explicitly. These exceptions typically result from
programming errors, such as dividing by zero, accessing an array index out of bounds, or calling a
method on a null object.
- Handling: While you can handle unchecked exceptions with a `try-catch` block, you are not required
to do so. You can let them propagate up the call stack. Unchecked exceptions are typically not
explicitly declared in method signatures.
- Examples: `NullPointerException`, `ArithmeticException`, `ArrayIndexOutOfBoundsException`.
// Unchecked exception handling (optional)
try {
// Code that may throw an unchecked exception
} catch (NullPointerException e) {
// Handle the exception (optional)
}
CORE JAVA

UNIT - V

1. Event Handling in Java.


Ans. Event handling in Java is a fundamental mechanism that allows developers to create interactive
and responsive applications by responding to user-generated events. These events can originate from
various sources, including graphical user interface (GUI) components like buttons, text fields, and
windows, as well as input devices such as the mouse and keyboard.
Here are five key points about event handling in Java:
i. Event Sources: Event sources are objects or components that generate events. They include GUI
components like buttons, text fields, and windows, as well as input devices such as the mouse
and keyboard.
ii. Event Listeners: Event listeners are specialized objects that listen for and respond to specific
types of events. Java defines various event listener interfaces, such as ActionListener and
MouseListener, each tailored to handle particular event types.
iii. Event Registration: To enable event handling, you must register event listeners with event
sources. This registration is typically done using methods like addActionListener() for buttons or
addMouseListener() for mouse events.
iv. Event Handling Methods: Event listeners implement methods associated with the event type
they handle. For instance, an ActionListener must implement the actionPerformed() method to
respond to button clicks. These methods contain the code that executes when an event occurs.
v. Event Types: Java supports a wide range of event types, each corresponding to specific user
actions or system events. Common event types include ActionEvent (e.g., button clicks),
MouseEvent (e.g., mouse movements and clicks), KeyEvent (e.g., key presses), and
WindowEvent (e.g., window opening and closing).

2. Choice class and List class.


Ans. In Java, the `Choice` and `List` classes are both used for creating user interface components to
present a list of selectable items. However, they have different implementations and use cases:
i. Choice Class:
- The Choice class is part of the AWT (Abstract Window Toolkit) library, which is Java's older
graphical user interface (GUI) framework. It is primarily used for creating simple drop-down lists or
combo boxes where users can select one item from a list of options.
- Choice components are limited in terms of customization and functionality compared to more
modern GUI libraries like Swing or JavaFX.
- Example:
import java.awt.*;
public class ChoiceExample {
public static void main(String[] args) {
Frame frame = new Frame("Choice Example");
Choice choice = new Choice();

choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");

frame.add(choice);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
ii. List Class:
- The List class is also part of the AWT library, but it is used for creating list boxes, which allow users
to select one or more items from a list of options.
- Unlike Choice, `List` components allow multiple selections. You can specify the number of visible
items and whether the user can select one or multiple items.
CORE JAVA

- Example:
import java.awt.*;
public class ListExample {
public static void main(String[] args) {
Frame frame = new Frame("List Example");
List list = new List(3, true); // Allow multiple selections with 3 visible rows

list.add("Option 1");
list.add("Option 2");
list.add("Option 3");
list.add("Option 4");
list.add("Option 5");

frame.add(list);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

3. Use of adapter class in Java.


Ans. Adapter classes in Java simplify the implementation of interfaces or abstract classes by providing
default method implementations. They are particularly useful when you don't need to provide a
complete implementation for all the methods of an interface or abstract class. Here's an example of
how adapter classes can be used in Java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseAdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Adapter Example");
frame.setSize(300, 200);

JButton button = new JButton("Click Me");

// Use MouseAdapter to handle mouseClicked event


button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null, "Button clicked!");
}
});

frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
By using the MouseAdapter class, we streamline our code and make it more concise and readable
while still achieving the desired functionality. This is a practical example of how adapter classes
simplify interface implementation in Java.

You might also like