//Java
//1 Instance Variable
class Student {
    int sId = 10; //Instance Variable
    String sName = "Java";

    static void Display1() { //Static Method
        Student std1 = new Student();
        System.out.println(std1.sId);
        System.out.println(std1.sName);
    }

    static void Display2() { //Static Method
        Student std2 = new Student();
        System.out.println(std2.sId);
        System.out.println(std2.sName);
    }

    public static void main(String[] args) {
        Student.Display1();
        Student.Display2();
    }
}

//2 Instance and static
class Student {
    int sId = 10; //Instance Variable
    String sName = "Java";
    static int sId1 = 20; //Static Variable
    static String sName1 = "JavaScript";
    void Display1() { //Instance Method
        System.out.println(sId);
        System.out.println(sName);
        System.out.println(Student.sId1);
        System.out.println(Student.sName1);
    }

    static void Display2() { //Static Method
        Student std = new Student();
        System.out.println(std.sId);
        System.out.println(std.sName);
        System.out.println(Student.sId1);
        System.out.println(Student.sName1);
    }

    public static void main(String[] args) { //Main Class
        Student std = new Student();
        std.Display1();
        Student.Display2();
    }
}

//3 Constructor
class Student {
    int s_id = 123;
    String s_name = "Jolly";
    Student() { //Default Constructor
        this(5);
        System.out.println("This is Default Constructor");
    }
    Student(int a) { //Parameterized Constructor
        System.out.println("This is Constructor calling another Constructor");
    }
    Student(int rn, String nm) { //Parameterized Constructor
        System.out.println("This is Parameterized Constructor");
    }
    public static void main(String[] args) {
        Student std = new Student();
        Student std1 = new Student(123, "John");
    }
}

//4 Inner Classes and outer class
class Outer { // Outer Class
    private int a = 10, b = 20;
    private void method1() {
        System.out.println("This is Outer Method");
    }
    class Inner { // Inner Class
        int a = 100, b = 200;
        void method2() {
            method1();
            System.out.println(a + b);
            System.out.println(Outer.this.a + Outer.this.b);
            System.out.println("This is Inner Method");
        }
    }
    public static void main(String[] args) { // Main Method
        Outer ot = new Outer();
        Outer.Inner in = ot.new Inner(); in .method2();
    }
}

//5Abstract Class
package internal;
abstract class DemoAbstract {

    abstract int method1(char c, int a);

    abstract float method2(boolean b);

    abstract String credential(String uname, String upwd);

}

 class DemoConcrete extends DemoAbstract {

    @Override
    public int method1(char c, int a) {
        // Implementation for method1
       System.out.println('a');
     return 5;
    }

    @Override
    public float method2(boolean b) {
        // Implementation for method2
        if (b == true) {
        	System.out.println("value is true");
            return 1.0f;
        } else {
        	System.out.println("value is false");
            return 0.0f;
        }
    }

    @Override
    public String credential(String uname, String upwd) {
        // Implementation for credential
       String concat = uname+upwd;
       System.out.println(concat);
       return concat;
    }

}

public class Main {

    public static void main(String[] args) {
        DemoConcrete obj = new DemoConcrete();

        obj.method1('a', 50);
        obj.method2(true);
       obj.credential("user1", "pass1");

         }

}

//6interface
public interface If1 {
void m1();
}
public interface If2 {
void m2();
}
public abstract class Demo implements If1, If2 {
public void m1() {
System.out.println("M1 Method");
}
}
public class Demo2 extends Demo{
public void m2() {
System.out.println("M2 Method");
}
public static void main(String[] args) {
Demo2 d= new Demo2();
d.m1();
d.m2();
}
}

//7arrays 
public class ArrayExample {
 public static void main(String[] args) {
 int[] a = {10, 20, 30, 40, 50};
 // find sum of all elements
 int sum = 0;
 for (int i = 0; i < a.length; i++) {
 sum += a[i];
 }
 System.out.println("Sum of all elements: " + sum);
 // find greatest element
 int max = a[0];
 for (int i = 1; i < a.length; i++) {
 if (a[i] > max) {
 max = a[i];
 }
 }
 System.out.println("Greatest element: " + max);
 // find smallest element
 int min = a[0];
 for (int i = 1; i < a.length; i++) {
 if (a[i] < min) {
 min = a[i];
 }
 }
 System.out.println("Smallest element: " + min);
 }
}


//8array as Parameteriz
public class ArrayExample {
 // method that takes an array as a parameter
 public static void printArray(int[] arr) {
 for (int i = 0; i < arr.length; i++) {
 System.out.print(arr[i] + " ");
 }
 System.out.println();
 }
 // method that returns an array
 public static int[] createArray(int n) {
 int[] arr = new int[n];
 for (int i = 0; i < n; i++) {
 arr[i] = i + 1;
 }
 return arr;
 }
 public static void main(String[] args) {
 int[] arr1 = {1, 2, 3, 4, 5};
 // passing an array to a method
 printArray(arr1);
 // getting an array from a method
 int[] arr2 = createArray(5);
 printArray(arr2);
 }
}

//9AString operations
public class StringOperationsExample {

    public static void main(String[] args) {

        // Example String
        String str = "Hello, World!";

        // findLength() method
        int length = str.length();
        System.out.println("Length of the string: " + length);

        // findCharAt() method
        char ch = str.charAt(7);
        System.out.println("Character at index 7: " + ch);

        // findSubstring() method
        String subString = str.substring(7, 12);
        System.out.println("Substring from index 7 to 11: " + subString);

        // findIndexOf() method
        int index = str.indexOf("World");
        System.out.println("Index of 'World': " + index);

        // findStartsWith() method
        boolean startsWith = str.startsWith("Hello");
        System.out.println("String starts with 'Hello': " + startsWith);

        // findEndsWith() method
        boolean endsWith = str.endsWith("!");
        System.out.println("String ends with '!': " + endsWith);

        // findisEmpty() method
        boolean isEmpty = str.isEmpty();
        System.out.println("String is empty: " + isEmpty);

        // findEquals() method
        boolean isEqual = str.equals("Hello, World!");
        System.out.println("String is equal to 'Hello, World!': " + isEqual);

        // findEqualsIgnoreCase() method
        boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello, world!");
        System.out.println("String is equal to 'hello, world!': " +
            isEqualIgnoreCase);

        // findConcat() method
        String concatString = str.concat(" Welcome to Java World!");
        System.out.println("Concatenated string: " + concatString);
    }
}

//9B String buffer class
public class StringBufferOperations {
 public static void main(String[] args) {
 StringBuffer sb = new StringBuffer("Hello");
 // concatenation using append()
 sb.append(", world!");
 System.out.println(sb.toString());
 // insertion using insert()
 sb.insert(5, " there");
 System.out.println(sb.toString());
 // replacement using replace()
 sb.replace(7, 12, "Earth");
 System.out.println(sb.toString());
 }
}

//9C STring tokenizer
import java.util.StringTokenizer;
public class StringTokenizeExample {
 public static void main(String[] args) {
 String str = "we are doing Java practical";
 // create a new StringTokenizer object with the given string and delimiter
 StringTokenizer st = new StringTokenizer(str, " ");
 // iterate over the tokens and print them out
 while (st.hasMoreTokens()) {
 System.out.println(st.nextToken());
 }
 }
}

//10Exceptoin handling
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ExceptionHandling {
    public static void main(String[] args) {
        // ArithmeticException
        try {
            int result = 10 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught: " + e.getMessage());
        }
        // NullPointerException
        String str = null;
        try {
            int length = str.length();
            System.out.println("Length of string: " + length);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException caught: " + e.getMessage());
        }
        // ArrayIndexOutOfBoundsException
        int[] arr = {
            1,
            2,
            3
        };
        try {
            int value = arr[3];
            System.out.println("Value: " + value);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException caught: " +
                e.getMessage());
        }
        // FileNotFoundException
        try {
            File file = new File("file.txt");
            Scanner scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException caught: " + e.getMessage());
        }
    }
}

//11multithreading
//using thread class
package internal;
import java.lang.*;

//thread using thread class

class Mythread1 extends Thread{
	
	public void run () {
		int i = 0;
		while(i<1000){
		System.out.println("rohit");
		i++;
	}
	}
}
class Mythread2 extends Thread{
	public void run() {
		int j =0;
		while(j<1000) {
			System.out.println("patil");
			j++;
		}
	}
}
public class hello {
	public static void main(String []args) {
	Mythread1 th = new Mythread1();
	Mythread2 tt = new Mythread2();
	th.start();
	tt.start();
}}

// using runnable interface
package internal;
import java.lang.*;


//thread using runnable interface
class Threadurrr implements Runnable{
	
	public void run() {
		int i = 0;
		while(i<500) {
			System.out.println("rohit");
			i++;
				}
	}
	}
class Threadurr implements Runnable{
	
	public void run() {
		int i = 0;
		while(i<500) {
			System.out.println("patil");
			i++;
		}
	}
	}
public class threadur {
	public static void main(String[] args) {
		Threadurrr bullet1 = new Threadurrr();
		Thread gun1 = new Thread(bullet1);
		Threadurr bullet2 = new Threadurr();
		Thread gun2 = new Thread(bullet2);
		gun1.start();
		gun2.start();
			}
}

//12A File I/O
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class VowelCounter {
    public static void main(String[] args) throws IOException {
        String filename = "abc.txt"; 
        int count = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            int c;
            while ((c = br.read()) != -1) {
                char character = (char) c;
                if (isVowel(character)) {
                    count++;
                }
            }
        }
        System.out.println("Number of vowels in " + filename + " is " + count);
    }

    private static boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
}

//12B Write a program in Java to copy the contents of one file into another.
import java.io.*;

public class FileOperation {

    public static void main(String[] args) {
        String sourceFile = "abc.txt";
        String destinationFile = "xyz.txt";

        try (FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(destinationFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("File copied successfully.");

        } catch (IOException e) {
            System.err.println("Error copying file: " + e.getMessage());
        }
    }
}

//13A event handling blood donation

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class BloodDonationForm extends Frame implements ActionListener {
   /**
	 * 
	 */
	private static final long serialVersionUID = 5797479938196761651L;
private Label nameLabel, ageLabel, bloodGroupLabel, lastDonationDateLabel, readyToDonateLabel;
   private TextField nameField, ageField, bloodGroupField, lastDonationDateField;
   private Checkbox readyToDonateCheckbox;
   private Button submitButton;
   private ArrayList<String> nameList, ageList, bloodGroupList, lastDonationDateList, readyToDonateList;
   
   public BloodDonationForm() {
      setTitle("Blood Donation Form");
      setSize(400, 300);
      setLayout(new GridLayout(6, 2));
      
      nameLabel = new Label("Name:");
      add(nameLabel);
      nameField = new TextField(20);
      add(nameField);
      
      ageLabel = new Label("Age:");
      add(ageLabel);
      ageField = new TextField(3);
      add(ageField);
      
      bloodGroupLabel = new Label("Blood Group:");
      add(bloodGroupLabel);
      bloodGroupField = new TextField(3);
      add(bloodGroupField);
      
      lastDonationDateLabel = new Label("Last Donation Date (DD/MM/YYYY):");
      add(lastDonationDateLabel);
      lastDonationDateField = new TextField(10);
      add(lastDonationDateField);
      
      readyToDonateLabel = new Label("Ready to Donate?");
      add(readyToDonateLabel);
      readyToDonateCheckbox = new Checkbox();
      add(readyToDonateCheckbox);
      
      submitButton = new Button("Submit");
      add(submitButton);
      submitButton.addActionListener(this);
      
      nameList = new ArrayList<String>();
      ageList = new ArrayList<String>();
      bloodGroupList = new ArrayList<String>();
      lastDonationDateList = new ArrayList<String>();
      readyToDonateList = new ArrayList<String>();
      
      setVisible(true);
   }
   
   public void actionPerformed(ActionEvent e) {
      String name = nameField.getText();
      String age = ageField.getText();
      String bloodGroup = bloodGroupField.getText();
      String lastDonationDate = lastDonationDateField.getText();
      String readyToDonate = readyToDonateCheckbox.getState() ? "Yes" : "No";
      
      nameList.add(name);
      ageList.add(age);
      bloodGroupList.add(bloodGroup);
      lastDonationDateList.add(lastDonationDate);
      readyToDonateList.add(readyToDonate);
      
      nameField.setText("");
      ageField.setText("");
      bloodGroupField.setText("");
      lastDonationDateField.setText("");
      readyToDonateCheckbox.setState(false);
      
      System.out.println("Form Submitted!");
   }
   
   public static void main(String[] args) {
      new BloodDonationForm();
   }
}

//13B trafic light

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TrafficSignal extends JFrame implements ActionListener {
   /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
JButton red, green, yellow;

   public TrafficSignal() {
      super("Traffic Signal");
      red = new JButton("RED");
      green = new JButton("GREEN");
      yellow = new JButton("YELLOW");
      red.addActionListener(this);
      green.addActionListener(this);
      yellow.addActionListener(this);
      setLayout(new FlowLayout());
      add(red);
      add(green);
      add(yellow);
      setSize(300, 100);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }

   public void actionPerformed(ActionEvent e) {
      if (e.getSource() == red) {
         JOptionPane.showMessageDialog(null, "STOP");
      } else if (e.getSource() == green) {
         JOptionPane.showMessageDialog(null, "GO");
      } else if (e.getSource() == yellow) {
         JOptionPane.showMessageDialog(null, "SLOW DOWN");
      }
   }

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


//14A JDBC Servlet
//swing file
Import java.awt.*;
Import java.awt.event.*;
import javax.swing.*;
public class StudentInfoUI extends JFrame {
    private JTextField rollNumberField;
    private JButton fetchButton;
    private JTextArea infoArea;
    public StudentInfoUI() {
        setTitle("Student Information");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // create components
        rollNumberField = new JTextField(10);
        fetchButton = new JButton("Fetch Info");
        infoArea = new JTextArea(10, 40);
        // add components to layout
        JPanel panel = new JPanel();
        panel.add(new JLabel("Roll Number: "));
        panel.add(rollNumberField);
        panel.add(fetchButton);
        add(panel, BorderLayout.NORTH);
        add(new JScrollPane(infoArea),
            BorderLayout.CENTER);
        // add event listener to button
        fetchButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // get roll number from text field
                    String rollNumber =
                        rollNumberField.getText();
                    // send request to servlet
                    String response = Swing Code: -
                        Import java.awt.*;
                    Import java.awt.event.*;
                    import javax.swing.*;
                    public class StudentInfoUI extends JFrame {
                        private JTextField rollNumberField;
                        private JButton fetchButton;
                        private JTextArea infoArea;
                        public StudentInfoUI() {
                            setTitle("Student Information");
                            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            // create components
                            rollNumberField = new JTextField(10);
                            fetchButton = new JButton("Fetch Info");
                            infoArea = new JTextArea(10, 40);
                            // add components to layout
                            JPanel panel = new JPanel();
                            panel.add(new JLabel("Roll Number: "));
                            panel.add(rollNumberField);
                            panel.add(fetchButton);
                            add(panel, BorderLayout.NORTH);
                            add(new JScrollPane(infoArea),
                                BorderLayout.CENTER);
                            // add event listener to button
                            fetchButton.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    // get roll number from text field
                                    String rollNumber =
                                        rollNumberField.getText();
                                    // send request to servlet
                                    String response =

                                        ServletUtil.fetchStudentInfo(rollNumber);
                                    // display response in text area
                                    infoArea.setText(response);
                                }
                            });
                            pack();
                            setVisible(true);
                        }
                        ServletUtil.fetchStudentInfo(rollNumber);
                        // display response in text area
                        infoArea.setText(response);
                    }
                }); pack(); setVisible(true);
        }
        public static void main(String[] args) {
            new StudentInfoUI();
        }
    }
    
//Servlet
Import java.io.IOException;
Import java.io.PrintWriter;
Import java.sql.Connection;
Import java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import java.sql.ResultSet;
Import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentDetailsServlet extends
HttpServlet {
    public void doGet(HttpServletRequest request,
        HttpServletResponse response)
    throws ServletException, IOException {
        String rollNumber =
            request.getParameter("rollNumber");
        String driver = "com.mysql.jdbc.Driver";
        String url =
            "jdbc:mysql://localhost:3306/student";
        String user = "root";
        String password = "password";
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        String query = "select * from student_details
        where roll_number = ? ";
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url,
                user, password);
            pst =
                con.prepareStatement(query);
            pst.setString(1, rollNumber);
            rs = pst.executeQuery();
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            if (rs.next()) {
                out.println("<h2>Student Details</h2>");
                out.println("<p><b>Name:</b> " +
                    rs.getString("name") + "</p>");
                out.println("<p><b>Class:</b> " +
                    rs.getString("class") + "</p>");
                out.println("<p><b>Marks:</b> " +
                    rs.getString("marks") + "</p>");
                out.println("<p><b>Age:</b> " +
                    rs.getString("age") + "</p>");
                out.println("<p><b>Gender:</b> " +
                    rs.getString("gender") + "</p>");
            } else {
                out.println("<h2>No student found with
                    Roll Number " + rollNumber + " < /h2>");
                }
                out.println("</body></html>");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (rs !=
                        null) {
                        rs.close();
                    }
                    if (pst != null) {
                        pst.close();
                    }
                    if (con != null) {
                        con.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    
//14B cultural
//EventForm.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Cultural Event Details</title>
   </head>
   <body>
      <h1> Registration Details</h1>
      <form action="RegistrationServlet" method="get">
         Student Roll No.: <input type="number"
            name="stdrollno"><br>
         Student Name : <input type="text" name="stdname"><br>
         Student class : <input type="text" name="stdclass"><br>
         Student Gender : <input type="text" name="stdgender"><br>
         Student Event Registration : <input type="text"
            name="stdeventtype"><br>
         <input type="submit" value="Save">
      </form>
   </body>
</html>

//Success.html
<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Recorded Successfully!</title>
   </head>
   <body>
      Your record was inserted into the database successfully!
   </body>
</html>

//Retry.html
<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Something Went Wrong!</title>
   </head>
   <body>
      Oops!, Record could not be inserted into the database. Please
      try again.
   </body>
</html>

//Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="https://jakarta.ee/xml/ns/jakartaee"
   xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
   xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
   https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd
   http://xmlns.jcp.org/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
   version="5.0">
   <display-name>CollegeCulturalEvents</display-name>
   <welcome-file-list>
      <welcome-file>EventForm.html</welcome-file>
   </welcome-file-list>
   <servlet>
      <description></description>
      <servlet-name>RegistrationServlet</servlet-name>
      <servlet-class>RegistrationServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>RegistrationServlet</servlet-name>
      <url-pattern>/RegistrationServlet</url-pattern>
   </servlet-mapping>
</web-app>

//Registration.java
public class Registration {
    private int stdrollno;
    private String stdname;
    private String stdclass;
    private String stdgender;
    private String stdeventtype;
    public int getStdrollno() {
        return stdrollno;
    }
    public void setStdrollno(int stdrollno) {
        this.stdrollno = stdrollno;
    }
    public String getStdname() {
        return stdname;
    }
    public void setStdname(String stdname) {
        this.stdname = stdname;
    }
    public String getStdclass() {
        return stdclass;
    }
    public void setStdclass(String stdclass) {
        this.stdclass = stdclass;
    }
    public String getStdgender() {
        return stdgender;
    }
    public void setStdgender(String stdgender) {
        this.stdgender = stdgender;
    }
    public String getStdeventtype() {
        return stdeventtype;
    }
    public void setStdeventtype(String stdeventtype) {
        this.stdeventtype = stdeventtype;
    }
}

//RegistrationDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegistrationDAO {
    String dbDriver = "com.mysql.jdbc.Driver"; //connects db to
    drivers
    String dbURL = "jdbc:mysql://localhost:3306/culturalevent"; //
    URL
    String userName = "root";
    String pwd = "root";
    Connection dbCon; // find out why
    private boolean connectToDtbc() throws
    SQLException, ClassNotFoundException {
        Class.forName(dbDriver);
        dbCon = DriverManager.getConnection(dbURL, userName, pwd);
        return true;
    }
    public boolean insertRecord(Registration rejObj) {
        //details below is table name in insertQuerystr
        String insertQuerystr = "Insert into event values
            ( ? , ? , ? , ? , ? )
        ";
        try {
            if (connectToDtbc()) {
                // PreparedStatement TO FIND OUT
                // 1,2,3,4 col no
                // executeUpdate() data submission
                PreparedStatement ppStmt =
                    dbCon.prepareStatement(insertQuerystr);
                ppStmt.setInt(1, rejObj.getStdrollno());
                ppStmt.setString(2, rejObj.getStdname());
                ppStmt.setString(3, rejObj.getStdclass());
                ppStmt.setString(4, rejObj.getStdgender());
                ppStmt.setString(5, rejObj.getStdeventtype());
                ppStmt.executeUpdate();
                ppStmt.close();
                dbCon.close();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }
}


//RegistrationServlet.java
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegistrationServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
,NumberFormatException {
Registration regObj= new Registration();
regObj.setStdrollno(Integer.parseInt(request.getParameter("std
rollno")));
regObj.setStdname(request.getParameter("stdname"));
regObj.setStdclass(request.getParameter("stdclass"));
regObj.setStdgender(request.getParameter("stdgender"));
regObj.setStdeventtype(request.getParameter("stdeventtype"));
RegistrationDAO regDAOObj=new RegistrationDAO();
if(regDAOObj.insertRecord(regObj)) {
response.sendRedirect("Success.html");
}
else {
response.sendRedirect("Retry.html");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}


////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//////////////////////////DSA//////////////////////////////////////
///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////



//1 Singly linkedlist
class Node {
    constructor(data) {
      this.data = data;
      this.next = null;
    }
  }
  
  class LinkedList {
    constructor() {
      this.head = null;
    }
  
    insertAtBeginning(data) {
      let newNode = new Node(data);
      newNode.next = this.head;
      this.head = newNode;
    }
  
    insertAtEnd(data) {
      let newNode = new Node(data);
      if (!this.head) {
        this.head = newNode;
        return;
      }
      let last = this.head;
      while (last.next) {
        last = last.next;
      }
      last.next = newNode;
    }
  
    deleteNode(key) {
      let temp = this.head;
      if (temp && temp.data == key) {
        this.head = temp.next;
        return;
      }
      let prev = null;
      while (temp && temp.data != key) {
        prev = temp;
        temp = temp.next;
      }
      if (!temp) return;
      prev.next = temp.next;
    }
  
    reverse() {
      let prev = null;
      let current = this.head;
      while (current) {
        let nextNode = current.next;
        current.next = prev;
        prev = current;
        current = nextNode;
      }
      this.head = prev;
    }
  
    display() {
      let temp = this.head;
      while (temp) {
        console.log(temp.data);
        temp = temp.next;
      }
    }
  }
  
  let linkedList = new LinkedList();
  linkedList.insertAtEnd(1);
  linkedList.insertAtBeginning(2);
  linkedList.insertAtBeginning(3);
  linkedList.insertAtEnd(4);
  linkedList.insertAtEnd(5);
  console.log("Linked List before reversal:");
  linkedList.display();
  linkedList.reverse();
  console.log("\nLinked List after reversal:");
  linkedList.display();
  
  
  
  //2 Doubly Linkedlist
  class Node {
    constructor(data) {
      this.data = data;
      this.next = null;
      this.prev = null;
    }
  }
  
  class DoublyLinkedList {
    constructor() {
      this.head = null;
      this.tail = null;
    }
  
    insertAtBeginning(data) {
      let newNode = new Node(data);
      newNode.next = this.head;
      if (this.head) {
        this.head.prev = newNode;
      }
      this.head = newNode;
      if (!this.tail) {
        this.tail = newNode;
      }
    }
  
    insertAtEnd(data) {
      let newNode = new Node(data);
      if (!this.head) {
        this.head = newNode;
        this.tail = newNode;
        return;
      }
      this.tail.next = newNode;
      newNode.prev = this.tail;
      this.tail = newNode;
    }
  
    deleteNode(key) {
      let temp = this.head;
      while (temp) {
        if (temp.data === key) {
          if (temp === this.head && temp === this.tail) {
            this.head = null;
            this.tail = null;
          } else if (temp === this.head) {
            this.head = this.head.next;
            this.head.prev = null;
          } else if (temp === this.tail) {
            this.tail = this.tail.prev;
            this.tail.next = null;
          } else {
            temp.prev.next = temp.next;
            temp.next.prev = temp.prev;
          }
          return;
        }
        temp = temp.next;
      }
    }
  
    display() {
      let temp = this.head;
      while (temp) {
        console.log(temp.data);
        temp = temp.next;
      }
    }
  }
  
  let doublyLinkedList = new DoublyLinkedList();
  doublyLinkedList.insertAtEnd(1);
  doublyLinkedList.insertAtEnd(2);
  doublyLinkedList.insertAtEnd(3);
  doublyLinkedList.insertAtBeginning(4);
  doublyLinkedList.insertAtBeginning(5);
  console.log("Doubly Linked List before deletion:");
  doublyLinkedList.display();
  doublyLinkedList.deleteNode(3);
  console.log("\nDoubly Linked List after deletion:");
  doublyLinkedList.display();
  
  
  
//3 Stack
class Node {
    constructor(value) {
      this.value = value;
      this.next = null;
    }
  }
  
  class Stack {
    constructor() {
      this.top = null;
    }
  
    push(value) {
      let newNode = new Node(value);
      newNode.next = this.top;
      this.top = newNode;
    }
  
    pop() {
      if (this.top == null) 
      return null;
      let item = this.top.value;
      this.top = this.top.next;
      return item;
    }
  
    display() {
      let current = this.top;
      while (current != null) {
        console.log(current.value);
        current = current.next;
      }
    }
  }


let stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.display();
stack.pop();
stack.display();


//4 Queue
class Node {
    constructor(value) {
      this.value = value;
      this.next = null;
    }
  }
  
  class Queue {
    constructor() {
      this.front = null;
      this.rear = null;
    }
  
    insert(value) {
      let newNode = new Node(value);
      if (this.rear === null) {
        this.front = this.rear = newNode;
        return;
      }
      this.rear.next = newNode;
      this.rear = newNode;
    }
  
    delete() {
      if (this.front === null) return null;
      let item = this.front.value;
      this.front = this.front.next;
      if (this.front === null) this.rear = null;
      return item;
    }
  
    display() {
      let current = this.front;
      while (current !== null) {
        console.log(current.value);
        current = current.next;
      }
    }
  }


let queue = new Queue();
queue.insert(1);
queue.insert(2);
queue.insert(3);
queue.display();
queue.delete();
queue.display();


//Circular queue
class Node {
    constructor(value) {
      this.value = value;
      this.next = null;
    }
  }
  
  class CircularQueue {
    constructor() {
      this.head = null;
      this.tail = null;
    }
  
    enqueue(value) {
      const newNode = new Node(value);
      if (this.isEmpty()) {
        this.head = newNode;
        this.tail = newNode;
        this.tail.next = this.head;
      } else {
        this.tail.next = newNode;
        this.tail = newNode;
        this.tail.next = this.head;
      }
    }
  
    dequeue() {
      if (this.isEmpty()) {
        return "Queue is empty";
      }
      const value = this.head.value;
      if (this.head === this.tail) {
        this.head = null;
        this.tail = null;
      } else {
        this.head = this.head.next;
        this.tail.next = this.head;
      }
      return value;
    }
  
    isEmpty() {
      return !this.head;
    }
  
  display() {
    if (this.isEmpty()) {
      console.log("Queue is empty");
      return;
    }
    let current = this.head;
    do {
      console.log(current.value);
      current = current.next;
    } while (current !== this.head);
  }
}
  const queue = new CircularQueue();
  queue.enqueue(1);
  queue.enqueue(2);
  queue.enqueue(3);
  queue.dequeue()
  queue.dequeue()
  queue.dequeue()
  queue.dequeue()
 
  queue.display();
      
      

// priority queue
class Node {
    constructor(data, priority) {
      this.data = data;
      this.priority = priority;
    //  this.next = null;
    }
  }
  
  class PriorityQueue {
    constructor() {
      
      this.head = null;
    }
  
    enqueue(data, priority) {
      const node = new Node(data, priority);
  
      if (!this.head || priority > this.head.priority) {
        node.next = this.head;
        this.head = node;
      } else {
        let current = this.head;
        while (current.next && current.next.priority >= priority) {
          current = current.next;
        }
        node.next = current.next;
        current.next = node;
      }
    }
  
    dequeue() {
      if (!this.head) {
        return null;
      }
      const dequeued = this.head;
      this.head = this.head.next;
      return dequeued.data;
    }

    display() {
        let current = this.head;
        while (current) {
          console.log(`Data: ${current.data}, Priority: ${current.priority}`);
          current = current.next;
        }
      }
          
  }


  const ll = new PriorityQueue()
  ll.enqueue(100 ,3 )
  ll.enqueue(200 ,1 )
  ll.enqueue(300, 2 )
  //ll.dequeue()
  ll.enqueue(321 , 4)
  ll.enqueue(321 , 53)
  ll.enqueue(321 , 76)
  ll.enqueue(321 , 76)
  ll.enqueue(34 , -76)
 

  ll.display( )
  
 
  //7reverse String
  
  function reverseString(str){
    let stack = [];
   
    for(let i = 0; i < str.length ; i++){
      stack.push(str[i])
    }
    let reverseString = ""
    while(stack.length > 0){
      reverseString += stack.pop()
    }
    return reverseString;
  }
  console.log(reverseString("Hello"));
  

//8Balance paranthesis

function areParenthesesBalanced(expression) {
  let stack = [];

  for (let i = 0; i < expression.length; i++) {
    let character = expression[i];

    if (character === '(' || character === '{' || character === '[') {
      stack.push(character);
    } else if (character === ')' || character === '}' || character === ']') {
      if (stack.length === 0) {
        return false;
      }

      let lastCharacter = stack.pop();

      if (
        (character === ')' && lastCharacter !== '(') ||
        (character === '}' && lastCharacter !== '{') ||
        (character === ']' && lastCharacter !== '[')
      ) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

let expression = "({[]})";
let result = areParenthesesBalanced(expression);
console.log(result); // outputs true



//9Reverse stack using queue

class Queue {
    constructor() {
      this.items = [];
    }
  
    enqueue(element) {
      this.items.push(element);
    }
  
    dequeue() {
      return this.items.shift();
    }
  
    isEmpty() {
      return this.items.length === 0;
    }
  
    size() {
      return this.items.length;
    }
  }
  
  class Stack {
    constructor() {
      this.items = [];
    }
  
    push(element) {
      this.items.push(element);
    }
  
    pop() {
      return this.items.pop();
    }
  
    isEmpty() {
      return this.items.length === 0;
    }
  
    size() {
      return this.items.length;
    }
  
    reverseStack(stack) {
      let queue = new Queue();
  
      while (!stack.isEmpty()) {
        queue.enqueue(stack.pop());
      }
  
      while (!queue.isEmpty()) {
        stack.push(queue.dequeue());
      }
  
      return stack;
    }
  }

  let stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);

console.log(stack.items); // outputs [1, 2, 3]

stack = stack.reverseStack(stack);

console.log(stack.items); // outputs [3, 2, 1]


//10BST
class Node {
    constructor(value) {
      this.value = value;
      this.left = null;
      this.right = null;
    }
  }
  
  class BinarySearchTree {
    constructor() {
      this.root = null;
    }
  
    insert(value) {
      const newNode = new Node(value);
      if (!this.root) {
        this.root = newNode;
        return this;
      }
  
      let current = this.root;
      while (true) {
        if (value === current.value) return undefined;
        if (value < current.value) {
          if (!current.left) {
            current.left = newNode;
            return this;
          }
          current = current.left;
        } else {
          if (!current.right) {
            current.right = newNode;
            return this;
          }
          current = current.right;
        }
      }
    }
  
   
   inorder(root){
    if (root == null) return;
    this.inorder(root.left);
    console.log(root.data);
    this.inorder(root.right);
   }

 preorder(root){
     if(root == null)return
     console.log(root.data)
     this.preorder(root.left)
     this.preorder(root.right)
    
 }

 postOrder(root){
     if(root == null)return
     this.postOrder(root.left)
     this.postOrder(root.right)
      console.log(root.data)
}

  const bst = new BinarySearchTree();
  bst.insert(10);
  bst.insert(5);
  bst.insert(15);
  bst.insert(2);
  bst.insert(7);
  bst.insert(12);
  bst.insert(17);
  
  
  //Graph traversel


class Graph {
    constructor() {
      this.adjacencyList = {};
    }
  
    addVertex(vertex) {
      if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
    }
  
    addEdge(vertex1, vertex2) {
      this.adjacencyList[vertex1].push(vertex2);
      this.adjacencyList[vertex2].push(vertex1);
    }
  
    removeEdge(vertex1, vertex2) {
      this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(
        (v) => v !== vertex2
      );
      this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(
        (v) => v !== vertex1
      );
    }
  
    removeVertex(vertex) {
      while (this.adjacencyList[vertex].length) {
        const adjacentVertex = this.adjacencyList[vertex].pop();
        this.removeEdge(vertex, adjacentVertex);
      }
      delete this.adjacencyList[vertex];
    }
  
    depthFirstTraversal(start) {
      const result = [];
      const visited = {};
      const adjacencyList = this.adjacencyList;
  
      (function dfs(vertex) {
        if (!vertex) return null;
        visited[vertex] = true;
        result.push(vertex);
        adjacencyList[vertex].forEach((neighbor) => {
          if (!visited[neighbor]) {
            return dfs(neighbor);
          }
        });
      })(start);
  
      return result;
    }
  
    breadthFirstTraversal(start) {
      const queue = [start];
      const result = [];
      const visited = {};
      visited[start] = true;
  
      while (queue.length) {
        const vertex = queue.shift();
        result.push(vertex);
  
        this.adjacencyList[vertex].forEach((neighbor) => {
          if (!visited[neighbor]) {
            visited[neighbor] = true;
            queue.push(neighbor);
          }
        });
      }
  
      return result;
    }
  }

  let graph = new Graph();

graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addVertex("E");
graph.addVertex("F");

graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "D");
graph.addEdge("C", "E");
graph.addEdge("D", "E");
graph.addEdge("D", "F");
graph.addEdge("E", "F");

console.log(graph.depthFirstTraversal("A")); // Output: ["A", "B", "D", "E", "C", "F"]
console.log(graph.breadthFirstTraversal("A")); // Output: ["A", "B", "C", "D", "E", "F"]

//linear search


function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i;
    }
  }
  return -1;
}

const numbers = [2, 5, 9, 15, 22];
const target = 22;
const result = linearSearch(numbers, target);

console.log(result);


//13binary search


function binarySearch(arr, target) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let middle = Math.floor((start + end) / 2);

    if (arr[middle] === target) {
      return middle;
    } else if (arr[middle] < target) {
      start = middle + 1;
    } else {
      end = middle - 1;
    }
  }

  return -1;
}

const numbers = [2, 5, 9, 15, 22];
const target = 22;
const result = binarySearch(numbers, target);

console.log(result);

//14Rain Trrece

function rainTerrace(arr) {
    let n = arr.length;
    let left = Array(n).fill(0);
    let right = Array(n).fill(0);
    let water = 0;
  
    left[0] = arr[0];
    for (let i = 1; i < n; i++) {
      left[i] = Math.max(left[i - 1], arr[i]);
    }
  
    right[n - 1] = arr[n - 1];
    for (let i = n - 2; i >= 0; i--) {
      right[i] = Math.max(right[i + 1], arr[i]);
    }
  
    for (let i = 0; i < n; i++) {
      water += Math.min(left[i], right[i]) - arr[i];
    }
  
    return water;
  }
  
  const heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
  const result = rainTerrace(heights);
  
  console.log(result); // Outputs: 6
  
  
  //15Recurssice staircase
function fun(n){
    //let count = 0 
    if ( n == 0 || n == 1 ){
        return 1;
    }

        if(n<0){
            return 0;
        }

        else{
            return fun(n-1) + fun (n-2);
        }
    
}
console.log(fun(5))


//16Maximmum subarray


function maximum_subarray(arr, n){
    let max_sum = Number.MIN_VALUE;
    for(let i = 0 ; i<n ; i++){
        max_sum = 0;
        for(let j = i ; j<n ; j++){
            sum = max_sum + arr[j]
            if(sum>max_sum){
                max_sum = sum;
            }
        }
    }
    return max_sum;
 }

 let arr = [2,-4,5, 4,-5, 5, 2 , -4 , 2 ,4 ]
 let n = arr.length
 console.log(maximum_subarray( arr , n))
 
 //17 Minimum number of jumps 


function minJumps(arr) {
    let n = arr.length;
    let jumps = Array(n).fill(Infinity);
  
    jumps[0] = 0;
  
    for (let i = 1; i < n; i++) {
      for (let j = 0; j < i; j++) {
        if (i <= j + arr[j] && jumps[j] !== Infinity) {
          jumps[i] = Math.min(jumps[i], jumps[j] + 1);
        }
      }
    }
  
    return jumps[n - 1] === Infinity ? -1 : jumps[n - 1];
  }
  
  const arr = [1, 3, 6, 1, 0, 9];
  const result = minJumps(arr);
  
  console.log(result); // Outputs: 3
  
  
  //18t Quick Sort.



function quickSort(arr, left = 0, right = arr.length - 1) {
  if (left < right) {
    let pivotIndex = partition(arr, left, right);

    quickSort(arr, left, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, right);
  }

  return arr;
}

function partition(arr, left, right) {
  let pivot = arr[right];
  let i = left - 1;

  for (let j = left; j <= right - 1; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }

  [arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];

  return i + 1;
}

const arr = [4, 3, 6, 1, 8, 9, 2];
const result = quickSort(arr);

console.log(result); // Outputs: [1, 2, 3, 4, 6, 8, 9]


//19MergeSort


function mergeSort(arr) {
  if (arr.length === 1) return arr;

  let mid = Math.floor(arr.length / 2);
  let left = arr.slice(0, mid);
  let right = arr.slice(mid);

  return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right) {
  let result = [];
  let i = 0;
  let j = 0;

  while (i < left.length && j < right.length) {
    if (left[i] < right[j]) {
      result.push(left[i]);
      i++;
    } else {
      result.push(right[j]);
      j++;
    }
  }

  while (i < left.length) {
    result.push(left[i]);
    i++;
  }

  while (j < right.length) {
    result.push(right[j]);
    j++;
  }

  return result;
}

const arr = [4, 3, 6, 1, 8, 9, 2];
const result = mergeSort(arr);

console.log(result); // Outputs: [1, 2, 3, 4, 6, 8, 9]

//20Tower of Hanoi problem.


function towerOfHanoi(n, source, auxiliary, target) {
    if (n === 1) {
      console.log(`Move disk 1 from source ${source} to target ${target}`);
      return;
    }
  
    towerOfHanoi(n - 1, source, target, auxiliary);
    console.log(`Move disk ${n} from source ${source} to target ${target}`);
    towerOfHanoi(n - 1, auxiliary, source, target);
  }
  
  const n = 3;
  towerOfHanoi(n, 'A', 'B', 'C');
  
  // Outputs:
  // Move disk 1 from source A to target C
  // Move disk 2 from source A to target B
  // Move disk 1 from source C to target B
  // Move disk 3 from source A to target C
  // Move disk 1 from source B to target A
  // Move disk 2 from source B to target C
  // Move disk 1 from source A to target C
  
  
  //21  Fibonacci numbers
 
function fibonacciDP(n) {
    let dp = new Array(n+1);
    dp[0] = 0;
    dp[1] = 1;
  
    for (let i = 2; i <= n; i++) {
      dp[i] = dp[i-1] + dp[i-2];
    }
  
    return dp[n];
  }
  
  console.log(fibonacciDP(9)); // 34
  
  
  //another option
  function fibonaci(n){
    if(n<=1){
      return n;
    }
    return fibonaci(n-1)+ fibonaci(n-2)
  }
  console.log(fibonaci(6))


  
  
  //22 Unique Path
function countPaths(m, n) {
    let dp = new Array(m);
    for (let i = 0; i < m; i++) {
      dp[i] = new Array(n);
    }
  
    for (let i = 0; i < m; i++) {
      dp[i][0] = 1;
    }
  
    for (let j = 0; j < n; j++) {
      dp[0][j] = 1;
    }
  
    for (let i = 1; i < m; i++) {
      for (let j = 1; j < n; j++) {
        dp[i][j] = dp[i-1][j] + dp[i][j-1];
      }
    }
  
    return dp[m-1][n-1];
  }
  
  console.log(countPaths(3, 3)); // 6
  
  //23 Longest Common Subsequence
function LCS(str1, str2) {
  let m = str1.length;
  let n = str2.length;
  let dp = new Array(m + 1);

  for (let i = 0; i <= m; i++) {
    dp[i] = new Array(n + 1).fill(0);
  }

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (str1[i - 1] === str2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }

  let index = dp[m][n];
  let lcs = new Array(index + 1);
  lcs[index] = "";

  let i = m;
  let j = n;
  while (i > 0 && j > 0) {
    if (str1[i - 1] === str2[j - 1]) {
      lcs[index - 1] = str1[i - 1];
      i--;
      j--;
      index--;
    } else if (dp[i - 1][j] > dp[i][j - 1]) {
      i--;
    } else {
      j--;
    }
  }
  return lcs.join("");
}

console.log(LCS("ABCD", "ACDF")); // ACD



//24 Power Set
function powerSet(set, index, current, result) {
  if (index === set.length) {
    result.push(current.slice());
    return;
  }

  powerSet(set, index + 1, current, result);
  current.push(set[index]);
  powerSet(set, index + 1, current, result);
  current.pop();
}

function getPowerSet(set) {
  let result = [];
  powerSet(set, 0, [], result);
  return result;
}

console.log(getPowerSet([1, 2, 3]));
  // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

  
  


  
 



  
  













 
by

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

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

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.