Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Programs

The document contains a comprehensive list of 43 Java programs covering various concepts including boilerplate code, authentication, eligibility checks, series generation, inheritance types, layout management in Swing, file operations, threading, and servlet handling. Each program is presented with code snippets demonstrating its functionality. This serves as a practical guide for learning and implementing Java programming techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Programs

The document contains a comprehensive list of 43 Java programs covering various concepts including boilerplate code, authentication, eligibility checks, series generation, inheritance types, layout management in Swing, file operations, threading, and servlet handling. Each program is presented with code snippets demonstrating its functionality. This serves as a practical guide for learning and implementing Java programming techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1. Program to demonstrate Java boilerplate/template.

2. Program to use the authentication method of a class.


3. Program to check if a person is eligible to vote or not.
4. Program to check if a number is divisible by 3, 5, both, or none.
5. Program to print the series: 1, 1, 2, 3, 5, 8... up to the 15th term.
6. Program to print the series: 7, 22, 11, 34, 17... up to the 15th term.
7. Program to print individual digits of a multi-digit number.
8. Program to check if the given number is a palindrome number or not.
9. Program to check if the user input is an Armstrong number or not.
10. Program to demonstrate single inheritance.
11. Program to demonstrate hierarchical inheritance.
12. Program to demonstrate multi-level inheritance.
13. Program to demonstrate multiple inheritance using an interface.
14. Program to demonstrate function overloading.
15. Program demonstrating function overriding.
16. Program demonstrating the use of the super keyword.
17. Program to show the use of JFrame (using an object).
18. Program to depict JFrame using inheritance.
19. Program to display a window in Java.
20. Program using Border Layout.
21. Program showcasing Flow Layout.
22. Program showing Grid Layout.
23. Program depicting Card Layout.
24. Program showing the use of Null Layout.
25. Program showcasing different JComponents available in Swing.
26. Program to demonstrate read/write operations using a byte stream.
27. Program to demonstrate read/write operations using a character stream.
28. Program to read/write a file using random access.
29. Program to demonstrate a thread using the Thread class.
30. Program to demonstrate a thread using the Runnable interface.
31. Program to demonstrate thread synchronization.
32. Program to demonstrate a Servlet using the Servlet interface.
33. Program to create a Servlet using the GenericServlet class.
34. Program to create a Servlet using the HttpServlet class.
35. Program to demonstrate form handling using a Servlet.
36. Program to demonstrate integration of JDBC with a Servlet.
37. Program to demonstrate request and response between two Servlets using
RequestDispatcher.
38. Program to demonstrate request and response between two Servlets using SendRedirect.
39. Program to demonstrate form handling using JSP.
40. Program to demonstrate the use of RMI in Java.
41. Program to demonstrate one-way communication through TCP.
42. Program to demonstrate two-way communication through TCP.
43. Program to demonstrate communication through UDP.

Here are the Java programs for all 43 questions you requested:

Java Boilerplate/Template Program:

1. public class Main {


2. public static void main(String[] args) {
3. System.out.println("Hello, World!");
4. }
5. }
6. Authentication Method in a Class:
7. class User {
8. private String username;
9. private String password;
10.
11. public User(String username, String password) {
12. this.username = username;
13. this.password = password;
14. }
15.
16. public boolean authenticate(String inputUsername, String inputPassword) {
17. return username.equals(inputUsername) && password.equals(inputPassword);
18. }
19.
20. public static void main(String[] args) {
21. User user = new User("admin", "password123");
22. System.out.println(user.authenticate("admin", "password123")); // true
23. }
24. }
25. Eligibility to Vote:
26. import java.util.Scanner;
27.
28. public class VotingEligibility {
29. public static void main(String[] args) {
30. Scanner scanner = new Scanner(System.in);
31. System.out.print("Enter age: ");
32. int age = scanner.nextInt();
33.
34. if (age >= 18) {
35. System.out.println("Eligible to vote.");
36. } else {
37. System.out.println("Not eligible to vote.");
38. }
39. }
40. }
41. Check Divisibility by 3, 5, Both, or None:
42. import java.util.Scanner;
43.
44. public class Divisibility {
45. public static void main(String[] args) {
46. Scanner scanner = new Scanner(System.in);
47. System.out.print("Enter a number: ");
48. int num = scanner.nextInt();
49.
50. if (num % 3 == 0 && num % 5 == 0) {
51. System.out.println("Divisible by both 3 and 5");
52. } else if (num % 3 == 0) {
53. System.out.println("Divisible by 3");
54. } else if (num % 5 == 0) {
55. System.out.println("Divisible by 5");
56. } else {
57. System.out.println("Divisible by neither 3 nor 5");
58. }
59. }
60. }
61. Fibonacci Series up to 15th Term:
62. public class Fibonacci {
63. public static void main(String[] args) {
64. int a = 0, b = 1;
65. System.out.print(a + ", " + b);
66.
67. for (int i = 3; i <= 15; i++) {
68. int next = a + b;
69. System.out.print(", " + next);
70. a = b;
71. b = next;
72. }
73. }
74. }
75. Series: 7, 22, 11, 34, 17...
76. public class Series {
77. public static void main(String[] args) {
78. int num = 7;
79. for (int i = 1; i <= 15; i++) {
80. System.out.print(num + ", ");
81. if (i % 2 != 0) {
82. num = num * 2;
83. } else {
84. num = num / 2;
85. }
86. }
87. }
88. }
89. Print Individual Digits of a Multi-Digit Number:
90. import java.util.Scanner;
91.
92. public class Digits {
93. public static void main(String[] args) {
94. Scanner scanner = new Scanner(System.in);
95. System.out.print("Enter a number: ");
96. int number = scanner.nextInt();
97.
98. while (number > 0) {
99. System.out.println(number % 10);
100. number = number / 10;
101. }
102. }
103. }
104. Palindrome Number Check:
105. import java.util.Scanner;
106.
107. public class Palindrome {
108. public static void main(String[] args) {
109. Scanner scanner = new Scanner(System.in);
110. System.out.print("Enter a number: ");
111. int num = scanner.nextInt();
112. int original = num, reverse = 0;
113.
114. while (num != 0) {
115. reverse = reverse * 10 + num % 10;
116. num = num / 10;
117. }
118.
119. if (original == reverse) {
120. System.out.println("The number is a palindrome.");
121. } else {
122. System.out.println("The number is not a palindrome.");
123. }
124. }
125. }
126. Armstrong Number Check:
127. import java.util.Scanner;
128.
129. public class Armstrong {
130. public static void main(String[] args) {
131. Scanner scanner = new Scanner(System.in);
132. System.out.print("Enter a number: ");
133. int num = scanner.nextInt();
134. int original = num, sum = 0;
135. int digits = (int) Math.log10(num) + 1;
136.
137. while (num != 0) {
138. int digit = num % 10;
139. sum += Math.pow(digit, digits);
140. num = num / 10;
141. }
142.
143. if (original == sum) {
144. System.out.println("The number is an Armstrong number.");
145. } else {
146. System.out.println("The number is not an Armstrong number.");
147. }
148. }
149. }
150. Single Inheritance:
151. class Animal {
152. void sound() {
153. System.out.println("Animal makes sound");
154. }
155. }
156.
157. class Dog extends Animal {
158. void sound() {
159. System.out.println("Dog barks");
160. }
161.
162. public static void main(String[] args) {
163. Dog dog = new Dog();
164. dog.sound(); // Dog barks
165. }
166. }
167. Hierarchical Inheritance:
168. class Animal {
169. void sound() {
170. System.out.println("Animal makes sound");
171. }
172. }
173.
174. class Dog extends Animal {
175. void sound() {
176. System.out.println("Dog barks");
177. }
178. }
179.
180. class Cat extends Animal {
181. void sound() {
182. System.out.println("Cat meows");
183. }
184. }
185.
186. public class Main {
187. public static void main(String[] args) {
188. Dog dog = new Dog();
189. dog.sound();
190. Cat cat = new Cat();
191. cat.sound();
192. }
193. }
194. Multi-Level Inheritance:
195. class Animal {
196. void sound() {
197. System.out.println("Animal makes sound");
198. }
199. }
200.
201. class Dog extends Animal {
202. void sound() {
203. System.out.println("Dog barks");
204. }
205. }
206.
207. class Puppy extends Dog {
208. void sound() {
209. System.out.println("Puppy whines");
210. }
211.
212. public static void main(String[] args) {
213. Puppy puppy = new Puppy();
214. puppy.sound(); // Puppy whines
215. }
216. }
217. Multiple Inheritance using Interface:
218. interface Animal {
219. void sound();
220. }
221.
222. interface Pet {
223. void play();
224. }
225.
226. class Dog implements Animal, Pet {
227. public void sound() {
228. System.out.println("Dog barks");
229. }
230.
231. public void play() {
232. System.out.println("Dog plays");
233. }
234.
235. public static void main(String[] args) {
236. Dog dog = new Dog();
237. dog.sound();
238. dog.play();
239. }
240. }
241. Function Overloading:
242. class Calculator {
243. int add(int a, int b) {
244. return a + b;
245. }
246.
247. double add(double a, double b) {
248. return a + b;
249. }
250.
251. public static void main(String[] args) {
252. Calculator calc = new Calculator();
253. System.out.println(calc.add(5, 10));
254. System.out.println(calc.add(5.5, 10.5));
255. }
256. }
257. Function Overriding:
258. class Animal {
259. void sound() {
260. System.out.println("Animal makes sound");
261. }
262. }
263.
264. class Dog extends Animal {
265. @Override
266. void sound() {
267. System.out.println("Dog barks");
268. }
269.
270. public static void main(String[] args) {
271. Dog dog = new Dog();
272. dog.sound();
273. }
274. }
275. Use of the Super Keyword:
276. class Animal {
277. void sound() {
278. System.out.println("Animal makes sound");
279. }
280. }
281.
282. class Dog extends Animal {
283. void sound() {
284. super.sound(); // Calls Animal's sound method
285. System.out.println("Dog barks");
286. }
287.
288. public static void main(String[] args) {
289. Dog dog = new Dog();
290. dog.sound();
291. }
292. }
293. Use of JFrame (Using Object):
294. import javax.swing.JFrame;
295.
296. public class FrameExample {
297. public static void main(String[] args) {
298. JFrame frame = new JFrame("Simple JFrame");
299. frame.setSize(400, 400);
300. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
301. frame.setVisible(true);
302. }
303. }
304. JFrame Using Inheritance:
305. import javax.swing.*;
306.
307. class CustomFrame extends JFrame {
308. public CustomFrame() {
309. setTitle("Inheriting JFrame");
310. setSize(400, 400);
311. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
312. setVisible(true);
313. }
314. }
315.
316. public class Main {
317. public static void main(String[] args) {
318. new CustomFrame();
319. }
320. }
321. Display a Window in Java:
322. import javax.swing.JFrame;
323.
324. public class WindowExample {
325. public static void main(String[] args) {
326. JFrame window = new JFrame("Window");
327. window.setSize(300, 200);
328. window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
329. window.setVisible(true);
330. }
331. }
332. Border Layout:
333. import javax.swing.*;
334. import java.awt.*;
335.
336. public class BorderLayoutExample {
337. public static void main(String[] args) {
338. JFrame frame = new JFrame("Border Layout Example");
339. frame.setLayout(new BorderLayout());
340. frame.add(new JButton("North"), BorderLayout.NORTH);
341. frame.add(new JButton("South"), BorderLayout.SOUTH);
342. frame.add(new JButton("East"), BorderLayout.EAST);
343. frame.add(new JButton("West"), BorderLayout.WEST);
344. frame.add(new JButton("Center"), BorderLayout.CENTER);
345. frame.setSize(400, 400);
346. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
347. frame.setVisible(true);
348. }
349. }
350. Flow Layout:
351. import javax.swing.*;
352. import java.awt.*;
353.
354. public class FlowLayoutExample {
355. public static void main(String[] args) {
356. JFrame frame = new JFrame("Flow Layout Example");
357. frame.setLayout(new FlowLayout());
358. frame.add(new JButton("Button 1"));
359. frame.add(new JButton("Button 2"));
360. frame.add(new JButton("Button 3"));
361. frame.setSize(300, 200);
362. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
363. frame.setVisible(true);
364. }
365. }
366. Grid Layout:
367. import javax.swing.*;
368. import java.awt.*;
369.
370. public class GridLayoutExample {
371. public static void main(String[] args) {
372. JFrame frame = new JFrame("Grid Layout Example");
373. frame.setLayout(new GridLayout(2, 2)); // 2x2 grid
374. frame.add(new JButton("Button 1"));
375. frame.add(new JButton("Button 2"));
376. frame.add(new JButton("Button 3"));
377. frame.add(new JButton("Button 4"));
378. frame.setSize(300, 200);
379. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
380. frame.setVisible(true);
381. }
382. }
383. Card Layout:
384. import javax.swing.*;
385. import java.awt.*;
386.
387. public class CardLayoutExample {
388. public static void main(String[] args) {
389. JFrame frame = new JFrame("Card Layout Example");
390. CardLayout cardLayout = new CardLayout();
391. JPanel panel = new JPanel(cardLayout);
392.
393. panel.add(new JButton("Card 1"), "Card 1");
394. panel.add(new JButton("Card 2"), "Card 2");
395.
396. frame.add(panel);
397. frame.setSize(300, 200);
398. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
399. frame.setVisible(true);
400.
401. cardLayout.show(panel, "Card 2");
402. }
403. }
404. Null Layout:
405. import javax.swing.*;
406. import java.awt.*;
407.
408. public class NullLayoutExample {
409. public static void main(String[] args) {
410. JFrame frame = new JFrame("Null Layout Example");
411. frame.setLayout(null); // No layout manager
412. JButton button = new JButton("Click Me");
413. button.setBounds(50, 50, 100, 30); // Position the button manually
414. frame.add(button);
415. frame.setSize(300, 200);
416. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
417. frame.setVisible(true);
418. }
419. }
420. Different JComponents in Swing:
421. import javax.swing.*;
422.
423. public class SwingComponentsExample {
424. public static void main(String[] args) {
425. JFrame frame = new JFrame("Swing Components Example");
426. frame.setSize(400, 400);
427. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
428.
429. JPanel panel = new JPanel();
430. panel.add(new JLabel("Label"));
431. panel.add(new JTextField("TextField"));
432. panel.add(new JButton("Button"));
433. panel.add(new JCheckBox("CheckBox"));
434. panel.add(new JRadioButton("RadioButton"));
435. panel.add(new JComboBox<>(new String[]{"Option 1", "Option 2"}));
436.
437. frame.add(panel);
438. frame.setVisible(true);
439. }
440. }

I will continue with the rest in the next message.

26. Read/Write Operations Using Byte Stream:

import java.io.*;

public class ByteStreamExample {


public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("output.txt");
fos.write(65); // Writes the byte corresponding to 'A'
fos.close();

FileInputStream fis = new FileInputStream("output.txt");


int data = fis.read();
System.out.println("Read byte: " + (char) data);
fis.close();
}
}

27. Read/Write Operations Using Character Stream:

import java.io.*;

public class CharacterStreamExample {


public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!");
writer.close();

FileReader reader = new FileReader("output.txt");


int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
}
}

28. Read/Write Using Random Access:


import java.io.*;

public class RandomAccessExample {


public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
file.writeUTF("This is a test.");

file.seek(0); // Move to the beginning of the file


System.out.println(file.readUTF());

file.close();
}
}

29. Thread Using the Thread Class:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running.");
}

public static void main(String[] args) {


MyThread thread = new MyThread();
thread.start();
}
}

30. Thread Using Runnable Interface:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running.");
}

public static void main(String[] args) {


MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

31. Thread Synchronization:

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public synchronized int getCount() {


return count;
}
}

class MyThread extends Thread {


Counter counter;

MyThread(Counter counter) {
this.counter = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
}

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


Counter counter = new Counter();
Thread t1 = new MyThread(counter);
Thread t2 = new MyThread(counter);
t1.start();
t2.start();
t1.join();
t2.join();

System.out.println("Count: " + counter.getCount());


}
}

32. Servlet Using the Servlet Interface:

import javax.servlet.*;
import java.io.*;

public class HelloServlet implements Servlet {


public void init(ServletConfig config) throws ServletException {}

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello from Servlet!");
}

public void destroy() {}


public ServletConfig getServletConfig() {
return null;
}

public String getServletInfo() {


return "Hello Servlet";
}
}

33. Servlet Using GenericServlet Class:

import javax.servlet.*;
import java.io.*;

public class GenericHelloServlet extends GenericServlet {


public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello from GenericServlet!");
}
}

34. Servlet Using HttpServlet Class:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HttpHelloServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello from HttpServlet!");
}
}

35. Form Handling Using Servlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FormServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println("Hello, " + name);
}
}

36. JDBC Integration with Servlet:

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class JdbcServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

PrintWriter out = response.getWriter();


while (rs.next()) {
out.println("User: " + rs.getString("username"));
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

37. Request and Response Using RequestDispatcher:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class RequestDispatcherServlet1 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
request.setAttribute("message", "Hello from Servlet1");
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet2");
dispatcher.forward(request, response);
}
}

public class RequestDispatcherServlet2 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String message = (String) request.getAttribute("message");
PrintWriter out = response.getWriter();
out.println(message);
}
}

38. Request and Response Using SendRedirect:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class RedirectServlet1 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.sendRedirect("Servlet2");
}
}

public class RedirectServlet2 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Redirected to Servlet2");
}
}

39. Form Handling Using JSP:

<html>
<body>
<form action="process.jsp" method="post">
Enter your name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

40. Use of RMI in Java:

import java.rmi.*;
import java.rmi.server.*;

public interface Hello extends Remote {


String sayHello() throws RemoteException;
}

public class HelloImpl extends UnicastRemoteObject implements Hello {


public HelloImpl() throws RemoteException {}

public String sayHello() {


return "Hello, World!";
}

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


Naming.rebind("Hello", new HelloImpl());
}
}

41. One-Way Communication Through TCP:

import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
Socket socket = serverSocket.accept();
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Hello from Server");
socket.close();
}
}

public class TCPClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
DataInputStream in = new DataInputStream(socket.getInputStream());
System.out.println(in.readUTF());
socket.close();
}
}

42. Two-Way Communication Through TCP:

import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String message = in.readUTF();
out.writeUTF("Server received: " + message);
socket.close();
}
}

public class TCPClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());

out.writeUTF("Hello, Server");
System.out.println(in.readUTF());
socket.close();
}
}

43. Communication Through UDP:

import java.io.*;
import java.net.*;

public class UDPServer {


public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + message);
socket.close();
}
}

public class UDPClient {


public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
byte[] sendData = "Hello, Server".getBytes();
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
serverAddress, 9876);
socket.send(sendPacket);
socket.close();
}
}

These cover the 43 programs you requested. Let me know if you'd like any clarifications or
additional examples!

You might also like