In this article, I have provided list of various usefule and beginners java programming example with output, like simple hello world program, adding two numbers, printing pyramid in java etc., which can be helpful for beginners to understand the syntax and logic of Java programming, so here is the list.
- Java Hello world program
- Addition of two numbers in java
- Leap year program in Java
- Armstrong number program in java
- Print prime number from 1 to 100 in Java
- Print ASCII Value program in Java
- Fibonacci Series program in Java
- Java program to reverse a string
- Printing Right angled * pattern triangle in Java
- Printing Equilateral triangle in Java
Java Hello world program
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World");
}
}
Output:
Hello World
- class keyword is used to declare a class in java
- public keyword is an access modifier which represents visibility, it means this function is visible to all.
- static is a keyword, used to make a static method. The advantage of static method is that there is no need to create object to invoke the static method. The main()
- method here is called by JVM, without creating any object for class.
- void is the return type of the method, it means this method will not return anything.
- Main: main() method is the most important method in a Java program. It represents startup of the program.
- String[] args is used for command line arguments.
- System.out.println() is used to print statements on the console.
Read: Hello World program in Java (Your first java program)
Addition of two numbers in java
package add;
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers to add: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println(num1+num2);
}
}
Output:
Enter two numbers to add:
5 20
25
In the above code, we are asking user to input two numbers using Scanner
class and saving values as num1
& num2
, then adding it.
Leap year program in Java
import java.util.Scanner;
public class Lear_year {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter any year:");
int year = s.nextInt();
boolean flag = false;
if (year % 400 == 0) {
flag = true;
} else if (year % 100 == 0) {
flag = false;
} else if (year % 4 == 0) {
flag = true;
} else {
flag = false;
}
if (flag) {
System.out.println("Year " + year + " is a Leap Year");
} else {
System.out.println("Year " + year + " is not a Leap Year");
}
}
}
Output:
Enter any year:2015
Year 2015 is not a Leap Year
Enter any year:2016
Year 2016 is a Leap Year
In the above program, we are checking if a number is leap year of not, by dividing it, by 400, 100 and 4 using % , as it gives remainder, if it remainder value then it is not a leap year.
Armstrong number program in java
package com.armstrong;
import java.util.Scanner;
public class ArmstrongNumberCheck {
public static void main(String args[])
{
int number, sum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to check if it is an armstrong number");
number = in.nextInt();
/* Converting Integer to String. It'll help to find number of
digits in the Integer by using length() */
String temp = number + "";
//get number length
int numLength = temp.length();
//copy the main Number in a variable
int numCopy = number;
//loop all the numbers until remainder is 0
while(numCopy != 0 ){
int remainder = numCopy % 10;
// using Math.pow to get digit raised to the power
// total number of digits
sum = sum + (int)Math.pow(remainder, numLength);
numCopy = numCopy/10;
}
System.out.println("sum is " + sum );
if (number == sum )
{
System.out.println( number + " is an armstrong number.");
}
else
{
System.out.println(number+ " is not an armstrong number.");
}
in.close();
}
}
Output:
Enter a number to check if it is an armstrong number
9474
sum is 9474
9474 is an armstrong number.
Enter a number to check if it is an armstrong number
121
sum is 10
121 is not an armstrong number.
Enter a number to check if it is an armstrong number
371
sum is 371
371 is an armstrong number.
Print prime number from 1 to 100 in Java
public class PrimeNumber {
public static void main(String[] args) {
int p = 0;
System.out.println("prime no are :");
for (int i = 2; i <= 100; i++)
{
for (int j = 2; j <= 100; j++)
{
if ((i % j) == 0)
{
if (i != j)
break;
else
{
p = i;
System.out.println(p);
}
}
}
}
}
}
Output:
prime no are :
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Print ASCII Value program in Java
public class PrintASCIIExample{
public static void main(String[] args) {
// character whose ASCII value to be found
char ch1 = 'a';
char ch2 = 'b';
// variable that stores the integer value of the character
int asciivalue1 = ch1;
int asciivalue2 = ch2;
System.out.println("ASCII value of " + ch1 + " is: " + asciivalue1);
System.out.println("ASCII value of " + ch2 + " is: " + asciivalue2);
}
}
output:
ASCII value of a is: 97
ASCII value of b is: 98
Fibonacci Series program in Java
package com.fib;
import java.util.Scanner;
public class fibonacciExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number to limit Fibonacci series: ");
int num = input.nextInt();
//loop till the last count
for(int i = 1; i <= num; i++){
//call Fibonacci function to print sum of last two numbers
System.out.print(printFibonacci(i) + " ");
}
input.close();
}
// recursion function
private static int printFibonacci(int CurrentNumber){
//exit condition
if(CurrentNumber == 1 || CurrentNumber == 2){
return 1;
}
return printFibonacci(CurrentNumber - 1) + printFibonacci(CurrentNumber - 2);
}
}
Output:
Enter how many numbers are needed in Fibonacci series:
10
1 1 2 3 5 8 13 21 34 55
In the above program, we are using a recursion function to print fibonacci series, basically, we ask user about how many number ( for loop) fibonacci series needs to be printed and call fibonacci function for that number of times, each time we add "currentNumber-1" and "CurrentNumber-2" value, and return it to print.
Java program to reverse a string
class ReverseString
{
public static void main(String[] args)
{
String input = "qawithexperts";
// getBytes() method to convert string
// into bytes[].
byte [] strAsByteArray = input.getBytes();
//create a new byte array for storing results
byte [] result =
new byte [strAsByteArray.length];
// Store result in reverse order into the
// result byte[]
for (int i = 0; i<strAsByteArray.length; i++)
result[i] =
strAsByteArray[strAsByteArray.length-i-1];
//print the new byte array as string
System.out.println(new String(result));
}
}
Output:
strepxehtiwaq
In the above program, we are revesring the string by traversing the string from backward and saving that string in new byte array from last to first character one by one using for loop in reverse, then printing it.
Printing Right angled * pattern triangle in Java
import java.io.*;
// Java code to demonstrate star pyramid pattern
public class JavaWithQAWithExperts
{
// Function to demonstrate printing pattern
public static void printStars(int n)
{
//Declare two vairables
int i, j;
// outer loop to handle number of rows
// n in this case, you can provide static values like 5 for printing 5 rows
for(i=0; i<n; i++)
{
// inner loop to handle number of columns
for(j=0; j<=i; j++)
{
// printing stars
System.out.print("* ");
}
// just to break line, after loop for each row is completed
System.out.println();
}
}
// Main function
public static void main(String args[])
{
int n = 5;
//Call the printStars function by passing integer value, here it is 5
printStars(n);
}
}
Output:
*
* *
* * *
* * * *
* * * * *
When we are creating a pyramid, we need to need two loops( easy way, we can do it with one loop also), one for printing the "*" or you can say numbers, another to start loop again for next row(once first loop is over, call the outer loop to print next line). So, basically
Printing Equilateral triangle in Java
import java.io.*;
// Java code to demonstrate star pattern
public class JavaWithQAWithExperts
{
//Main function to print triangle
public static void printTriangle(int n)
{
// k= number of spaces
int k = 2*n - 2,i,j;
// outer loop to handle number of rows
for (i=0; i<n; i++)
{
// inner loop to handle number spaces
// values changing acc. to requirement
for (j=0; j<k; j++)
{
// printing spaces
System.out.print(" ");
}
// decrementing k after each loop
k = k - 1;
// inner loop to handle number of columns
for (j=0; j<=i; j++ )
{
// printing stars
System.out.print("* ");
}
// ending line after each row
System.out.println();
}
}
// Calling Function
public static void main(String args[])
{
int n = 5; //number of rows
//call function to print triangle
printTriagle(n);
}
}
Output
*
* *
* * *
* * * *
* * * * *
In the above code, we are using K variable to print spaces but this time we are decrementing it by 1,i.e, k= k-1 , after each loop of printing spaces get's over, so basically logic is same as per the 2nd code, but changing it a little bit it generates equivalent triangle.
You may also like to read:
Best Java IDE for making easy to code in Java. (Eclipse, Netbeans or Any other?)