Mostrando entradas con la etiqueta JAVA. Mostrar todas las entradas
Mostrando entradas con la etiqueta JAVA. Mostrar todas las entradas

jueves, 5 de marzo de 2026

TOP 10 University Exams Exercises related to Java

Welcome to another coding session at larebelion.com! If you are an IT, Computer Science, or Software Engineering student, you know that facing a Java programming exam can be intimidating.

To help you absolutely crush your next test, we have compiled the ultimate study guide. Below is our "TOP 10 University Exams Exercises related to Java" structured by the 10 most heavily-tested topics globally. To make this the most complete guide on the internet, we’ve expanded these 10 core topics into 52 real exam questions and code solutions extracted from top-tier universities across Spain, the UK, Mexico, Colombia, and the United States.

Grab your favorite IDE, a cup of coffee, and let's get coding!




🇪🇸 SPAIN: Arrays & Matrices

Sources: Universidad Complutense de Madrid (UCM) & Universitat Politècnica de Catalunya (UPC)

1. Sum of Array Elements

int sumArray(int[] arr) { int sum = 0; for(int n : arr) sum += n; return sum; }

2. Find Maximum Value in Array

int maxArray(int[] arr) { int max = arr[0]; for(int n : arr) if(n > max) max = n; return max; }

3. Reverse an Array

void reverse(int[] arr) { for(int i=0; i < arr.length/2; i++) { int temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } }

4. Count Even and Odd Numbers

void countEvenOdd(int[] arr) { int e=0, o=0; for(int n: arr) if(n%2==0) e++; else o++; System.out.println("Even: "+e+", Odd: "+o); }

5. Matrix Addition (2D Arrays)

int[][] add(int[][] a, int[][] b) { int[][] c = new int[a.length][a[0].length]; for(int i=0; i < a.length; i++) for(int j=0; j < a[0].length; j++) c[i][j] = a[i][j] + b[i][j]; return c; }

6. Check Palindrome String

boolean isPalindrome(String s) { return s.equals(new StringBuilder(s).reverse().toString()); }

7. Count Vowels in a String

int countVowels(String s) { return s.replaceAll("[^AEIOUaeiou]", "").length(); }

8. Character Frequency Counter

void charFreq(String s) { int[] freq = new int[256]; for(char c : s.toCharArray()) freq[c]++; }

9. Remove All Whitespaces

String removeSpaces(String s) { return s.replaceAll("\\s", ""); }

10. Check if Two Strings are Anagrams

boolean isAnagram(String s1, String s2) { char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); java.util.Arrays.sort(a1); java.util.Arrays.sort(a2); return java.util.Arrays.equals(a1, a2); }

🇬🇧 UNITED KINGDOM: Object-Oriented Programming (OOP)

Sources: Imperial College London & University of Edinburgh

11. Basic Class & Encapsulation

class Student { private String name; public String getName() { return name; } public void setName(String n) { name = n; } }

12. Inheritance Example

class Animal { void eat() { System.out.println("Eating"); } } class Dog extends Animal { void bark() { System.out.println("Bark"); } }

13. Method Overloading

class MathOp { int add(int a, int b) { return a+b; } double add(double a, double b) { return a+b; } }

14. Method Overriding

class Parent { void show() { System.out.println("Parent"); } } class Child extends Parent { @Override void show() { System.out.println("Child"); } }

15. Abstract Classes

abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } }

16. Interface Implementation

interface Drawable { void draw(); } class Pen implements Drawable { public void draw() { System.out.println("Pen draws"); } }

17. Singly Linked List Node

class Node { int data; Node next; Node(int d) { data = d; next = null; } }

18. Stack Using Array (Push method)

void push(int arr[], int top, int data) { if(top < arr.length-1) arr[++top] = data; }

19. Queue Using Array (Enqueue method)

void enqueue(int arr[], int rear, int data) { if(rear < arr.length) arr[rear++] = data; }

20. Bubble Sort Algorithm

void bubbleSort(int[] arr) { for(int i=0; i < arr.length-1; i++) for(int j=0; j < arr.length-i-1; j++) if(arr[j] > arr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } }

🇲🇽 MEXICO: Math & Logic Fundamentals

Sources: Universidad Nacional Autónoma de México (UNAM) & Tecnológico de Monterrey (ITESM)

21. Factorial of a Number

int factorial(int n) { int fact = 1; for(int i=1; i <= n; i++) fact *= i; return fact; }

22. Fibonacci Sequence up to N

void fibonacci(int n) { int a=0, b=1; for(int i=1; i <= n; i++) { System.out.print(a+" "); int c = a+b; a=b; b=c; } }

23. Prime Number Checker

boolean isPrime(int n) { if(n <= 1) return false; for(int i=2; i <= Math.sqrt(n); i++) if(n%i==0) return false; return true; }

24. Armstrong Number Checker

boolean isArmstrong(int n) { int sum=0, temp=n; while(temp > 0) { int d=temp%10; sum+=d*d*d; temp/=10; } return n==sum; }

25. Greatest Common Divisor (GCD)

int gcd(int a, int b) { while(b != 0) { int temp = b; b = a % b; a = temp; } return a; }

26. Least Common Multiple (LCM)

int lcm(int a, int b) { return (a * b) / gcd(a, b); }

27. Binary to Decimal Conversion

int binaryToDecimal(String binary) { return Integer.parseInt(binary, 2); }

28. Decimal to Binary Conversion

String decimalToBinary(int decimal) { return Integer.toBinaryString(decimal); }

29. Leap Year Checker

boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }

30. Perfect Number Checker

boolean isPerfect(int n) { int sum=0; for(int i=1; i < n; i++) if(n%i==0) sum+=i; return sum==n; }

🇨🇴 COLOMBIA: Recursion & Exception Handling

Sources: Universidad Nacional de Colombia & Universidad de los Andes

31. Recursive Factorial

int recFact(int n) { return (n == 0) ? 1 : n * recFact(n - 1); }

32. Recursive Fibonacci Nth term

int recFib(int n) { return (n <= 1) ? n : recFib(n - 1) + recFib(n - 2); }

33. Sum of Digits using Recursion

int sumDigits(int n) { return n == 0 ? 0 : n % 10 + sumDigits(n / 10); }

34. Power Function using Recursion

int power(int base, int exp) { return exp == 0 ? 1 : base * power(base, exp - 1); }

35. Recursive Binary Search

int binarySearch(int[] arr, int l, int r, int x) { if (r >= l) { int mid = l+(r-l)/2; if(arr[mid]==x) return mid; if(arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; }

36. Try-Catch Division by Zero

void safeDivide(int a, int b) { try { System.out.println(a/b); } catch(ArithmeticException e) { System.out.println("Cannot divide by zero"); } }

37. Array Index Out of Bounds Handling

void safeArrayAccess(int[] arr, int index) { try { System.out.println(arr[index]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Invalid index"); } }

38. Custom Exception Creation

class MyException extends Exception { public MyException(String s) { super(s); } }

39. Throwing a Custom Exception

void validateAge(int age) throws MyException { if(age < 18) throw new MyException("Not eligible"); }

40. Finally Block Execution

void executeFinally() { try { int x = 10/0; } catch(Exception e) { } finally { System.out.println("Always executed"); } }

🇺🇸 UNITED STATES: Advanced Java Concepts & Collections

Sources: Massachusetts Institute of Technology (MIT) & Stanford University

41. Iterate over a HashMap

void printMap(java.util.Map<Integer, String> map) { for(java.util.Map.Entry<Integer, String> entry : map.entrySet()) System.out.println(entry.getKey() + " " + entry.getValue()); }

42. Remove Duplicates using HashSet

java.util.Set<Integer> removeDups(java.util.List<Integer> list) { return new java.util.HashSet<>(list); }

43. Create a Thread by Extending Thread class

class MyThread extends Thread { public void run() { System.out.println("Thread running"); } }

44. Create a Thread using Runnable Interface

class MyRunnable implements Runnable { public void run() { System.out.println("Runnable running"); } }

45. Singleton Design Pattern

class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if(instance==null) instance = new Singleton(); return instance; } }

46. Java 8 Lambda Expression (List Iteration)

void lambdaIterate(java.util.List<String> list) { list.forEach(item -> System.out.println(item)); }

47. Java 8 Streams: Filter Even Numbers

java.util.List<Integer> filterEven(java.util.List<Integer> list) { return list.stream().filter(n -> n%2==0).collect(java.util.stream.Collectors.toList()); }

48. Find Second Largest Element in Array

int secondLargest(int[] arr) { java.util.Arrays.sort(arr); return arr[arr.length-2]; }

49. Find First Non-Repeating Character in a String

char firstNonRepeating(String s) { for(char c : s.toCharArray()) if(s.indexOf(c) == s.lastIndexOf(c)) return c; return '_'; }

50. Validate Email using Regular Expressions (Regex)

boolean isValidEmail(String email) { return email.matches("^[A-Za-z0-9+_.-]+@(.+)$"); }

🎁 BONUS: EXTRA EXAM CHALLENGES!

Because at larebelion.com we want you to be over-prepared, here are two bonus classic questions!

51. Merge Two Sorted Arrays

int[] merge(int[] a, int[] b) { int[] c = new int[a.length + b.length]; int i=0, j=0, k=0; while(i < a.length && j < b.length) c[k++] = a[i] < b[j] ? a[i++] : b[j++]; while(i < a.length) c[k++] = a[i++]; while(j < b.length) c[k++] = b[j++]; return c; }

52. Check if an Array is Sorted

boolean isSorted(int[] arr) { for(int i=0; i < arr.length-1; i++) if(arr[i] > arr[i+1]) return false; return true; }

Final Thoughts for Students

Practice makes perfect. Don't just copy and paste these snippets! Write them out in your IDE, break them, debug them, and understand why they work. By mastering these 52 exercises covering Arrays, OOP, Recursion, Exceptions, and Collections, you will be prepared to tackle virtually any undergraduate Java exam.

Make sure to bookmark this post for your finals week, and let us know in the comments below at larebelion.com which exercise was the hardest for you! Happy coding!

viernes, 20 de febrero de 2026

Minecraft Java Adios OpenGL Hola Vulkan

¡Atención, jugadores de Minecraft Java! Prepárense para una gran actualización que cambiará la forma en que el juego se ve y se ejecuta. Mojang ha anunciado que la edición Java de Minecraft dará un salto tecnológico significativo al reemplazar su antiguo motor gráfico, OpenGL, por el más moderno y potente Vulkan. Este cambio, que llegará con la próxima actualización 'Vibrant Visuals', promete mejorar el rendimiento y desbloquear nuevas capacidades gráficas, especialmente en sistemas como Linux y macOS, donde Vulkan ofrece ventajas notables incluso a través de capas de traducción.

Minecraft Java Adios OpenGL Hola Vulkan

Este movimiento hacia Vulkan no solo beneficiará a los jugadores en términos de fluidez y calidad visual, sino que también representa un desafío y una oportunidad para la comunidad de modding. Mojang ha emitido una llamada a los creadores de mods para que comiencen a prepararse para esta transición, sugiriendo que migrar de OpenGL a Vulkan requerirá un esfuerzo considerable. La recomendación principal es empezar a distanciarse del uso directo de OpenGL en los mods y, siempre que sea posible, aprovechar las APIs de renderizado internas del juego. Para aquellos cuyas necesidades no se cubran con esto, Mojang se muestra abierto a la comunicación para colaborar.

Es importante tener en cuenta que esta actualización podría dejar fuera a los jugadores con hardware muy antiguo que no soporte Vulkan. Sin embargo, el soporte para Vulkan se remonta a GPUs bastante antiguas, por lo que la mayoría de los jugadores activos no deberían tener problemas. La transición se realizará gradualmente: Vulkan se implementará junto a OpenGL en las versiones de prueba (snapshots) durante el verano, permitiendo a los usuarios alternar entre ambos. Una vez que Mojang considere que el rendimiento y la estabilidad de Vulkan son óptimos, OpenGL será eliminado por completo, marcando el fin de una era y el comienzo de una experiencia visual más avanzada en Minecraft Java.

Fuente Original: https://developers.slashdot.org/story/26/02/19/2156234/minecraft-java-is-switching-from-opengl-to-vulkan?utm_source=rss1.0mainlinkanon&amp;utm_medium=feed

Artículos relacionados de LaRebelión:

Artículo generado mediante LaRebelionBOT

lunes, 14 de julio de 2025

¿Sobrevivirán los Programadores a la Era de la IA? Desmitificando el Futuro de la Informática

 En un panorama tecnológico dominado por la inteligencia artificial, muchos se preguntan si las carreras en informática están destinadas a la obsolescencia. Sin embargo, este artículo argumenta que la realidad es mucho más compleja y que, lejos de desaparecer, la informática se vuelve aún más crucial en este nuevo mundo.

El autor desafía la idea popular de que la IA reemplazará a los informáticos, señalando que esta visión a menudo proviene de fuera del sector. Si bien la IA puede automatizar ciertas tareas, como la escritura de código, la informática abarca un espectro mucho más amplio que incluye la arquitectura de sistemas, el diseño de infraestructuras digitales, la ciberseguridad, la verificación de sistemas y la creación de nuevos lenguajes de programación. Estas áreas requieren un razonamiento y una comprensión contextual que la IA actual no posee.

La IA debe ser vista como una herramienta que aumenta la productividad de los informáticos, no como un sustituto. Puede ayudar a resumir información y generar contenido, pero carece de la capacidad de diagnosticar interrupciones complejas, reescribir código para tecnologías emergentes o diseñar infraestructuras críticas.

El artículo destaca diez tareas específicas donde la IA no puede reemplazar a los humanos sin una supervisión altamente especializada, incluyendo la adaptación de algoritmos financieros, la creación de arquitecturas energéticamente eficientes, la auditoría de sistemas médicos basados en IA, el diseño de plataformas para validar correos electrónicos, el desarrollo de la próxima generación de IA segura y ética.

La informática está en constante evolución, y la IA depende de ella para su propio desarrollo. En lugar de desalentar a las nuevas generaciones, es crucial fomentar su formación en informática, ya que el conocimiento técnico sigue siendo la clave para construir, controlar y mejorar el mundo digital que nos rodea. Al igual que durante la Revolución Industrial, quienes entiendan y dominen la tecnología tendrán un futuro asegurado.

Vibe coding o cómo crear una app sin tener ni idea de programación:  ¿alucinación de

Lecturas Relacionadas:

Fuente Original:

Fuente Original: https://es.gizmodo.com/lo-que-muchos-no-te-cuentan-sobre-la-ia-y-la-informatica-por-que-el-futuro-aun-necesita-programadores-2000179455 

sábado, 25 de noviembre de 2023

What is the tech stack for the shortern future?

Predicting the exact technology stack for the future can be challenging because technology evolves rapidly, and new innovations constantly emerge. However, there are some trends and technologies that have been gaining traction and are likely to play a significant role in the tech stacks of the future. Keep in mind that the specific stack you choose will depend on your project's requirements and goals. Here are some key trends and technologies to consider:


  • Cloud Computing: Cloud platforms like Amazon Web Services (AWS), Microsoft Azure, and Google Cloud are expected to continue dominating the cloud computing landscape. Serverless computing and containerization (using technologies like Docker and Kubernetes) will likely become even more important for scalability and efficiency.

  • Edge Computing: As IoT devices become more prevalent, edge computing will grow in importance. This involves processing data closer to the source (i.e., the "edge" of the network) to reduce latency and improve real-time decision-making.

  • Artificial Intelligence (AI) and Machine Learning (ML): AI and ML will continue to be integrated into various applications and services. Frameworks like TensorFlow and PyTorch will remain important, and AI/ML models will be increasingly deployed at the edge for faster processing.

  • Blockchain: While blockchain technology is primarily associated with cryptocurrencies like Bitcoin, it has applications beyond finance, such as supply chain management, voting systems, and more. Blockchain platforms like Ethereum and Hyperledger are likely to see continued development and adoption.

  • Quantum Computing: Quantum computing is still in its infancy, but it holds great promise for solving complex problems that are currently beyond the capabilities of classical computers. Companies like IBM and Google are actively working on quantum computing research.

  • 5G Technology: The rollout of 5G networks will enable faster and more reliable wireless connectivity. This will impact various industries, including IoT, autonomous vehicles, augmented reality, and virtual reality.

  • Cybersecurity: With the increasing importance of digital data and connectivity, cybersecurity will remain a top concern. Technologies like AI-driven threat detection, zero-trust security models, and encryption will continue to evolve.

  • Web Technologies: JavaScript, HTML, and CSS will remain fundamental for web development, but frameworks like React, Angular, and Vue.js are likely to continue their popularity. Progressive Web Apps (PWAs) and WebAssembly are also promising technologies.

  • DevOps and Automation: DevOps practices, along with tools like Jenkins, Docker, and Ansible, will continue to streamline development, deployment, and operations processes. Automation will be critical for efficiency and reliability.

  • Sustainability: Sustainability considerations will play a larger role in tech stacks. Energy-efficient hardware, green data centers, and eco-friendly software development practices will become more important.

  • AR/VR: Augmented reality (AR) and virtual reality (VR) technologies will continue to advance, with applications in gaming, education, healthcare, and more.

  • Natural Language Processing (NLP): NLP technologies like GPT-4 and beyond will enable more sophisticated conversational AI, language translation, and content generation.

  • Container Orchestration: Technologies like Kubernetes and Docker Swarm will remain crucial for managing and scaling containerized applications.



It's essential to stay up-to-date with emerging technologies and adapt your tech stack based on your project's specific needs and the evolving industry trends. Flexibility and a willingness to learn and experiment will be valuable skills for technology professionals in the future. 

viernes, 27 de octubre de 2023

JAVA: ¿Porque nos hacen aprender JAVA en la Universidad?

 Aprender Java es importante por varias razones:

  1. Amplia demanda laboral: Java es uno de los lenguajes de programación más populares y ampliamente utilizados en la industria de la tecnología. Muchas empresas buscan desarrolladores de Java, lo que significa que hay una gran demanda laboral en este campo. Aprender Java puede abrirte puertas en el mercado laboral y aumentar tus oportunidades de empleo.
  2. Versatilidad: Java se utiliza en una amplia variedad de aplicaciones, desde desarrollo web hasta aplicaciones móviles, sistemas embebidos, aplicaciones de escritorio y más. Esto significa que puedes aplicar tus conocimientos de Java en una variedad de proyectos y contextos.
  3. Plataforma independiente: Java es conocido por su capacidad de ser ejecutado en múltiples plataformas. Esto se debe a la máquina virtual Java (JVM), que permite que el código Java se ejecute en diferentes sistemas operativos sin necesidad de modificaciones importantes. Esto lo hace ideal para aplicaciones empresariales que deben ser compatibles con diversas plataformas.
  4. Comunidad y recursos: Java tiene una gran comunidad de desarrolladores y una amplia cantidad de recursos de aprendizaje disponibles en línea, como tutoriales, documentación oficial y foros de discusión. Esto facilita el proceso de aprendizaje y resolución de problemas.
  5. Seguridad y robustez: Java está diseñado con un enfoque en la seguridad y la robustez. Tiene características que ayudan a prevenir vulnerabilidades comunes de seguridad y a gestionar eficazmente la memoria, lo que reduce la posibilidad de errores graves en el código.
  6. Orientación a objetos: Java es un lenguaje orientado a objetos, lo que significa que se basa en un modelo de programación que se asemeja a cómo pensamos y organizamos conceptos en el mundo real. Esto facilita la creación de software modular y mantenible.
  7. Frameworks y bibliotecas: Java cuenta con una amplia variedad de frameworks y bibliotecas que simplifican el desarrollo de aplicaciones en diferentes dominios, como Spring para desarrollo web, Android para aplicaciones móviles y Hibernate para acceso a bases de datos, entre otros.
  8. Carrera a largo plazo: Aprender Java puede proporcionarte una base sólida para tu carrera en el desarrollo de software. A medida que adquieras experiencia, podrás especializarte en áreas específicas de desarrollo, como el desarrollo web, la inteligencia artificial o el desarrollo de aplicaciones móviles, todo mientras sigues utilizando Java como base.

Random r1 = new Random();
Random r2 = new Random(47);
Random r3 = new Random(47); // r2 y r3 darán la misma secuencia.
  
int n1 = r1.nextInt();
int n2 = r2.nextInt(10); // número aleatorio entre 0 y 9 (el 10 es exclusive)
int n3 = r3.nextInt(10); // obtendremos el mismo número aleatorio que n2, ya que ambos usan la misma semilla
  
System.out.println("n1: " + n1);
System.out.println("n2: " + n2);
System.out.println("n3: " + n3);


En resumen, aprender Java es importante debido a su amplia demanda en el mercado laboral, su versatilidad, su capacidad de ser utilizado en diversas plataformas y su sólida comunidad de desarrollo. Ya sea que estés buscando una carrera en programación o quieras expandir tus habilidades en el desarrollo de software, Java es un lenguaje que vale la pena aprender.




viernes, 29 de septiembre de 2023

Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 2)

 Como continuación del artículo "Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 1)", aqui publico la Parte 2 del artículo que no es más que una continuación con otros 20 ejercicios prácticos para que pongais en juego lo aprendido en la universidad o vuestros cursos de programación de Java.



Ejercicio 21: Programa Java de búsqueda lineal

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {4,2,7,1,8,3,6};
    int flag = 0;
    
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    
    for(int i=0;i<numbers.length;i++){
      if (x==numbers[i]){
        System.out.println("Successful search, the element is found at position "+ i);
        flag = 1;
        break;
      }
    }

    if(flag==0){
      System.out.println("Oops! Search unsuccessful");
    }
    
  }
}


Ejercicio 22: Programa Java de búsqueda binaria

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    int result = binarySearch(numbers, 0, numbers.length-1, x);
    if (result != -1)
      System.out.println("Search successful, element found at position "+result);
    else
      System.out.println("The given element is not present in the array");
    
  }

  public static int binarySearch(int[] numbers,int low,int high,int x){
    if (high >= low){
      int mid = low + (high - low)/2;
      if (numbers[mid] == x)
        return mid;
      else if (numbers[mid] > x)
        return binarySearch(numbers, low, mid-1, x);
      else
        return binarySearch(numbers, mid+1, high, x);
    }else{
      return -1;
    }
        
        
  }
}


Ejercicio 23: Programa Java para encontrar el número de números impares en una matriz

class Main {
  public static void main(String[] args) {

    int[] numbers = {8,3,1,6,2,4,5,9};
    int count = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]%2!=0)
        count++;
    }
   System.out.println("The number of odd numbers in the list are: "+count);      
        
  }
}


Ejercicio 24: Programa Java para encontrar el mayor número de una matriz sin utilizar funciones incorporadas

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,8,1,7,2,9,5,4};
    int largest = numbers[0];
    int position = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]>largest){
        largest = numbers[i];
        position = i;
      }
    }

   System.out.println("The largest element is "+largest+" which is found at position "+position);      
        
  }
}


Ejercicio 25: Programa Java para insertar un número en cualquier posición de una matriz

import java.util.Scanner;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,4,1,9,6,2,8};
    System.out.println(Arrays.toString(numbers));

    System.out.println("Enter the number to be inserted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the position: ");
    int y = Integer.parseInt(sc.nextLine());

    for(int i=numbers.length-1;i>y;i--){
        numbers[i] = numbers[i-1];
    }
    numbers[y] = x;

   System.out.println(Arrays.toString(numbers));   
        
  }
}


Ejercicio 26: Programa Java para borrar un elemento de un array por índice

import java.util.Scanner;
import java.util.Arrays;

import java.util.ArrayList; 

class Main {
  public static void main(String[] args) {

    ArrayList<Integer> numbers = new ArrayList<Integer>(5); 
    numbers.add(3);
    numbers.add(7);
    numbers.add(1);
    numbers.add(4);
    
    System.out.println(numbers);

    System.out.println("Enter the position of the element to be deleted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    numbers.remove(x);

   System.out.println(numbers);   
        
  }
}


Ejercicio 27: Programa Java para comprobar si una cadena es un palíndromo o no

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    String a, b = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the string you want to check: ");
    a = s.nextLine();
    
    int n = a.length();
    for(int i = n - 1; i >= 0; i--){
        b = b + a.charAt(i);
    }
    
    if(a.equalsIgnoreCase(b)){
      System.out.println("The string is a palindrome.");
    }else{
      System.out.println("The string is not a palindrome.");
    }
    
  }
}


Ejercicio 28: Programa Java para la suma de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the sum of two matrices    
    int c[][]=new int[3][3];  //3 rows and 3 columns  
    
    //adding 2 matrices    
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=a[i][j]+b[i][j];
        System.out.print(c[i][j]+" ");    
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 29: Programa Java para la multiplicación de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the product of two matrices    
    int c[][]=new int[3][3];
    
    //multiplying 2 matrices
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=0;      
        for(int k=0;k<3;k++){      
          c[i][j]+=a[i][k]*b[k][j];      
        }
        System.out.print(c[i][j]+" ");
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 30: Programa Java para comprobar el año bisiesto

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the year you want to check: ");
    int year = Integer.parseInt(sc.nextLine()); 
    boolean leap = false;
    
    // if the year is divided by 4
    if (year % 4 == 0) {
      // if the year is century
      if (year % 100 == 0) {
        // if year is divided by 400, then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      // if the year is not century
      else
        leap = true;
    }
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
    
  }
}


Ejercicio 31: Programa Java para hallar el enésimo término de una serie de Fibonacci mediante recursión

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {
    Scanner cs=new Scanner(System.in);
    int n;
		System.out.print("Enter the position(N): ");
		n=cs.nextInt();
		System.out.print("Nth Fibonacci Number is: "+NthFibonacciNumber(n));
  }

  static int NthFibonacciNumber(int n){
	    if(n==1)
	        return 0;
	    else if(n==2)
	        return 1;
	    else
	        return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2);
	}
  
}


Ejercicio 32: Programa Java para imprimir series Fibonacci usando iteración

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int n1=0,n2=1;
    Scanner cs=new Scanner(System.in);
		System.out.print("Enter the number of terms in the sequence: ");
		int count = cs.nextInt(); 
    int n3,i;
    
    System.out.print(n1+" "+n2);//printing 0 and 1
    //printing from 2 because 0 and 1 are already printed  
    for(i=2;i<count;++i){
      n3=n1+n2;    
      System.out.print(" "+n3);    
      n1=n2;    
      n2=n3;
      }    
	
    }
}


Ejercicio 33: Programa Java para implementar una calculadora que realice operaciones básicas

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
      int firstNumber, secondNumber, opt, add, sub, mul;
      double div;
      Scanner s = new Scanner(System.in);
      System.out.print("Enter first number: ");
      firstNumber = s.nextInt();
      System.out.print("Enter second number: ");
      secondNumber = s.nextInt();
      
      while(true){
        System.out.println("Enter 1 for addition");
        System.out.println("Enter 2 for subtraction");
        System.out.println("Enter 3 for multiplication");
        System.out.println("Enter 4 for division");
        System.out.println("Enter 5 to Exit");
        int option = s.nextInt();
        switch(option){
          case 1:
            add = firstNumber + secondNumber;
            System.out.println("Result:"+add);
            break;
 
          case 2:
            sub = firstNumber - secondNumber;
            System.out.println("Result:"+sub);
            break;
 
          case 3:
            mul = firstNumber * secondNumber;
            System.out.println("Result:"+mul);
            break;
 
          case 4:
            div = (double)firstNumber / secondNumber;
            System.out.println("Result:"+div);
            break;    
 
          case 5:
            System.exit(0);
            
            }
        }
	
    }
}


Ejercicio 34: Programa Java para encontrar tu peso en Marte

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.print("How many pounds (lbs) do you weigh? ") ;
  float weight = input.nextFloat();

  // computing the weight on mars
  double weightOnMars = (weight * .38);

  // displaying results with 4 decimal places
  System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on Mars");

    System.out.println("Converting the variable into integer");
    int weightOnMarsInt = (int)weightOnMars;
    System.out.println(weightOnMarsInt);

    System.out.println("Converting the variable into char");
    char weightOnMarsChar = (char)weightOnMars;
    System.out.println(weightOnMarsChar);

    System.out.println("Converting the variable into Int and doing an operation on it");
    int newIntVariable = weightOnMarsChar * 2;
    System.out.println(newIntVariable);
    
  }
}


Ejercicio 35: Programa Java para comprobar si el número aleatorio generado es par o impar

import java.util.Random;

class Main {
  public static void main(String[] args) {

    int min = 1;
    int max = 100;

    //Generating a random number
    Random r = new Random();
    int randomNumber = min + r.nextInt(max);
    System.out.println("Generated random number is: "+randomNumber);

    //Checking whether the number is odd or even

    if(randomNumber%2==0){
      System.out.println("The generated random number is even.");
    }else{
      System.out.println("The generated random number is odd.");
    }
        
  }
}


Ejercicio 36: Programa Java para calcular el número de contenedores necesarios

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("How many Lego bricks do we have? Choose an odd number between 50 and 100: ");
    int amountOfBricks = Integer.parseInt(sc.nextLine());

    System.out.println("How many Lego blocks fit in one container? Choose an even number between 5 and 10: ");
    int containerCapacity = Integer.parseInt(sc.nextLine());

    int noOfFullContainers = amountOfBricks/containerCapacity;
    int noOfTotalContainers;

    int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;

    if(noOfBlocksInNotFullContainers!=0){
      noOfTotalContainers = noOfFullContainers + 1;
    }else{
      noOfTotalContainers = noOfFullContainers;
    }
    
    System.out.println("No of full containers we have: "+noOfFullContainers);
    System.out.println("No of total containers we have: "+noOfTotalContainers);
    System.out.println("No of blocks in the container that is not completely full: "+noOfBlocksInNotFullContainers);
        
  }
}


Ejercicio 37: Programa Java para calcular impuestos

import java.math.BigDecimal;    

class Main {
  public static void main(String[] args) {

    double netValue = 9.99;
    double VAT = 23.0;

    //calculating grossValue
    double grossValue = netValue + (VAT*netValue/100);
    System.out.println("The gross value is: "+grossValue);

    // multiplying the value by 10000
    double grossValue10000 = grossValue * 10000;
    System.out.println("The gross value for 10000 units is: "+grossValue10000);

    // calculating price excluding VAT 23%
    double excludingVAT = grossValue10000 - (VAT*grossValue10000/100);
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT);

    // doing the same operations using BigDecimal instead of double
     System.out.println("\n----Using BigDecimal instead of double----\n");
       
    BigDecimal netValue_big = new BigDecimal("9.99");
    BigDecimal VAT_big = new BigDecimal("23.0");
    BigDecimal HUNDRED = new BigDecimal("100");
    BigDecimal TenThousand = new BigDecimal("10000");

    //calculating grossValue
    BigDecimal grossValue_big = netValue_big.add(VAT_big.multiply(netValue_big.divide(HUNDRED)));
    System.out.println("The gross value is: "+grossValue_big);
    
    // multiplying the value by 10000
    BigDecimal grossValue10000_big = grossValue_big.multiply(TenThousand);
    System.out.println("The gross value for 10000 units is: "+grossValue10000_big);
    
    // calculating price excluding VAT 23%
    BigDecimal excludingVAT_big = grossValue10000_big.subtract(VAT_big.multiply(grossValue10000_big.divide(HUNDRED)));
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT_big);


  System.out.println("\nThe accuracy is higher when we use BigDecimal instead of double");
    
  }
}


Ejercicio 38: Calcular el IMC con Java

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    float height, weight, bmi;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the height (in inches): ");
    height = s.nextFloat();
    System.out.println("Enter the weight (in pounds): ");
    weight = s.nextFloat();
    bmi = (float)(weight / Math.pow(height, 2) * 703);

    System.out.println("The BMI is: "+bmi);

    if(bmi<16.00)
      System.out.println("starvation");
    else if(bmi>=16.00 && bmi <= 16.99)
      System.out.println("emaciation");
    else if(bmi>=17.00 && bmi <= 18.49)
      System.out.println("underweight");
    else if(bmi>=18.50 && bmi<=22.99)
      System.out.println("normal, low range");
    else if(bmi>=23.00 && bmi<=24.99)
      System.out.println("normal, high range");
    else if(bmi>=25.00 && bmi<=27.49)
      System.out.println("overweight, low range");
    else if(bmi>=27.50 && bmi<=29.99)
      System.out.println("overweight, high range");
    else if(bmi>=30.00 && bmi<=34.9)
      System.out.println("1st degree obesity");
    else if(bmi>=35.00 && bmi<=39.90)
      System.out.println("2nd degree obesity");
    else
      System.out.println("3rd degree obesity");
  
    }
}


Ejercicio 39: Programa Java para hallar la suma de números pares

class Main {
  public static void main(String[] args) {
      int sum=0;
    
      for(int i=1;i<=100;i++){
        if(i%2==0){
          sum = sum + i;
        }
      }

      System.out.println("The sum of even numbers from 1-100 is: "+sum);
    
    }
}


Ejercicio 40: Programa Java para encontrar los números más grandes y más pequeños a partir de números aleatorios

import java.util.Random;

class Main {
  public static void main(String[] args) {
    int min = 1, max=100;
    int largest=0;
    int smallest=100;
    int i = 1;
    
    while(i<=10){
      //Generating a random number
      Random r = new Random();
      int randomNumber = min + r.nextInt(max);
      System.out.println("Generated random number is: "+randomNumber);
      if(randomNumber>largest){
        largest = randomNumber;
      }
      if(randomNumber<smallest){
        smallest = randomNumber;
      }
      i++;
    }
    
    System.out.println("\n");
    System.out.println("The smallest number is: "+smallest);
    System.out.println("The largest number is: "+largest);
    
  }
}