Core Java Imp
Core Java Imp
1. What is Java?
2. What is an Exception?
Ans: An exception in Java is an event that disrupts the normal flow of a program's
execution. It typically occurs during runtime and can be handled using try-catch blocks
to prevent program crashes.
Multilevel Inheritance
Hierarchical Inheritance
4. What is AWT?
Ans: AWT (Abstract Window Toolkit) is a Java library used for creating graphical user
interfaces (GUI). It contains various classes like Button, Label, and TextField for
developing windows-based applications.
Ans: The throw keyword is used in Java to explicitly throw an exception. For example:
throw new ArithmeticException("Error message");
Ans: An abstract class in Java is a class that cannot be instantiated and may contain
abstract methods (methods without implementation) that subclasses must override. It
can also contain concrete methods.
7. What is an event?
Ans: An event in Java refers to any action or occurrence recognized by software, like
button clicks or mouse movements, which can trigger a specific response within a
program.
Ans: Method overloading occurs when multiple methods in the same class have the
same name but differ in the number or type of their parameters.
Ans: Encapsulation is the concept of bundling data (variables) and methods that
operate on the data within a single unit, typically a class, and restricting access to some
of the object’s components using access specifiers.
Ans: Java is platform-neutral because its compiled bytecode can be executed on any
platform that has a compatible JVM, allowing programs to be written once and run
anywhere.
Ans: Access specifiers define the visibility and accessibility of classes, methods,
and variables. They are:
o public
o private
o protected
Ans: The static keyword in Java is used to define class-level methods or variables that
are shared among all instances of the class. Static members belong to the class itself
rather than any specific object.
Ans: Environment variables such as JAVA_HOME and CLASSPATH are set to configure
the Java Development Kit (JDK) and to specify the path where Java programs and
libraries can be found by the operating system.
class Car {
String model;
void start() {
System.out.println("Car started");
Ans: Swing is a part of Java’s Foundation Classes (JFC) used to create lightweight GUI
applications. It provides more powerful and flexible components than AWT, such as
buttons, panels, and text fields.
Ans: BufferedReader is used to read text from a character-based input stream efficiently.
It buffers input, minimizing the number of I/O operations by reading chunks of data.
Ans: Panel is a container in AWT that can hold multiple components (like buttons and
text fields) and group them together. It is often used for layout purposes in GUI
applications.
21. Define variable in Java? What are the naming rules of variable?
Ans: A variable is a container that holds data that can be changed during the execution
of a program.
Naming rules:
Case-sensitive
Cannot be a keyword.
Ans: Inheritance is a mechanism where a new class (subclass) inherits the properties
and behavior of an existing class (superclass), promoting code reuse and hierarchical
relationships.
Array: Fixed size, can store both primitive data types and objects.
ArrayList: Dynamic size, can only store objects (wrapper classes for primitives).
Ans: An error is a serious problem that occurs during the execution of a program,
usually related to system resources or environment. Types include:
Compile-time errors
Runtime errors
Logical errors
Applets cannot communicate with other servers except the one from which they
were loaded.
Ans: A container is a component that can hold other components, such as panels or
frames, in GUI applications.
Ans: JDK (Java Development Kit) is a software development kit required to develop
Java applications. To build and run a Java program:
Ans: The classpath is an environment variable that tells the Java Virtual Machine (JVM)
where to look for user-defined classes and packages when running Java applications.
Ans: A collection is an object that groups multiple elements into a single unit. Java’s
Collection Framework provides classes like List, Set, and Map for storing and
manipulating data.
Ans: Reader and Writer classes are used for handling character-based input/output
streams in Java. Reader reads characters, while Writer writes characters.
repaint(): Calls the update() method, which in turn calls paint(), used to refresh
the UI.
Ans: Access modifiers control the visibility of class members. They include:
Ans: Polymorphism is the ability of an object to take many forms, mainly through
method overriding (runtime polymorphism) and method overloading (compile-time
polymorphism)
Import statements
Class definition
Methods
Ans: this is a reference variable that points to the current object within a method or
constructor.
Primitive types: byte, short, int, long, float, double, boolean, char
Ans: The default layout for a Frame is BorderLayout, and for a Panel, it is FlowLayout.
Ans: In Swing, getContentPane() is used to retrieve the content pane of a JFrame, where
you can add components like buttons or text fields.
Ans: An interface in Java is a reference type that can contain only abstract methods
(before Java 8) or default methods (Java 8 and later). Classes implement interfaces to
provide specific behaviors.
1. What is Super Keyword? Explain the use of super keyword with suitable
example.
Ans: The super keyword in Java refers to the superclass (parent class) of the current
object. It is used to access superclass methods, constructors, or variables from a
subclass.
Uses of the super keyword:
Access superclass variables when they are hidden by subclass variables.
Invoke superclass methods when overridden by subclass methods.
Invoke superclass constructors from a subclass constructor.
Example:
class Animal {
String name = "Animal";
void display() {
System.out.println("This is an Animal");
}
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println("This is a Dog");
}
void printInfo() {
System.out.println(super.name); // Accessing superclass variable
super.display(); // Calling superclass method
}
}
public class TestSuper {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printInfo();
}
}
5. Why the main() method in public static? Can we overload it? Can we run java class
without main() method?
Ans: The main() method is public and static in Java because:
public: It must be accessible to the JVM, which calls it to start the execution.
static: It can be called without creating an instance of the class.
1. Can we overload main()? Yes, you can overload the main() method by defining
other versions of main() with different parameter lists, but the JVM will always
look for public static void main(String[] args) to start execution.
2. Can we run a Java class without the main() method? In recent versions of Java,
if you have a class that doesn't have a main() method, the JVM will throw a
NoSuchMethodError. However, earlier versions could run via static initialization
blocks.
6. What is recursion is Java? Write a Java Program to final factorial of a given number
using recursion.
Ans: Recursion is a process in which a method calls itself continuously until it reaches a
base condition.
Example: Factorial using Recursion:
class RecursionExample {
static int factorial(int n) {
if (n == 0) { // Base condition
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
15. How to create and access package in Java? Explain it with example.
Ans: A package in Java is used to group related classes and interfaces, providing
modularity and avoiding naming conflicts. It helps in organizing the project and
controlling access to different classes.
Steps to create and access a package:
1. Create a Package: Use the package keyword followed by the package name at
the top of your Java file.
2. Compile the Package: After creating the class inside a package, you need to
compile it using javac with the -d option to specify the destination folder.
3. Import the Package: In other Java classes, you can use the import keyword to
access the classes inside the package.
Example:
Step 1: Create a package java
Copy code
// File: MyPackage/MyClass.java
package MyPackage;
// Single-Dimensional Array
// Accessing elements
// Two-Dimensional Array
int[][] twoDArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
// Jagged Array
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6}
};
// Accessing elements
Q3. Programs.
1. Write a java program which accepts student details (Sid, Sname, Saddr)
from user and display it on next frame. (Use AWT).
Ans: import java.awt.*;
import java.awt.event.*;
public StudentDetails() {
labelSid = new Label("Student ID:");
labelSname = new Label("Student Name:");
labelSaddr = new Label("Student Address:");
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
new DisplayFrame(textSid.getText(), textSname.getText(), textSaddr.getText());
}
Label label = new Label("ID: " + sid + ", Name: " + sname + ", Address: " + saddr);
add(label);
setSize(400, 100);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
}
2. Write a package MCA which has one class student. Accept student
details through parameterized constructor. Write display() method to
display details. Create a main class which will use package and calculate
total marks and percentage.
Ans:
// Package MCA
package MCA;
// Main Class
import MCA.Student;
import java.util.Scanner;
try {
if (input.length() < 5) {
throw new InvalidStringException("Invalid String: Length must be 5 or more.");
}
System.out.println("Uppercase: " + input.toUpperCase());
} catch (InvalidStringException e) {
System.out.println(e.getMessage());
}
}
}
4. Write a Java Program using Applet to create login form.
Ans:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
add(labelUser);
add(textUser);
add(labelPass);
add(textPass);
add(loginButton);
}
// Draw eyes
g.setColor(Color.BLACK);
g.fillOval(75, 80, 10, 10); // Left eye
g.fillOval(115, 80, 10, 10); // Right eye
// Draw mouth
g.drawArc(75, 90, 50, 30, 0, -180); // Smile
}
}
6. Write a java program to copy the dates from one file into another file.
Ans:
import java.io.*;
Collections.reverse(numbers);
System.out.println("Reversed ArrayList: " + numbers);
}
}
8. Write a Java program using AWT to display details of Customer (cust_id,
cust_name, cust_addr) from user and display it on the next frame.
Ans:
import java.awt.*;
import java.awt.event.*;
public CustomerDetails() {
labelCustId = new Label("Customer ID:");
labelCustName = new Label("Customer Name:");
labelCustAddr = new Label("Customer Address:");
setSize(300, 200);
setVisible(true);
}
Label label = new Label("ID: " + custId + ", Name: " + custName + ", Address: " +
custAddr);
add(label);
setSize(400, 100);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
}
9. Write a Java program to reverse elements in array.
Ans:
import java.util.Scanner;
class BankAccount {
static int accountCount = 0;
String accountHolderName;
double balance;
void displayInfo() {
System.out.println("Account Holder: " + accountHolderName + ", Balance: $" +
balance);
}
}
Cone(double r, double h) {
radius = r;
height = h;
}
void area() {
double area = Math.PI * radius * (radius + Math.sqrt(height * height + radius *
radius));
System.out.println("Cone Surface Area: " + area);
}
void volume() {
double volume = (1.0 / 3) * Math.PI * radius * radius * height;
System.out.println("Cone Volume: " + volume);
}
}
Cylinder(double r, double h) {
radius = r;
height = h;
}
void area() {
double area = 2 * Math.PI * radius * (radius + height);
System.out.println("Cylinder Surface Area: " + area);
}
void volume() {
double volume = Math.PI * radius * radius * height;
System.out.println("Cylinder Volume: " + volume);
}
}
// Draw eyes
g.setColor(Color.BLACK);
g.fillOval(75, 80, 10, 10); // Left eye
g.fillOval(115, 80, 10, 10); // Right eye
// Draw mouth
g.drawArc(75, 90, 50, 30, 0, -180); // Smile
}
}
13. Write a Java program to Fibonacci series.
Ans:
import java.util.Scanner;
int a = 0, b = 1, c;
System.out.print("Fibonacci Series: " + a + " " + b);
Collections.reverse(integers);
System.out.println("Reversed ArrayList: " + integers);
}
}
18. Write a Java program to count number of digits, spaces and characters
from a file.
Ans:
import java.io.*;
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Email submitted: " + textEmail.getText());
JOptionPane.showMessageDialog(frame, "Email submitted!");
}
});
frame.add(panel);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
22. Create a class Teacher (Tid, Tname, Designation, Salary, Subject). Write
Ans:
class Teacher {
int Tid;
String Tname;
String Designation;
double Salary;
String Subject;
Teacher(int id, String name, String designation, double salary, String subject) {
this.Tid = id;
this.Tname = name;
this.Designation = designation;
this.Salary = salary;
this.Subject = subject;
}
}
if (index != -1) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found.");
}
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listModel.clear();
int number = Integer.parseInt(textField.getText());
for (int i = 1; i <= 10; i++) {
listModel.addElement(number + " x " + i + " = " + (number * i));
}
}
});
frame.add(panel);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
28. Write a java program to display multiplication table of a given number
into the List box by clicking on button.
Ans:
// Package named Series
package Series;
class Fibonacci {
public void printFibonacci(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series: " + a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
System.out.println();
}
}
class Cube {
public void printCubes(int n) {
System.out.print("Cubes: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i * i + " ");
}
System.out.println();
}
}
class Square {
public void printSquares(int n) {
System.out.print("Squares: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i + " ");
}
System.out.println();
}
}
// Main Class
import Series.*;
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}