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

Java Programming Concepts and Examples

The document provides a comprehensive overview of Java programming concepts, including the Java Development Kit (JDK), static keyword, classpath, collections framework, and exception handling. It includes Java programs demonstrating perfect numbers, area calculations using method overloading, and file character counting. Additionally, it discusses applets, data types, and package creation in Java.

Uploaded by

tanvipasalkar92
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)
13 views14 pages

Java Programming Concepts and Examples

The document provides a comprehensive overview of Java programming concepts, including the Java Development Kit (JDK), static keyword, classpath, collections framework, and exception handling. It includes Java programs demonstrating perfect numbers, area calculations using method overloading, and file character counting. Additionally, it discusses applets, data types, and package creation in Java.

Uploaded by

tanvipasalkar92
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

Q1: Attempt Any Eight

a) What is JDK? How to build and run a Java program?

JDK stands for Java Development Kit, which is a software environment that includes tools,
libraries, and the Java Runtime Environment (JRE) required for developing and running Java
applications. To build a program, save code in a .java file, compile it using javac [Link],
and run it with the java classname command.

b) Explain Static keyword.

The static keyword in Java is used for memory management. It allows fields, methods, blocks,
and nested classes to belong to the class rather than to an instance, enabling them to be
accessed without creating an object of the class.

c) What is the use of classpath?

Classpath is an environment variable that tells the Java Virtual Machine and Java compiler
where to find user-defined classes and packages. It is essential for locating required classes
during both compilation and execution.

d) What is a collection? Explain the collection framework in detail.

A collection in Java is an object that can store a group of elements. The Collection Framework is
a set of classes and interfaces that implement commonly reusable collection data structures
such as lists, sets, and maps, providing algorithms for searching, sorting, and manipulating data.

e) What is the use of Reader and Writer classes?

Reader and Writer classes in Java are part of the [Link] package, used for input and output of
character streams. Reader is used for reading characters, while Writer is used for writing
characters, supporting internationalization by handling Unicode data.

f) What is the use of layout manager?

A layout manager in Java controls the way GUI components are arranged in a container. It
determines the size, position, and arrangement of components in graphical user interfaces,
allowing flexible and automated layouts.

g) What is the difference between paint( ) and repaint( )?

The paint() method is called by the system or explicitly to render a component.


The repaint() method, when called, schedules a call to paint() but does not itself perform
drawing; it signals the GUI system to refresh the component.

h) Explain access modifiers used in Java.


Access modifiers in Java define the visibility of classes, methods, and variables. public allows
access from any class, private restricts access to within the class, protected permits access
within the package and subclasses, and default (no modifier) allows access only within the
package.

i) Define keyword throw.

The throw keyword is used in Java to explicitly throw an exception, either predefined or custom,
for handling errors during program execution.

j) Define polymorphism.

Polymorphism is an OOP principle where a single interface can represent different underlying
forms (data types). In Java, it allows objects to be accessed through references of parent classes,
supporting method overriding and dynamic method dispatch.

Q2: Attempt Any Four

a) Explain features of Java.

Java features include platform independence, object-oriented design, robustness, security,


portability, high performance, multithreading, and automatic memory management via garbage
collection.

b) What is the difference between constructor and method? Explain types of constructors.

Constructors initialize objects and share the class name, do not have a return type, and are
called once when an object is created. Methods perform operations, have a return type, and
may be called multiple times. Types of constructors are default (no parameters) and
parameterized (with parameters).

c) Differentiate between interface and abstract class.

Aspect Interface Abstract Class

Only abstract methods (Java 7); Java 8+ allows Can have abstract or concrete
Methods default/static methods methods

Variables Public, static, final Non-final, instance/static


Aspect Interface Abstract Class

Inheritance Multiple interfaces possible Only single inheritance

Constructor None Can have constructor

d) Explain the concept of exception and exception handling.

An exception is an event that disrupts normal execution flow. Exception handling in Java
uses try, catch, throw, throws and finally to catch, manage, and recover from runtime errors
gracefully.

e) Explain try and catch with example.

The try block encloses code that may throw exceptions. The catch block handles the exception
type. Example:

java

try {

int x = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Division by zero not allowed");

Q3: Attempt Any Four

a) Java program to display all the perfect numbers between 1 to n

java

import [Link];

public class PerfectNumbers {

public static boolean isPerfect(int num) {

int sum = 0;

for (int i = 1; i <= num / 2; i++) {


if (num % i == 0) {

sum += i;

return sum == num;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter the upper limit n: ");

int n = [Link]();

[Link]("Perfect numbers between 1 and " + n + " are:");

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

if (isPerfect(i)) {

[Link](i);

[Link]();

b) Java program to calculate area of circle, triangle, and rectangle using method overloading

java

public class AreaCalculator {

// Area of circle

public double area(double radius) {

return 3.14159 * radius * radius;


}

// Area of triangle

public double area(double base, double height) {

return 0.5 * base * height;

// Area of rectangle

public double area(double length, double breadth, String shape) {

return length * breadth;

public static void main(String[] args) {

AreaCalculator ac = new AreaCalculator();

[Link]("Area of Circle: " + [Link](7));

[Link]("Area of Triangle: " + [Link](5, 10));

[Link]("Area of Rectangle: " + [Link](4, 7, "rectangle"));

c) Java program to accept n integers, store in ArrayList, and display elements in reverse order

java

import [Link];

import [Link];

public class ReverseArrayList {

public static void main(String[] args) {


ArrayList<Integer> list = new ArrayList<>();

Scanner sc = new Scanner([Link]);

[Link]("Enter number of integers: ");

int n = [Link]();

[Link]("Enter " + n + " integers:");

for (int i = 0; i < n; i++) {

[Link]([Link]());

[Link]("Elements in reverse order:");

for (int i = [Link]() - 1; i >= 0; i--) {

[Link]([Link](i));

[Link]();

d) Java program to count number of digits, spaces, and characters from a file

java

import [Link];

import [Link];

public class FileCharacterCount {

public static void main(String[] args) throws IOException {

FileReader fr = new FileReader("[Link]");

int ch;

int digits = 0, spaces = 0, letters = 0;


while ((ch = [Link]()) != -1) {

char c = (char) ch;

if ([Link](c)) digits++;

else if ([Link](c)) spaces++;

else if ([Link](c)) letters++;

[Link]();

[Link]("Digits: " + digits);

[Link]("Spaces: " + spaces);

[Link]("Letters: " + letters);

e) Applet to display x and y position of cursor movement using mouse and keyboard listeners

java

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class CursorPositionApplet extends Applet implements MouseMotionListener,


KeyListener {

int x = 0, y = 0;

String keyInfo = "";


public void init() {

addMouseMotionListener(this);

addKeyListener(this);

setFocusable(true);

public void mouseMoved(MouseEvent e) {

x = [Link]();

y = [Link]();

repaint();

public void mouseDragged(MouseEvent e) {}

public void keyPressed(KeyEvent e) {

keyInfo = "Key Pressed: " + [Link]();

repaint();

public void keyReleased(KeyEvent e) {}

public void keyTyped(KeyEvent e) {}

public void paint(Graphics g) {

[Link]("Mouse Position: (" + x + "," + y + ")", 20, 20);

[Link](keyInfo, 20, 40);


}

Q4: Attempt Any Four

a) How a Java program is structured? Explain data types.

A Java program is structured into classes containing methods. The entry point is
the main() method. Java defines primitive data types such
as int, byte, short, long, float, double, char, and boolean for storing single values of different
types. It also supports reference data types for objects.

b) What is applet? Explain its types.

An applet is a small Java program that runs within a web browser or applet viewer. Types
include:

• Standalone applet: Runs within the browser.

• Application applet: Runs as a standalone Java application.

• Socket applet: Uses network sockets to communicate.

c) Java program to count number of lines, words, and characters from a given file

java

import [Link];

import [Link];

import [Link];

public class FileStats {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new FileReader("[Link]"));

String line;

int lines = 0, words = 0, chars = 0;


while ((line = [Link]()) != null) {

lines++;

chars += [Link]();

String[] wordList = [Link]("\\s+");

words += [Link];

[Link]();

[Link]("Lines: " + lines);

[Link]("Words: " + words);

[Link]("Characters: " + chars);

d) Java program to design email registration form (swing components)

java

import [Link].*;

import [Link].*;

import [Link].*;

public class EmailRegistrationForm extends JFrame {

private JTextField emailField;

private JButton submitButton;

private JLabel messageLabel;

public EmailRegistrationForm() {

setTitle("Email Registration");
setSize(300, 150);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

add(new JLabel("Email:"));

emailField = new JTextField(20);

add(emailField);

submitButton = new JButton("Submit");

add(submitButton);

messageLabel = new JLabel();

add(messageLabel);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

String email = [Link]();

if ([Link]("@")) {

[Link]("Email Registered");

} else {

[Link]("Invalid Email");

});

}
public static void main(String[] args) {

new EmailRegistrationForm().setVisible(true);

e) Class Teacher and program to accept 'n' teachers and display those teaching Java using
array of objects

java

import [Link];

class Teacher {

int Tid;

String Tname;

String Designation;

double Salary;

String Subject;

Teacher(int Tid, String Tname, String Designation, double Salary, String Subject) {

[Link] = Tid;

[Link] = Tname;

[Link] = Designation;

[Link] = Salary;

[Link] = Subject;

public class TeacherArray {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of teachers: ");

int n = [Link]();

[Link](); // consume newline

Teacher[] teachers = new Teacher[n];

for (int i = 0; i < n; i++) {

[Link]("Teacher " + (i+1) + " details:");

[Link]("ID: ");

int id = [Link]();

[Link]();

[Link]("Name: ");

String name = [Link]();

[Link]("Designation: ");

String desig = [Link]();

[Link]("Salary: ");

double sal = [Link]();

[Link]();

[Link]("Subject: ");

String subj = [Link]();

teachers[i] = new Teacher(id, name, desig, sal, subj);

[Link]("\nTeachers teaching Java:");


for (Teacher t : teachers) {

if ([Link]("Java")) {

[Link]("ID: " + [Link] + ", Name: " + [Link]);

[Link]();

Q5: Write short notes (any two)

a) Define object.

An object in Java is an instance of a class containing state (fields) and behavior (methods). It
represents an entity with identity, attributes, and capabilities.

b) Define term finally block.

The finally block in Java is used to execute important code such as closing resources (files,
connections) regardless of whether an exception is handled or not. It follows a try-catch block
and always executes.

c) What is package? Write down all steps for package creation.

A package in Java is a namespace that organizes classes and interfaces, preventing naming
conflicts and controlling access. To create a package:

1. Use the package keyword followed by the package name at the top of the Java file.

2. Save the file in the directory structure matching the package name.

3. Compile the file using javac.

4. Use import to use the package classes in other files.

Common questions

Powered by AI

The 'classpath' in Java is an environment variable that specifies the location of user-defined classes and packages required by the Java Virtual Machine (JVM) and the Java compiler at both compilation and runtime. It tells the Java environment where to find the class files to load them into the program. During compilation, the classpath can be adjusted to ensure that all necessary dependencies and libraries are correctly referenced to avoid compilation errors due to missing classes. Similarly, at runtime, the JVM uses the classpath to locate the classes that need to be executed, ensuring that the program has access to all the required resources. Proper configuration of the classpath is crucial for the successful compilation and execution of Java programs, especially when dealing with external libraries or complex projects .

Reader and Writer classes in Java, found in the java.io package, are designed for handling input and output of character streams respectively. Unlike byte streams, which handle raw bytes, these classes provide methods for reading and writing Unicode characters, which is essential for internationalization. By abstracting character data handling, they ensure that text-related I/O processes are consistent across different locales and languages. This makes it possible to read and write text files in a manner that respects diverse character sets, including complex scripts used in various world languages, thus facilitating globalization by allowing Java applications to handle multiple cultural and linguistic environments seamlessly .

The Java Collection Framework is a comprehensive set of interfaces and classes that provide a standardized way to manage and manipulate groups of objects, known as collections. This framework supports data structures like lists, sets, and maps, each providing different functionalities to suit various needs, such as search, insertion, deletion, and iteration. The collection classes like ArrayList, HashSet, and HashMap allow for dynamic data structures capable of growing and shrinking as needed, unlike arrays. The framework's significance lies in its provision of high-level methods and algorithms, like sorting and searching, abstracting the complexities involved with data operations. It streamlines the way developers work with data structures, making Java-based applications more robust and efficient in handling large, diverse datasets .

A Java program is typically structured with classes containing methods. The execution entry point is the main() method. Java supports two types of data: primitive and reference data types. Primitive types include int, byte, short, long, float, double, char, and boolean. These types are predefined by Java and named by a reserved keyword. They represent single data values and occupy a specific amount of memory. Reference data types, by contrast, refer to objects, and any variable that is declared in this way is essentially holding a pointer to the memory location where the data is stored. This structure allows Java to be flexible and robust, providing both efficient handling of simple data and complex data structures .

Exceptions in Java represent conditions that occur during the execution of a program, disrupting the normal flow of instructions. Java uses a robust mechanism for handling exceptions, involving the use of try, catch, throw, throws, and finally blocks. The try block contains code that might throw an exception. If an exception occurs, execution stops and control transfers to the catch block, which must specify the type of exception it can handle. For example, try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Division by zero not allowed"); } demonstrates managing an ArithmeticException by performing a risk-prone operation within the try block and gracefully handling any exceptions using the catch block. This structure supports the creation of stable applications by managing unforeseen errors efficiently .

The 'paint()' method in Java is invoked by the system or programmatically to render a component and its content on the screen. It is responsible for the visual representation of the component and is called with a Graphics object that represents the drawing area. In contrast, 'repaint()' is a method that is called to request that a component be redrawn. When 'repaint()' is invoked, it schedules a call to 'paint()' at the appropriate time without doing the painting itself; this enables the Event Dispatch Thread to manage when the component refresh happens. 'repaint()' ensures that changes to the UI are efficiently queued and handled to update the interface .

Java's robustness and security are bolstered by several key features. Robustness is primarily achieved through Java's strong memory management with garbage collection, which helps manage objects' lifecycles and detect memory leaks. Java also enforces strict compile-time and runtime checking to prevent errors, alongside automatic type checking. Security in Java is largely provided by its design principles, such as lack of pointer arithmetic, which helps prevent memory corruption. The security manager and bytecode verifier play critical roles in enforcing security policies for Java programs, preventing unauthorized operations and code injection attacks. The JVM adds an additional layer by interpreting bytecode and ensuring it doesn't breach security constraints. This combination of features helps Java programs run in various environments safely and reliably .

Constructors and methods in Java both play different roles but are integral to object-oriented programming. Constructors are special blocks of code designed to initialize new objects. They share the class's name, have no explicit return type, and are called automatically when an object is instantiated. There are two types of constructors: default, which takes no parameters, and parameterized, which can take values to initialize an object with specific data. Methods, on the other hand, define operations that can be performed on objects. They have explicitly defined return types and aim to perform tasks or return specific data after being called. While constructors can only be invoked once when an object is created, methods can be called as many times as needed .

The 'static' keyword in Java is used for memory management by allowing fields, methods, blocks, and nested classes to belong to the class rather than to an instance. This means that static members are shared among all instances of a class, which reduces the memory footprint because there is only one copy per class, no matter how many objects exist. Static variables are initialized only once, at the start of the execution. Methods declared as static cannot access non-static data directly. This promotes the efficient use of memory by sharing common methods and variables across instances without redundant copies .

In Java, interfaces and abstract classes serve different purposes and have distinct features. Interfaces can only contain abstract methods (though Java 8 allows default and static methods), whereas abstract classes can have both abstract and concrete methods. Variables in interfaces are implicitly public, static and final, making them constants, while abstract classes can have instance variables with any access modifier. Regarding inheritance, Java allows multiple interfaces to be implemented by a single class, supporting multiple inheritance of type. However, a class can only inherit from one abstract class. Abstract classes can have constructors, which can be used to initialize fields, whereas interfaces cannot have constructors as they cannot dictate instantiation details .

You might also like