Compilition of Java Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Compilations of Java Programs

Jonathan D Wong

Table of contents
1. For loop
2. While loop
3. Do while loop
4. If statement
5. If else statement
6. Concatenate
7. Number methods
8. Array sort
9. Comparison
10. Switch statement
Java program 1
1. Display a Text Five Times
public class Main {
public static void main (String[] args) {

int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println("Java is fun");
}
}
}

Output: Java is fun


Java is fun
Java is fun
Java is fun
Java is fun

2. Display Sum of Natural Numbers


public class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1000;

for (int i = 1; i <= n; ++i) {


sum += i; // sum = sum + i
}
System.out.println ("Sum = " + sum);
}
}
Output: Sum = 500500

3. The sum of numbers


public class SumOfNumbers
{
public static void main(String arg[])
{
int input = 6;
int sum = 0;

for(int i = 1; i <= input; i++)


{
sum = sum + i;
System.out.println("Sum after adding " + i + " is : " + sum);
}

System.out.println();
System.out.println("Sum of numbers till " + input + " is " + sum);

}
}

Output: Sum after adding 1 is: 1


Sum after adding 2 is: 3
Sum after adding 3 is: 6
Sum after adding 4 is: 10
Sum after adding 5 is: 15
Sum after adding 6 is: 21
Sum of numbers till 6 is 21

Java program 2
1. Find the midpoint of two number
public class Main {
public static void main(String args[]) {
int i, j;
i = 10;
j = 20;

while (++i < --j);

System.out.println("Midpoint is " + i);


}
}
Output: Midpoint is 15
2. Execute the code block for each of the element in the
array
public class main {

public static void main(String[] args) {


String[] phones = {"Apple", "Android", "Xiaomi", "Lenovo"};
int i = 0;

while(i<phones.length) {
System.out.println("I have "+phones[i] + " smartphone.");
i++;
}
}
}
Output: I have Apple smartphone.
I have Android smartphone.
I have Xiaomi smartphone.
I have Lenovo smartphone.

3. Compute the sum of positive numbers only

import java.util.Scanner;

public class Main {


public static void main(String[] args) {

int sum = 0;

Scanner input = new Scanner(System.in);


System.out.println("Enter a number:");
int number = input.nextInt();

while (number >= 0) {

sum += number;

System.out.println("Enter a number:");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output: Enter a number: 25
Enter a number: 9
Enter a number: 5
Enter a number: -3
Sum = 39

Java program 3
1. Print even numbers between 1 to 20
public class main {
     public static void main(String[] args) {
    int i=1;
    System.out.println("Even numbers between 1 to 20:");
    do{
     if(i%2==0)
      {
      System.out.println(i);
       }
      i++;
      while(i<=20);
}
}
Output: Even numbers between 1 to 20:

2
4
6
8
10
12
14
16
18
20

2. User input numbers and get the total


import java.util.Scanner;
public class main
{
public static void main(String[] args)
{
int number, total = 0;
Scanner sc = new Scanner(System.in);
do{
System.out.println("Please enter number: ");
number = sc.nextInt();
total += number;
}while (number != 0);
System.out.println("Total = " + total);
sc.close();
}
}

Output: Please enter number: 5

Please enter number: 1


Please enter number: 9
Please enter number: 4
Please enter number: 2
Please enter number: 9
Please enter number: 4
Total = 34

3. Display maximum number


import java.util.Scanner;
public class main
{
public static void main(String[] args)
{
int counter;
int number;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter maximum number: ");
number = sc.nextInt();
counter = 1;
do{
System.out.println(counter + " ");
counter++;
}while(counter <= number);
sc.close();
}
}

Output: Please enter maximum number: 50


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Java program 4

1. Comparison of two numbers


import java.util.Scanner;
public class main
{
public static void main(String args[])
{
int b,c;
Scanner scnr = new Scanner(System.in);
System.out.println("b is: ");
b=scnr.nextInt();
System.out.println("c is: ");
c=scnr.nextInt();
if (b > c)
{
System.out.println("b is greater than c");
}
System.out.println("The comparison of two numbers");
}
}

Output: b is: 6
c is: 4
b is greater than c
The comparison of two numbers

2. Determine the grade


public class main {
public static void main(String args[]){
int marks=67;
if (marks>=60){//evaluate test expression
System.out.print("Your grade is B");
}
}
}

Output: Your grade is B

3. Determine positive number


public class main {

public static void main(String[] args) {


int a = 99;
if (a > 0) {
System.out.println("Positive number");
}
}
}
Output: Positive number
Java program 5

1. Determine the largest number


import java.util.Scanner;
public class main
{
public static void main(String args[])
{
int a,b;
Scanner scnr = new Scanner(System.in);
System.out.println("a is: ");
a=scnr.nextInt();
System.out.println("b is: ");
b=scnr.nextInt();
if (a > b)
{
System.out.println("a is largest number");
}
else
{
System.out.println("b is largest number");
}
}
}

Output: a is: 5
b is: 6
b is the largest number

2. Determine the voting age


public class main {
public static void main(String args[]){
int age=20;
if(age<18)
{
System.out.println("You can’t vote");
}
else{
System.out.println("You can vote");
}
}
}

Output: You can vote

3. Determine if pass or fail


import java.util.Scanner;
public class main {
public static void main(String[] args) {
int a;
Scanner scnr = new Scanner(System.in);
System.out.println("Student: ");
a=scnr.nextInt();
if (a>=74) {
System.out.println("You are passed the exam! Congratulation");
} else {
System.out.println("Sorry! you are failed in exam.");
}
}
}

Output: Student: 79
You are passed the exam! Congratulation

Java program 6
1. Merging two array using concatenate
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array1 = {
1,
2,
3,
4
};
int[] array2 = {
5,
6,
7,
8
};
int length = array1.length + array2.length;
System.out.println("First Array is: ");
for (int i = 0; i < array1.length; i++) {
System.out.print(" " + array1[i]);
}
System.out.println(" ");
System.out.println("Second Array is: ");
for (int i = 0; i < array2.length; i++) {
System.out.print(" " + array2[i]);
}

int[] result = new int[length];


int position = 0;

for (int element: array1) {


result[position] = element;
position++;
}
for (int element: array2) {
result[position] = element;
position++;
}
System.out.println("\nThe resulting array after merging two arrays is: ");
System.out.println(Arrays.toString(result));
}
}
Output: First Array is:
1234
Second Array is:
5678
The resulting array after merging two arrays is: [1, 2, 3, 4, 5, 6, 7, 8]

2. Combining two array using concatenate


import java.util. * ;
public class MergeArrayExample4 {
public static void maiin(String args[]) {
String str1[] = {
"T",
"E",
"C",
"H"
};
String str2[] = {
"V",
"I",
"D",
"V",
"A",
"N"
};
System.out.print("The first array is:");
for (int i = 0; i < str1.length; i++) {
System.out.print(" " + str1[i]);
}
System.out.print("\nThe second array is:");
for (int i = 0; i < str2.length; i++) {
System.out.print(" " + str2[i]);
}

List list = new ArrayList(Arrays.asList(str1));


list.addAll(Arrays.asList(str2));
Object[] str3 = list.toArray();
Systemi.out.print("\nThe merged array is: ");
System.oiut.println(Arrays.toString(str3));

}
}

Output: The first array is: T E C H


The second array is: V I D V A N
The merged array is: [T, E, C, H, V, I, D, V, A, N]

3. Combining words using concatenate


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

String s4 = "Jonathan" + " " + "D" + " " + "Wong";i


String s1 = s4;
s4 += " " + "Bsit" + " " + "4th" + " " + "year";

System.out.println(s4);

}
}

Output: Jonathan D Wong Bsit 4th year

Java program 7
1. The methods that add two numbers
public class Main {
public int addNumbers(int a, int b) {
int sum = a + b;

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

int num1 = 25;


int num2 = 15;

Main obj = new Main();

int result = obj.addNumbers(num1, num2);


System.out.println("Sum is: " + result);
}
}

Output: 40
2. The method takes a number as its parameter and
returns the square of the number.
public class main {
public static int square(int num) {

return num * num;


}

public static void main(String[] args) {


int result;
result = square(10);

System.out.println("Squared value of 10 is: " + result);


}
}

Output: Squared value of 10 is: 100


3. Calculate the square of a number
public class Main {
private static int getSquare(int x){
return x * x;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
int result = getSquare(i);
System.out.println("Square of " + i + " is: " + result);
}
}
}

Output: Square of 1 is: 1

Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25

Java program 8
1. Array elements in ascending order
import java.util.Scanner;
public class main
{
public static void main(String[] args)
{
int count, temp;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();
int num[] = new int[count];
System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.oiut.print(num[count - 1]);
}
}

Output: Enter number of elements you want in the array: 5


Enter array elements: 90
-20
8
11
3
Array Elements in Ascending Order : -20, 3, 8, 11, 90

2. Array elements in descending order


import java.util.Arrays;
import java.util.Collections;

public class Main


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

Integer[] IntArray = {52, 45, 32, 64, 12, 87, 78, 98, 23, 7};

System.out.printf("Original Array: %s",


Arrays.toString(IntArray));
Arrays.sort(IntArray, Collections.reverseOrder());

System.out.printf("\n\nSorted Array: %s",


Arrays.toString(IntArray));
}
}
Output: Original Array: [52, 45, 32, 64, 12, 87, 78, 98, 23, 7]

Sorted Array: [98, 87, 78, 64, 52, 45, 32, 23, 12, 7]
3. Sort array numbers in random order
import java.util.Arrays;
import java.util.Random;
public class ShuffleArray {
public static void main(String[] args) {

int[] array = { 1, 2, 3, 4, 5, 6, 7 };

Random rand = new Random();

for (int i = 0; i < array.length; i++) {


int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array[i];
array[i] = temp;
}
System.out.println(Arrays.toString(array));
}
}

Output: [6, 4, 2, 1, 5, 3, 7]
Java program 9
1. Compare two strings using equals
public class main {
public static void main(String[] args) {

String style = "Bold";


String style2 = "Bold";

if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

Output: Equal

2. Comparing two numbers

public class main{


public static void main(String[] args) {
int a=24, b=25;
if (a == b){
System.out.println("Both are equal");
}
else if(a>b){
System.out.println("a is greater than b");
}
else{
System.out.println("b is greater than a");
}
}
}

Output: b is greater than a

3. Compare two list, find the common item


public class main{
public static void main(String[] args) {
ArrayList<Integer> listOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

ArrayList<Integer> listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7));

listOne.retainiAll(listTwo);

System.out.println("Common items in both lists " + listOne);


}
}

Output: Common items in both lists [1, 2, 4, 5]

Java program 10
1. Used the switch statement to find the size

public class main{


public static void main(String[] args) {
int number = 44;
String size;

switch (number) {

case 29:
size = "Small";
break;

case 42:
size = "Medium";
break;

case 44:
size = "Large";
break;

case 48:
size = "Extra Large";
break;

default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}

Output: Size: Large

2. Making Calculator using the switch statement


import java.util.Scanner;

public class main {


public static void main(String[] args) {

char operator;
Double number1, number2, result;

Scanner input = new Scanner(System.in);

System.out.print("Choose an operator: +, -, *, or /: ");


operator = input.next().charAt(0);

System.out.print("Enter first number: ");


number1 = input.nextDouble();

System.out.println("Enter second number: ");


number2 = input.nextDouble();

switch (operator) {

case '+':
result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;

case '-':
result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break;

case '*':
result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}

input.close();
}
}

Output: Choose an operator: +, -, *, or /: +

Enter first number: 23


Enter second number: 21
23.0+21.0 = 44.0

Output 2: Choose an operator: +, -, *, or /: -


Enter first number: 24
Enter second number: 13
24.0-13.0 = 11.0

Output 3: Choose an operator: +, -, *, or /: *


Enter first number: 12
Enter second number: 6
12.0*6.0 = 72.0

Output 4: Choose an operator: +, -, *, or /: /


Enter first number: 36
Enter second number: 6
36.0/6.0 = 6.0

Output 5: Choose an operator: +, -, *, or /:?


Enter first number: 12
Enter second number: 23
Invalid operator!

You might also like