0% found this document useful (0 votes)
24 views5 pages

Java Program Examples and Code Snippets

The document contains multiple Java code examples demonstrating various programming concepts such as creating a menu bar, handling user-defined exceptions, type casting, using vectors, action listeners, result sets, constructors, grid layouts, threading, JTree, switch cases, summing digits, and URL handling. Each example is self-contained and illustrates a specific feature or functionality within Java. The code snippets are designed for educational purposes, showcasing fundamental programming techniques.

Uploaded by

sajansteve33
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)
24 views5 pages

Java Program Examples and Code Snippets

The document contains multiple Java code examples demonstrating various programming concepts such as creating a menu bar, handling user-defined exceptions, type casting, using vectors, action listeners, result sets, constructors, grid layouts, threading, JTree, switch cases, summing digits, and URL handling. Each example is self-contained and illustrates a specific feature or functionality within Java. The code snippets are designed for educational purposes, showcasing fundamental programming techniques.

Uploaded by

sajansteve33
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

1.

Menu Bar

import [Link].*;

public class MenuBarExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Menu Bar Example");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem item = new JMenuItem("Open");

[Link](item);
[Link](menu);
[Link](menuBar);

[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

2. User Defined Exception (Age < 18)

class UnderAgeException extends Exception {


UnderAgeException(String message) {
super(message);
}
}

public class AgeCheck {


public static void main(String[] args) {
int age = 16;
try {
if (age < 18)
throw new UnderAgeException("Age is less than 18");
else
[Link]("Eligible");
} catch (UnderAgeException e) {
[Link]([Link]());
}
}
}

3. Type Casting

public class TypeCastingExample {


public static void main(String[] args) {
int a = 10;
double b = a;
double x = 9.5;
int y = (int)x;
[Link]("b = " + b);
[Link]("y = " + y);
}
}

4. Vector Methods

import [Link].*;

public class VectorExample {


public static void main(String[] args) {
Vector<String> v = new Vector<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("B");
[Link](v);
[Link]("Size: " + [Link]());
}
}

5. Action Listener

import [Link].*;
import [Link].*;

public class ButtonClick {


public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Click Me");

[Link](e -> [Link](null, "Button Clicked"));

[Link](button);
[Link](200, 150);
[Link](null);
[Link](50, 50, 100, 30);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

6. ResultSet

import [Link].*;

public class ResultSetExample {


public static void main(String[] args) throws Exception {
Connection con = [Link]("jdbc:mysql://localhost/test", "root",
"pass");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}

[Link]();
}
}

7. Constructor

class Student {
String name;

Student(String n) {
name = n;
}

void show() {
[Link]("Name: " + name);
}

public static void main(String[] args) {


Student s = new Student("John");
[Link]();
}
}

8. Calculator with GridLayout

import [Link].*;
import [Link].*;

public class GridCalculator {


public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
[Link](new GridLayout(4, 4));
String[] buttons = {"1", "2", "3", "+", "4", "5", "6", "-",
"7", "8", "9", "*", "C", "0", "=", "/"};

for (String text : buttons)


[Link](new JButton(text));

[Link](300, 300);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

9. Even & Odd Threads

public class EvenOddThread {


public static void main(String[] args) {
Thread even = new Thread(() -> {
for (int i = 0; i <= 10; i += 2) {
[Link]("Even: " + i);
try { [Link](500); } catch (Exception e) {}
}
});

Thread odd = new Thread(() -> {


for (int i = 1; i <= 10; i += 2) {
[Link]("Odd: " + i);
try { [Link](500); } catch (Exception e) {}
}
});

[Link]();
[Link]();
}
}

10. JTree

import [Link].*;
import [Link];

public class TreeExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTree Example");
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child2");

[Link](child1);
[Link](child2);

JTree tree = new JTree(root);


[Link](tree);
[Link](200, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

11. Switch Case

public class SwitchExample {


public static void main(String[] args) {
int day = 2;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Other day");
}
}
}

12. Sum of Digits

public class SumDigits {


public static void main(String[] args) {
int num = 1234, sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
[Link]("Sum: " + sum);
}
}

13. URL Class

import [Link].*;

public class URLExample {


public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Path: " + [Link]());
}
}

Common questions

Powered by AI

GridLayout in Java Swing provides a consistent and scalable way of arranging components in a grid of uniformly sized cells. This simplifies the creation of GUIs like calculators (as shown in Source 1) and ensures predictable resizing since all components adjust evenly to the container's size. However, a potential drawback is the uniformity constraint, which may lead to wasted space when component sizes vary greatly, lacking flexibility if specific components require non-uniform dimensions .

A Vector is preferred over an ArrayList in Java when thread safety is required, as Vector methods are synchronized and thus inherently thread-safe. This makes Vectors suitable for concurrent modifications without introducing external synchronizations. The example in Source 1 demonstrates basic operations like add, remove, and size on a Vector, highlighting its similarities with ArrayList in usage, but the distinction lies in Vectors’ overhead due to synchronized methods, which impacts performance in non-concurrent scenarios .

The ActionListener interface in Java Swing facilitates user interaction by allowing an object to respond to action events, such as a button being clicked. An object that implements ActionListener must define the actionPerformed method. In the provided example, an ActionListener is added to a JButton using a lambda expression, which executes a message dialogue displaying 'Button Clicked' whenever the button is pressed. This mechanism allows for decoupling of the event handling logic from the UI components themselves, increasing modularity and reuse .

The design principle evident in using DefaultMutableTreeNode for constructing a JTree is encapsulation. Nodes abstract their hierarchical relationships and data storage within a tree structure. This setup allows easy addition, removal, and manipulation of nodes (as seen with 'root.add(child1)') demonstrating composition over inheritance. The encapsulated nature of DefaultMutableTreeNode allows for easy management of tree node children without exposing internal workings, aligning with object-oriented design principles of Java Swing for UI components .

To handle exceptions effectively in a ResourceBundle, potentially for internationalized error messages like those generated by a user-defined exception, you must define a ResourceBundle containing messages for different locales. Override the exception message in the configured locale's properties file with a key matching the exception message. When the UnderAgeException is thrown, the ResourceBundle's getString method retrieves the appropriately localized message. This ensures that the user receives context-sensitive feedback. Although the documented example focuses on a straightforward exception, this approach can be extended for internationalization in production applications .

Type casting in Java involves converting a variable of one primitive data type to another, which can be explicit or implicit. Implicit casting occurs when converting a smaller type (int) to a larger type (double), as seen with 'double b = a;' where integer 'a' is automatically cast to double. Explicit casting requires the programmer's intervention, as in 'int y = (int)x;', converting double to int, potentially leading to a loss of precision since only the integer part is preserved .

In Java Swing, a JMenuBar is instantiated and added to a JFrame using the method setJMenuBar. A JMenu is created and added to the JMenuBar. Within the JMenu, JMenuItems can be added, which can trigger actions when selected. This interaction allows for the creation of a menu system for a GUI that is controlled through the JFrame's lifecycle and visible whenever the frame is displayed .

Efficient thread management in Java applications can use executor services to handle thread lifecycle, task management, or use synchronized blocks or locks to manage data access between threads. In the EvenOddThread program, threads execute independently without shared resource contention, demonstrated by simple threading via the Thread class and lambda expressions. To improve efficiency, consider using a thread pool to reduce overhead associated with thread creation and termination, or the threading API’s concurrent utilities for handling inter-thread communication, such as the TaskExecutor frameworks .

JDBC (Java Database Connectivity) API facilitates database connectivity by establishing a connection using DriverManager and executing SQL queries via a Statement or PreparedStatement. Data retrieval is achieved through a ResultSet, which iterates over each row produced by the query. In the example, a ResultSet is queried to print student details from a database, showing how JDBC allows for generic code to manage database interactions, handle exceptions, and ensure connection closures after operations completion, like the explicit connection close call avoiding resource leaks .

The Switch statement in Java enhances control flow by providing a multi-way branching structure that simplifies the selection among integer-based or enumerated values. The presented example maps integer inputs to string outputs like 'Tuesday' for case 2. Its limitations include lack of support for complex conditions or non-integral types prior to Java 7. Furthermore, forgetting to terminate cases with break can lead to fall-through errors, though these have been partially mitigated with Java 12 introducing expression switches .

You might also like