DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Updated on

Day 13 of 100 - Java: Basic programs

11:00 PM, I started a 25 min timer. Lazily started reading some basic Java examples.

Create an Immutable class

final class Immutable {
  private String name;
  private String number;

  ...
}
Enter fullscreen mode Exit fullscreen mode

ASCII value of a character

char ch = 'b';
int ascii = ch;
Enter fullscreen mode Exit fullscreen mode

Number is odd or even

if (num % 2 == 0)
  //even
else
  // odd
Enter fullscreen mode Exit fullscreen mode

Factorial of a number

int number = 10;
long factorial = 1;
for (int i = 1; i <= num; ++i) {
  factorial *= i;
}
Enter fullscreen mode Exit fullscreen mode

Display alphabets

char c;
for (c = 'A'; c <= 'Z'; ++c)
  System.out.print(c + " ");
Enter fullscreen mode Exit fullscreen mode

Check for prime numbers

int number = 29;
boolean flag = false;

for (int i = 2; i <= number / 2; ++i) {
  if (num % i == 0) {
    flag = true;
    break;
  }
}
Enter fullscreen mode Exit fullscreen mode

GCD using recursion

public static void main(String[] args) {
  int num1 = 366, num2 = 60;
  int hcf = hcf(num1, num2);
}

public static int hcf (int num1, int num2) {
  if (num2 != 0)
    return hcf(num2, num1 % num2);
  else
    return num1;
}
Enter fullscreen mode Exit fullscreen mode

Write a number as sum of two primes

int number = 34;
boolean flag = false;

for (int i = 2; i <= number / 2; ++i) {
  if (checkPrime(i)) {
    if (checkPrime(number -i)) {
      flag = true;
    }
  }
}


static boolean checkPrime(int number) {
  boolean isPrime = true;

  for (int i = 2; i <= number / 2; ++i) {
    if (num % i == 0) {
      isprime = false;
      break;
    }
  }
  return isPrime;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)