Java Programs Compendium - Short & Easy Solutions
1. Largest of three numbers (if-else)
public class Largest {
public static void main(String[] args) {
int a = 10, b = 20, c = 15;
int max = (a>b)?(a>c?a:c):(b>c?b:c);
[Link]("Largest: " + max);
}
}
2. Prime check
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i=2; i*i<=n; i++) if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
int n = 29;
[Link](n + " is prime? " + isPrime(n));
}
}
3. Fibonacci series (loop)
public class Fibonacci {
public static void main(String[] args) {
int n = 10, a=0,b=1;
[Link](a + (n>1? " " + b : ""));
for (int i=2;i<n;i++){
int c = a+b; [Link](" " + c);
a=b; b=c;
}
}
}
4. Search element in array
import [Link];
public class SearchArray {
public static void main(String[] args) {
int[] arr = {2,5,9,3};
int key = 9; boolean found = false;
for (int x: arr) if (x==key) { found=true; break; }
[Link](key + (found? " found" : " not found"));
}
}
5. Sort array ascending
import [Link];
public class SortArray {
public static void main(String[] args) {
int[] a = {5,2,9,1};
[Link](a);
[Link]([Link](a));
}
}
6. Count vowels and consonants
public class CountVC {
public static void main(String[] args) {
String s = "Hello World";
int v=0,c=0;
for(char ch: [Link]().toCharArray()){
if (ch>='a'&&ch<='z') {
if ("aeiou".indexOf(ch)>=0) v++; else c++;
}
}
[Link]("Vowels="+v+" Consonants="+c);
}
}
7. String functions demo
public class StringDemo {
public static void main(String[] args) {
String s = "HelloWorld";
[Link]([Link]());
[Link]([Link](1));
[Link]([Link](5));
[Link]([Link]("HelloWorld"));
[Link]([Link]("HellaWorld"));
}
}
8. Vector operations
import [Link];
public class VectorOps {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
[Link]("A"); [Link]("B");
[Link]("A");
[Link](v + " size=" + [Link]());
}
}
9. Single inheritance demo
class Parent { void msg(){[Link]("Parent");} }
class Child extends Parent { void show(){[Link]("Child");} }
public class InheritDemo {
public static void main(String[] args){
Child c = new Child(); [Link](); [Link]();
}
}
10. Create and use a package
// Save as com/example/[Link]
package [Link];
public class MyClass {
public static void greet(){ [Link]("Hello from package"); }
}
// Usage:
// import [Link];
// [Link]();
11. try–catch–finally demo
public class TryCatchFinally {
public static void main(String[] args) {
try {
int x = 10/0;
} catch (Exception e) {
[Link]("Caught: " + e);
} finally {
[Link]("Finally block");
}
}
}
12. Handle multiple exceptions
public class MultipleEx {
public static void main(String[] args) {
try {
int[] a = new int[2];
a[2]=5;
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
[Link]("Handled: " + e);
}
}
}
13. Thread using Thread class
class MyThread extends Thread {
public void run(){ [Link]("Thread running"); }
}
public class ThreadDemo {
public static void main(String[] args){
new MyThread().start();
}
}
14. Thread using Runnable
public class RunnableDemo {
public static void main(String[] args){
Runnable r = () -> [Link]("Runnable running");
new Thread(r).start();
}
}
15. Thread priorities
public class ThreadPriority {
public static void main(String[] args) {
Thread t1 = new Thread(() -> [Link]("T1")),
t2 = new Thread(() -> [Link]("T2"));
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link](); [Link]();
}
}
A1. Applet Hello CSJM University (old-style applet)
/* Deprecated API; for exam purposes only */
import [Link];
import [Link];
public class HelloApplet extends Applet {
public void paint(Graphics g){ [Link]("Hello CSJM University",20,20); }
}
A2. Applet draw shapes
import [Link];
import [Link];
public class ShapesApplet extends Applet {
public void paint(Graphics g){
[Link](10,10,100,10);
[Link](10,20,80,40);
[Link](10,70,80,40);
}
}
A3. AWT Button and Label
import [Link].*;
import [Link].*;
public class ButtonLabel extends Frame {
public ButtonLabel(){
setLayout(new FlowLayout());
add(new Label("Click:")); add(new Button("OK"));
setSize(200,100); setVisible(true);
}
public static void main(String[] args){ new ButtonLabel(); }
}
A4. TextField and PasswordField (AWT)
import [Link].*;
public class TextPass extends Frame {
public TextPass(){
setLayout(new FlowLayout());
add(new [Link]("User:")); add(new TextField(10));
add(new [Link]("Pass:")); add(new TextField(10){ { setEchoChar('*'); } });
setSize(300,100); setVisible(true);
}
public static void main(String[] args){ new TextPass(); }
}
A5. List and Choice (ComboBox) in AWT
import [Link].*;
public class ListChoice extends Frame {
public ListChoice(){
setLayout(new FlowLayout());
List list = new List(3); [Link]("One"); add(list);
Choice c = new Choice(); [Link]("A"); add(c);
setSize(200,150); setVisible(true);
}
public static void main(String[] args){ new ListChoice(); }
}
A6. Button action event
import [Link].*; import [Link].*;
public class ButtonEvent extends Frame {
public ButtonEvent(){
Button b = new Button("Click");
[Link](e -> [Link]("Button clicked"));
add(b); setSize(200,100); setVisible(true);
}
public static void main(String[] args){ new ButtonEvent(); }
}
A7. WindowListener example
import [Link].*; import [Link].*;
public class WindowDemo extends Frame {
public WindowDemo(){
addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){
[Link](0); }});
setSize(200,100); setVisible(true);
}
public static void main(String[] args){ new WindowDemo(); }
}
A8. Layouts (Flow, Border, Grid)
import [Link].*;
public class LayoutsDemo extends Frame {
public LayoutsDemo(){
setLayout(new FlowLayout()); add(new Button("F1"));
setSize(300,200); setVisible(true);
}
public static void main(String[] args){ new LayoutsDemo(); }
}
A9. Basic string functions
public class StringBasics {
public static void main(String[] args){
String s = " Hello Java ";
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]("Java","World"));
}
}
J1. JDBC: establish connection (MySQL)
import [Link].*;
public class JDBCConnect {
public static void main(String[] args) throws Exception {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/dbname","user","pass");
[Link]("Connected"); [Link]();
}
}
J2. JDBC insert record
import [Link].*;
public class JDBCInsert {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
Statement st = [Link]();
[Link]("INSERT INTO student(id,name) VALUES(1,'Aryan')");
[Link]("Inserted"); [Link]();
}
}
J3. JDBC update record
import [Link].*;
public class JDBCUpdate {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
Statement st = [Link]();
[Link]("UPDATE student SET name='New' WHERE id=1");
[Link]();
}
}
J4. JDBC delete record
import [Link].*;
public class JDBCDelete {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
Statement st = [Link]();
[Link]("DELETE FROM student WHERE id=1");
[Link]();
}
}
J5. JDBC fetch and display (ResultSet)
import [Link].*;
public class JDBCSelect {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
ResultSet rs = [Link]().executeQuery("SELECT id,name FROM student");
while([Link]()) [Link]([Link](1)+" " + [Link](2));
[Link]();
}
}
J6. JDBC PreparedStatement
import [Link].*;
public class JDBCPrepared {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
PreparedStatement ps = [Link]("INSERT INTO student(id,name) VALUES(?,?)");
[Link](1,2); [Link](2,"Bob"); [Link](); [Link]();
}
}
J7. JDBC ResultSet navigation
import [Link].*;
public class JDBCNav {
public static void main(String[] args) throws Exception {
Connection con =
[Link]("jdbc:mysql://localhost:3306/db","user","pass");
Statement st = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link]("SELECT id,name FROM student");
if([Link]()) [Link]([Link](1)+" " + [Link](2));
if([Link]()) [Link]([Link](1)+" " + [Link](2));
[Link]();
}
}
S1. Servlet Hello World
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
[Link]("text/html"); [Link]().println("<h1>Hello World</h1>");
}
}
S2. Servlet read form data using doGet
// form: ?name=xxx
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String name = [Link]("name");
[Link]().println("Name: " + name);
}
S3. Servlet read form data using doPost
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
String name = [Link]("name");
[Link]().println("Name: " + name);
}
S4. Servlet visit counter (session)
import [Link].*;
public class VisitServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
HttpSession s = [Link]();
Integer cnt = (Integer)[Link]("count");
cnt = (cnt==null)?1:cnt+1;
[Link]("count", cnt);
[Link]().println("Visits: " + cnt);
}
}
S5. Servlet display student info in HTML
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
[Link]("text/html");
[Link]().println("<html><body><h3>Student</h3><p>ID:1<br>Name:Aryan</p></body></html>");
}
S6. Servlet using cookies for username
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
Cookie c = new Cookie("user","aryan"); [Link](c);
[Link]().println("Cookie set");
}
S7. Servlet using HttpSession for login
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
String user = [Link]("user");
HttpSession s = [Link](); [Link]("user", user);
[Link]().println("Logged in");
}
P1. JSP current date and time
<%@ page import="[Link].*" %>
<%= new [Link]() %>
P2. JSP accept and display user input
<!-- form posts to this JSP -->
Name: <%= [Link]("name") %>
P3. JSP declarations/scriptlets/expressions
<%! int x = 5; %>
<% x++; %>
<%= x %>
P4. JSP read form values and store DB (template)
<%@ page import="[Link].*" %>
<%
String name = [Link]("name");
Connection c = [Link]("jdbc:mysql://localhost/db","user","pass");
PreparedStatement ps = [Link]("INSERT INTO student(name) VALUES(?)");
[Link](1,name); [Link](); [Link]();
%>
Saved
P5. JSP simple login authentication
<%
String u = [Link]("user"), p = [Link]("pass");
if("admin".equals(u) && "pass".equals(p)) [Link]("Welcome"); else [Link]("Invalid");
%>
P6. JSP demonstrate JSTL tags (example)
<!-- Example: requires JSTL on classpath -->
<%@ taglib prefix="c" uri="[Link] %>
<c:forEach var="i" begin="1" end="5">${i} </c:forEach>
P7. JSP print numbers 1-10 dynamically
<% for(int i=1;i<=10;i++){ [Link](i+" "); } %>