0% found this document useful (0 votes)
4 views14 pages

Q1

The document provides a comprehensive overview of Java programming concepts, including the structure of a Java program, the use of the 'this' keyword, data types, interfaces, exception handling, and streams. It also includes detailed explanations of method overloading and overriding, the differences between interfaces and abstract classes, and features of the Java Collections Framework. Additionally, the document contains Java code examples for various tasks such as calculating areas, searching names in an array, and copying non-numeric data from one file to another.

Uploaded by

sagarthube
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)
4 views14 pages

Q1

The document provides a comprehensive overview of Java programming concepts, including the structure of a Java program, the use of the 'this' keyword, data types, interfaces, exception handling, and streams. It also includes detailed explanations of method overloading and overriding, the differences between interfaces and abstract classes, and features of the Java Collections Framework. Additionally, the document contains Java code examples for various tasks such as calculating areas, searching names in an array, and copying non-numeric data from one file to another.

Uploaded by

sagarthube
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/ 14

Q.1) Answer the following questions?

a. What is a java program structure?

→1. Package declaration (optional). 2. Import statements.

3. Class definition. 4. Main method. 5. Statements within methods.

b. define this Keyword?

→In Java, `this` refers to the current object. It is used to access instance variables, methods, or
constructors of the same class, avoiding naming conflicts.

c. Explain in details datatypes in java?

→ Java has two types of data types: 1. Primitive:

- byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes): Store integers.

- float (4 bytes), double (8 bytes): Store decimals.

- char (2 bytes): Stores characters.

- boolean (1 bit): Stores true/false.

2. Non-Primitive:

- Includes classes, arrays, interfaces, and strings for storing objects.

d. what is an interface?

→ An interface in Java is a blueprint of a class. It contains abstract methods (no body) and constants.
Classes implement interfaces to achieve abstraction and multiple inheritance.

e. what is the use of readers and writers class?

→ The Readers & Writers classes in Java are used for handling character-based input and output,
supporting Unicode characters, and simplifying file and stream operations.

f. which method is used to specify containers layout with syntax?

→ The method used to specify a container's layout in Java is setLayout(LayoutManager obj).

Syntax: container.setLayout(new LayoutManager());

g. what is the default layout for frame and panel?

→ The default layout for:

• Frame: BorderLayout.

• Panel: FlowLayout.

h. explain modifiers and access controls used in java?


→ In Java, modifiers and access control determine the visibility and behavior of classes, methods,
and variables.

Access Modifiers: Public,Private,Protected,default

Non-Access Modifiers: Static,final,abstract,synchronized,transient,volatile

i)List & Explain any two in built exceptions?

→ ArithmeticException: Thrown when an illegal arithmetic operation, like division by zero, occurs.

NullPointerException: Thrown when trying to access or modify an object reference that is null.

j)Explain the purpose of getContentPanel().

→ The getContentPane() method in Java is used to retrieve the content pane of a JFrame (or other
container). It allows you to add components (like buttons, labels, etc.) to the main window, as the
content pane is where the components are placed.

Q.2)Attempt any four of the following?

1)Explain in details the features of java?

→ Java is a versatile, object-oriented, and platform-independent programming language. Key


features include:

1. Simple: Easy to learn and use with a clear syntax.

2. Object-Oriented: Supports encapsulation, inheritance, and polymorphism.

3. Platform-Independent: Java code runs on any device with a Java Virtual Machine (JVM).

4. Multithreaded: Supports concurrent execution of programs using multiple threads.

5. Secure: Built-in security features like bytecode verification and sandboxing.

6. Robust: Strong memory management, exception handling, and garbage collection.

7. Distributed: Facilitates building networked applications with support for RMI and sockets.

2)what are the rules for method overloading and method overriding?

→ Rules for Method Overloading:

1. Same method name: Overloaded methods must have the same name.

2. Different parameter list: The methods must differ in the number or type of parameters.

3. Return type: Return type can be different, but it alone cannot distinguish overloaded
methods.

4. Same scope: Overloading occurs within the same class or subclass.


Rules for Method Overriding:

1. Same method signature: The method in the subclass must have the same name, return
type, and parameters.

2. Inheritance: The method must be inherited from the superclass.

3. Access level: The overridden method cannot have a more restrictive access modifier than
the original method (e.g., a public method cannot be overridden as private).

4. Use of @Override annotation (optional but recommended): To ensure the method is


correctly overridden.

3)differentiate between interface and abstract class?

→Interface vs. Abstract Class

1. Methods:

o Interface: Can only have abstract methods (until Java 8, which added default and
static methods).

o Abstract Class: Can have both abstract methods (without implementation) and
concrete methods (with implementation).

2. Multiple Inheritance:

o Interface: Supports multiple inheritance, a class can implement multiple interfaces.

o Abstract Class: A class can inherit only one abstract class due to single inheritance.

3. Constructors:

o Interface: Cannot have constructors.

o Abstract Class: Can have constructors.

4. Access Modifiers:

o Interface: All methods are implicitly public, and variables are public static final by
default.

o Abstract Class: Can have methods with various access modifiers (private, protected,
public).

5. Fields:

o Interface: Can only have constants (static final variables).

o Abstract Class: Can have instance variables and static variables.

6. Purpose:
o Interface: Used to represent a contract for what a class can do, without specifying
how.

o Abstract Class: Used when classes share common functionality but also have
different implementations.

4) explain the concept of exception and exception handling?

→Exception:

An exception is an event that disrupts the normal flow of the program's execution. It occurs
during runtime and can be caused by errors such as division by zero, file not found, or invalid
input. Exceptions are objects that represent error conditions.

Exception Handling:

Exception handling in Java allows you to manage runtime errors in a controlled way using
try, catch, throw, throws, and finally blocks. This helps maintain program flow even when
unexpected situations occur:

1. try block: Contains the code that might throw an exception.

2. catch block: Handles the exception if it occurs.

3. throw: Used to explicitly throw an exception.

4. throws: Declares an exception that might be thrown by a method.

5. finally block: Executes code after try-catch, regardless of whether an exception occurred.

This mechanism ensures that errors are handled gracefully without crashing the application.

5)what are the different types of streams? explain in details?

→ In Java, streams are used for input and output (I/O) operations. They allow you to read from and
write to various data sources like files, memory, or network connections. Streams are broadly
classified into two categories: byte streams and character streams.

1. Byte Streams:

Byte streams are used to handle I/O of raw binary data. They read and write data in the form of
bytes, which is ideal for handling all kinds of I/O, including image files, audio files, and other binary
files.

• InputStream: The superclass for all byte input streams.

o FileInputStream: Reads bytes from a file.

o BufferedInputStream: Reads bytes from a stream in a buffered manner, improving


performance.

o DataInputStream: Reads primitive data types (e.g., int, float) in binary form.
• OutputStream: The superclass for all byte output streams.

o FileOutputStream: Writes bytes to a file.

o BufferedOutputStream: Writes bytes to a stream in a buffered manner, improving


performance.

o DataOutputStream: Writes primitive data types in binary format.

2. Character Streams:

Character streams are used for I/O operations involving text data. They handle characters and are
capable of reading and writing Unicode characters, making them suitable for text files.

• Reader: The superclass for all character input streams.

o FileReader: Reads characters from a file.

o BufferedReader: Reads text from a character stream in a buffered manner,


improving performance.

o InputStreamReader: Converts byte streams into character streams.

• Writer: The superclass for all character output streams.

o FileWriter: Writes characters to a file.

o BufferedWriter: Writes text to a character stream in a buffered manner.

o PrintWriter: Writes formatted text to a stream.

3. Specialized Streams:

• Object Streams: These are used to serialize and deserialize objects.

o ObjectInputStream: Reads objects from a stream.

o ObjectOutputStream: Writes objects to a stream.

6) Write a java program to display alternate character from a given string.

→ import java.util.Scanner;
class Slip4A {
public static void main(String args[]){
Scanner scan=new Scanner(System.in);

try {
System.out.print("Enter String : ");
String str = scan.nextLine();
for(int i=0;i<str.length();i+=2) {
System.out.print(" " + str.charAt(i));
}
} catch (Exception e) {}
}
}

#Enter string: Coding activity

cdn ciiy

7)write a java program to calculate the area of circle,triangle and rectangle(use method
overloading).

→public class AreaCalculator {

public double calculateArea(double radius) {

return Math.PI * radius * radius; // Formula: π * r^2

public double calculateArea(double length, double width) {

return length * width; // Formula: length * width

public double calculateArea(double base, double height) {

return 0.5 * base * height; // Formula: 0.5 * base * height

public static void main(String[] args) {

AreaCalculator calculator = new AreaCalculator();

double circleArea = calculator.calculateArea(7.0);

System.out.println("Area of Circle: " + circleArea);

double rectangleArea = calculator.calculateArea(5.0, 4.0);

System.out.println("Area of Rectangle: " + rectangleArea);

double triangleArea = calculator.calculateArea(6.0, 3.0);

System.out.println("Area of Triangle: " + triangleArea);

}
Output:

Area of Circle: 153.93804002589985

Area of Rectangle: 20.0

Area of Triangle: 9.0

9)write a java program to search a give name in an array and if it is found then display its index
otherwise display appropriate message.

→import java.util.Scanner;

public class NameSearch {

public static void main(String[] args) {

String[] names = {"John", "Alice", "Bob", "Eve", "Charlie"};

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the name to search: ");

String nameToSearch = scanner.nextLine();

int index = searchName(names, nameToSearch);

if (index != -1) {

System.out.println("Name '" + nameToSearch + "' found at index: " + index);

} else {

System.out.println("Name '" + nameToSearch + "' not found in the array.");

scanner.close();

public static int searchName(String[] names, String nameToSearch) {

for (int i = 0; i < names.length; i++) {

if (names[i].equalsIgnoreCase(nameToSearch)) {

return i; // Return the index if name is found

}
return -1; // Return -1 if name is not found

Output:

Enter the name to search: Alice

Name 'Alice' found at index: 1

Enter the name to search: David

Name 'David' not found in the array

9)write a java program to display ASCII value of the characters from a file?

→import java.io.FileReader;

import java.io.IOException;

public class AsciiValueFromFile {

public static void main(String[] args) {

String fileName = "sample.txt";

try (FileReader fileReader = new FileReader(fileName)) {

int character;

while ((character = fileReader.read()) != -1) {

System.out.println("Character: " + (char) character + " | ASCII Value: " + character);

} catch (IOException e) {

System.out.println("Error reading the file: " + e.getMessage());

Output: Hello

Character: H | ASCII Value: 72

Character: e | ASCII Value: 101


Character: l | ASCII Value: 108

Character: l | ASCII Value: 108

Character: o | ASCII Value: 111

10)write a java program to display multiplication table of a given number into the list box by
clicking button?

→import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MultiplicationTableApp {

public static void main(String[] args) {

JFrame frame = new JFrame("Multiplication Table");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300, 300);

frame.setLayout(new FlowLayout());

JLabel label = new JLabel("Enter a number:");

JTextField textField = new JTextField(10);

JButton button = new JButton("Generate Table");

DefaultListModel<String> listModel = new DefaultListModel<>();

JList<String> listBox = new JList<>(listModel);

frame.add(label);

frame.add(textField);

frame.add(button);

frame.add(new JScrollPane(listBox));

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

listModel.clear();
try {

int number = Integer.parseInt(textField.getText());

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

listModel.addElement(number + " x " + i + " = " + (number * i));

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(frame, "Please enter a valid number.", "Error",


JOptionPane.ERROR_MESSAGE);

});

frame.setVisible(true);

11)what is collection?explain collection framework in details?

→ A Collection in Java is an object that holds a group of elements. It provides methods for storing,
accessing, manipulating, and processing data, and includes interfaces like List, Set, and Map.

The Java Collections Framework provides a set of interfaces, classes, and algorithms for managing
data. It includes interfaces like Collection, List, Set, Queue, and Map, with implementations such
as ArrayList, HashSet, and HashMap. Collections allow efficient data storage and manipulation,
supporting operations like insertion, deletion, sorting, and searching. Utility classes like Collections
offer sorting and shuffling methods. The framework simplifies data handling by offering flexible,
reusable components for various data structures and algorithms in Java.

12)difference between Swing & AWT ?

→ AWT:

1. Uses heavyweight components that rely on native system resources.

2. Platform-dependent, leading to inconsistent appearances across platforms.

3. Provides basic GUI components like buttons, labels, and text fields.

4. Simpler and faster for basic GUI development.

5. Limited in terms of customization and advanced features.


Swing:

1. Uses lightweight components that are drawn entirely in Java.

2. Platform-independent, ensuring consistent appearance across platforms.

3. Offers advanced components like tables, trees, and rich text areas.

4. More flexible and customizable, supporting various look-and-feel options.

5. Fully supports drag-and-drop functionality and more complex event handling.

13)write a java program to generate ‘n’ terms of above series?

→ import java.util.Scanner;

public class ArmstrongNumber{

public static boolean isArmstrong(int num){

int originalNum = num,sum = 0,digits = String.valueOf(num).length();

while(num != 0){

int digit = num % 10;

sum += Math.pow(digit, digits);

num /= 10;

return sum == originalNum;

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

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

int number = sc.nextInt();

if(isArmstrong(number)){

System.out.println(number + " is an Armstrong number.");

}else{

System.out.println(number + " is not an Armstrong number.");

}
sc.close();

Output: 153 is an Armstrong number.

14)write a java program to copy only non-numeric data from one file to another file?

→ Here is the Java program without comments and unnecessary spaces:

```java

import java.io.*;

public class CopyNonNumericData{

public static void main(String[] args){

try{

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

String line;

while((line = reader.readLine()) != null){

StringBuilder nonNumericData = new StringBuilder();

for(char c : line.toCharArray()){

if(!Character.isDigit(c)){

nonNumericData.append(c);

writer.write(nonNumericData.toString());

writer.newLine();

reader.close();

writer.close();
System.out.println("Non-numeric data copied successfully!");

}catch(IOException e){

System.out.println("Error: " + e.getMessage());

Q.3)Write short notes?

1)define new operator?

→ The new operator in Java is used to create new objects or instances of classes. It dynamically
allocates memory for the object and returns a reference to that memory location. This operator is
essential for instantiating classes, arrays, and other data structures. When you use new, it calls the
constructor of the class, initializing the object. For example, MyClass obj = new MyClass(); creates
a new object of MyClass. The new operator is crucial for object-oriented programming in Java.

2)define term finalize() method.

→ The finalize() method in Java is a method of the Object class that is called by the garbage
collector before an object is destroyed. It allows an object to clean up resources like closing files or
releasing memory before it is reclaimed. The finalize() method is invoked automatically by the
garbage collector, but it can be overridden to provide custom cleanup logic. However, its use is
discouraged in modern Java development, as it can introduce unpredictability and performance
issues.

Example: protected void finalize() throws Throwable {

// Cleanup code here

super.finalize();

3)define package with all steps for package creation?

→ steps for creating a package in Java:

1. Declare the Package: Use package keyword at the top of the Java file.

Example: package mypackage;

2. Create Classes/Interfaces: Write your classes or interfaces inside the package

3. Save the File: Save the file in a folder that matches the package name (e.g.,
mypackage/MyClass.java).
4. Compile the Code: Use javac to compile the Java file.

Example: javac mypackage/MyClass.java

5. Import and Use: In other classes, use `import` to access the package's content.

You might also like