JAVA BASIC PROGRAMS

**ALL CODES ARE 100 % ERROR FREE**

**CODES ARE ALSO CHECKED THOROUGHLY** 

HERE ARE THE CODING OF JAVA BASIC PROGRAMS WHICH IS SUITABLE FOR ALL WITH EXPLANATIONS

***ALL CODES ARE CONTRIBUTED BY PARARDHA DHAR***

<

1.Java program to print 'Hello world' (First program in Java)

Welcome! Now, you are in the world of Java programming. Here we will learn to write, compile and execute a java program.
1) Writing a java program
You can write a java program in any simple text editor like Notepad, Notepad++ or any IDE (Integrated Development Environment) which supports Java compilation and execution, but here we are talking about writing java program - So use any text editor, write your program (a basic program in given below) and save the file with extension .java

Here, we are saving it with "HelloWorld.java".

2) Compiling java program
In java compilation, it’s a process to convert text file (.java file/java program) to class file. Java compiler converts Java source code to the class file and produced output file will be "HelloWorld.class".

Note: public class name will be the class file name.

To compile java program, follow following syntax:
javac HelloWorld.java

public class HelloWorld {
    public static void main(String[] args) {
        //printing the message
        System.out.println("Hello World!");
    }
}

How to print different type of values in Java?

class j2 {
    public static void main(String args[]) {
        int num;
        float b;
        char c;
        String s;

        //integer
        num = 100;
        //float
        b = 1.234 f;
        //character
        c = 'A';
        //string
        s = "Hello Java";

        System.out.println("Value of num: " + num);
        System.out.println("Value of b: " + b);
        System.out.println("Value of c: " + c);
        System.out.println("Value of s: " + s);
    }
}

How to read and print an integer value in Java?

import java.util.*;

class j3 {
    public static void main(String args[]) {
        int a;

        //declare object of Scanner Class
        Scanner buf = new Scanner(System.in);

        System.out.print("Enter value of a :");
        /*nextInt() method of Scanner class*/
        a = buf.nextInt();

        System.out.println("Value of a:" + a);
    }
}

Java program to find sum and average of two integer numbers

import java.util.*;

class j4
{
    public static void main(String args[])
    {
        int a, b, sum;
        float avg;


        Scanner buf = new Scanner(System.in);

        System.out.print("Enter first number : ");
        a = buf.nextInt();

        System.out.print("Enter second number : ");
        b = buf.nextInt();

        /*Calculate sum and average*/
        sum = a + b;
        avg = (float)((a + b) / 2);

        System.out.print("Sum : " + sum + "\nAverage : " + avg);
    }
}

Java program to find sqare,cube and square root of a given number

Given an integer number and we have to find their Square, Square Root and Cube.
In this program, we are using these two methods of Math class:
1.Math.pow(m,n):It is used to get the power of any base, it will return m to the power of n (m^n).

2.Math.sqrt(m):It is used to get the square root of any number, it will return square root of m.
import java.util.*;
 
/*Java Program to find square, square root and cube of a given number*/
public class j5 
{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int num;

System.out.print("Enter an integer number: ");
num=sc.nextInt();

System.out.println("Square of "+ num + " is: "+ Math.pow(num, 2));
System.out.println("Cube of "+ num + " is: "+ Math.pow(num, 3));
System.out.println("Square Root of "+ num + " is: "+ Math.sqrt(num));
}
}

Java program to swap two numbers with and without using third variable

**BY USING THE THIRD VARIABLE**
//Java program to swap two numbers.
import java.util.*;

class SwapTwoNumbers {
    public static void main(String[] s) {
        int a, b;
        //Scanner class to read value
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter value of a: ");
        a = sc.nextInt();
        System.out.print("Enter value of a: ");
        b = sc.nextInt();

        System.out.println("Before swapping - a: " + a + ", b: " + b);
        //using thrid variable
        int temp;
        temp = a;
        a = b;
        b = temp;
        System.out.println("After swapping  - a: " + a + ", b: " + b);
    }
}
**WITHOUT USING THE THIRD VARIABLE**
import java.util.*;

class SwapTwoNumbers {
    public static void main(String[] s) {
        int a, b;
        //Scanner class to read value
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter value of a: ");
        a = sc.nextInt();
        System.out.print("Enter value of a: ");
        b = sc.nextInt();

        System.out.println("Before swapping - a: " + a + ", b: " + b);
        //without using thrid variable
        a = a + b;
        b = a - b;
        b = a - b;
        System.out.println("After swapping  - a: " + a + ", b: " + b);
    }
}

Java program to check number is positive, negative or zero.

//Java program to check number is positive, negative or zero.

import java.util.*;

class PosNegZero {
    public static void main(String[] s) {
        int num;
        //Scanner class to read value
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter any integer number: ");
        num = sc.nextInt();

        //check condition for +ve, -ve and Zero
        if (num > 0)
            System.out.println(num + " is POSITIVE NUMBER.");
        else if (num < 0)
            System.out.println(num + " is NEGATIVE NUMBER.");
        else
            System.out.println("IT's ZERO.");

    }
}

Java - Calculate Compound Interest using Java Program.


In this code snippet we will learn how to calculate compound interest.

If Mike initially borrows an Amount and in return agrees to make n repayments per year, each of an Amount this amount now acts as a PRINCIPAL AMOUNT. While Mike is repaying the loan, interest is accumulating at an annual percentage rate, and this interest is compounded times a year (along with each payment). Therefore, Mike must continue paying these instalments of Amount until the original amount and any accumulated interest is repaid. This equation gives the Amount that the person still needs to repay after number of years.

CompoundInterest = Principal_Amount * Math.pow((1 + Interest_Rate/100), Time_Period);

import java.util.Scanner;

public class Compound_Interest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        double Principal_Amount = 0.0;
        double Interest_Rate = 0.0;
        double Time_Period = 0.0;
        double CompoundInterest = 0.0;

        Scanner i = new Scanner(System.in);

        System.out.print("Enter the Principal Amount : ");
        Principal_Amount = i.nextDouble();

        System.out.print("Enter the Time Period : ");
        Time_Period = i.nextDouble();

        System.out.print("Enter the Interest Rate : ");
        Interest_Rate = i.nextDouble();

        CompoundInterest = Principal_Amount * Math.pow((1 + Interest_Rate / 100), Time_Period);

        System.out.println("");
        System.out.println("Compound Interest : " + CompoundInterest);
    }

}

Java - Calculate LCM (Least Common Multiple) using Java Program.


In this code snippet, we will find the LCM of given numbers using Java program.

LCM can be defined as any common multiple except 1, then it will always be greater than or equal to the maximum number. It cannot be less than it. LCM of two numbers is a number which is a multiple of both the numbers.

import java.util.Scanner;

public class Lcm {

    //  Lowest common Number
    public static int lcm(int First_number, int Second_number) {
        int x, max = 0, min = 0, lcm = 0;
        if (First_number > Second_number) {
            max = First_number;
            min = Second_number;
        } else {
            max = Second_number;
            min = First_number;
        }

        for (int i = 1; i <= min; i++) {
            x = max * i;
            if (x % min == 0) {
                lcm = x;
                break;
            }
        }
        return lcm;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("First Number  :");
        int num1 = sc.nextInt();
        System.out.print("Second Number :");
        int num2 = sc.nextInt();

        System.out.println("Lowest Common Factor: " + lcm(num1, num2));

    }
}

Java program to find largest number among three numbers.

//Java program to find largest number among three numbers.

import java.util.*;

class LargestFrom3 {
    public static void main(String[] s) {
        int a, b, c, largest;
        //Scanner class to read value
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first  number:");
        a = sc.nextInt();
        System.out.print("Enter second number:");
        b = sc.nextInt();
        System.out.print("Enter third  number:");
        c = sc.nextInt();

        if (a > b && a > c)
            largest = a;
        else if (b > a && b > c)
            largest = b;
        else
            largest = c;

        System.out.println("Largest Number is : " + largest);

    }
}

Java program to check whether year is Leap year or not.

1.For century years- year must be divisible by 400.

2.For non century years- year must divisible by 4 (in 2nd condition after || operator, there is a condition year%100!=0 it means when year is not divisible by 100 that means it is non century years.

//Java program to check whether year is Leap year or not.

import java.util.*;

class LeapYear {
    public static void main(String[] s) {
        int year;
        Scanner sc = new Scanner(System.in);

        try {

            System.out.print("Enter year:");
            year = sc.nextInt();

            if ((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0))
                System.out.println(year + " is a Leap Year.");
            else
                System.out.println(year + " is not a Leap Year.");
        } catch (Exception Ex) {
            System.out.println("Oops ... : " + Ex.toString());
        }

    }
}

Java - Greatest Common Divisor or Euclidean Algorithm Program or Highest Common Divisor.


In this code snippet we will learn how to get Greatest Common Divisor in Java, Implementation of Euclidean Algorithm to get Highest Common Divisor.


The Euclidean algorithm is used to find the Greatest Common Divisor and Highest Common Divisor of two numbers. Greatest Common Divisor is calculated by divide both numbers with their common divisorpublic class Gcd {

    //  greatest common divisor

    public static int gcd(int First_number, int Second_number) {

        int i = First_number % Second_number;

        while (i != 0) {

            First_number = Second_number;

            Second_number = i;

            i = First_number % Second_number;

        }

        return Second_number;

    }


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        System.out.print("First Number  :");

        int num1 = sc.nextInt();

        System.out.print("Second Number :");

        int num2 = sc.nextInt();


        System.out.println("Greatest Common Divisors: " + gcd(num1, num2));


    }

}

Java - Greatest Common Factor or Euclidean Algorithm Program or Highest Common Factor.


In this code snippet we will learn how to get Greatest Common Factor in Java, Implementation of Euclidean Algorithm to get Highest Common Factor.


The Euclidean algorithm is used to find the Greatest Common Factor and Highest Common Factor of two numbers. Highest Common Factor is calculated by divide both numbers with their common factor.

import java.util.Scanner;

public class HCF {

    //  greatest common factor
    public static int hcf(int First_number, int Second_number) {
        int hcf = 0;
        int min = Math.min(First_number, Second_number);

        for (int i = min; i >= 1; i--) {
            if (First_number % i == 0 && Second_number % i == 0) {
                hcf = i;
                break;
            }
        }
        return hcf;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("First Number  :");
        int num1 = sc.nextInt();
        System.out.print("Second Number :");
        int num2 = sc.nextInt();

        System.out.println("Highest Common Factor: " + hcf(num1, num2));

    }
}

Java program to find Largest of Three Numbers

Largest of Three Numbers in Java - This program will read three integer numbers from the user and find the largest number among them, here we will find the largest number using if else conditions, ternary operator and function/method.

//Java program to find Largest of three numbers.
 
import java.util.*;
 
public class LargestNumber{   
     
     public static void main(String []args)
     {
            int a=0,b=0,c=0;
            int largest=0;
            //Scanner class to take user input.
            Scanner X = new Scanner(System.in);
             
            System.out.print("Enter First No. :");
            a = X.nextInt(); //read integer number
             
            System.out.print("Enter Second No. :");
            b = X.nextInt(); //read integer number
             
            System.out.print("Enter Third No. :");
            c = X.nextInt(); //read integer number
             
            if( a>b && a> c)
                largest = a;
            else if(b>a && b>c)
                largest = b;
            else
                largest = c;
             
            System.out.println("Lagest Number is : "+largest);
     }
}

EMI Calculator in Java - Java program to calculate EMI.


EMI Calculator in Java - This program will read Loan Amount, Interest Rate and Time in Years and calculate monthly EMI.

//EMI Calculator Program in Java
 
import java.util.*;
 
public class EmiCalc{
 
    public static void main(String []args)
    {
         
        //Scanner class to take user input.
        Scanner X = new Scanner(System.in);
         
        double principal, rate, time, emi;
  
        System.out.print("Enter principal: ");
        principal = X.nextFloat();
      
        System.out.print("Enter rate: ");
        rate = X.nextFloat();
      
        System.out.print("Enter time in year: ");
        time = X.nextFloat();
      
        rate=rate/(12*100); /*one month interest*/
        time=time*12; /*one month period*/
      
      
        emi= (principal*rate*Math.pow(1+rate,time))/(Math.pow(1+rate,time)-1);
      
        System.out.print("Monthly EMI is= "+emi+"\n");
                 
    }
}

Java program to Calculate Perimeter of a Circle.


Find Perimeter of Circle in Java - This program will read radius from the user and calculate the Perimeter of the circle.

//Java program to Calculate Perimeter of a Circle.
 
import java.util.Scanner;
 
public class PerimeterCircle {
 
    public static void main(String[] args) {
 
        double radius;
        Scanner sc=new Scanner(System.in);
         
         // input radius of circle
        System.out.print("Enter the Radius of Circle : ");
        radius=sc.nextDouble(); 
         
        // circle parameter is 2 * pie * radius 
        double Perimeter=2*3.14*radius;
         
        System.out.print("Perimeter of Circle : " + parameter);
         
    }
 
}


CALENDAR PROGRAM

Enter day no and year to get the actual date


import java.util.*;

public class cal
{
    void main(int d,int y)
    {
        int f=0,nd=31,m=1;
        if(y%400==0 ||(y%4==0 && y%100!=0))
            f=1;
        while(d>nd && m<=12)
        {
            d=d-nd;
            m++;
            if(m==4||m==6||m==9||m==11)
                nd=30;
            else if(m==1||m==3||m==5||m==7||m==8||m==10||m==12)
                nd=31;
            else if(f==0 && m==2)
                nd=28;
            else if(f==1 && m==2)
                nd=29;

        }
        if(d<1 ||m>12)
            System.out.print("Invalid date");
        else
            System.out.print("date: "+d+"-"+m+"-"+y);
    }

Java Math class

Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can't define to return the bit-for-bit same results. This relaxation permits implementation with better-performance where strict reproducibility is not required.

If the size is int or long and the results overflow the range of value, the methods addExact(), subtractExact(), multiplyExact(), 

FOR LIVE DEMO OF THIS FOLLOWING PROGRAM GO HERE http://tpcg.io/kLhmHLLv



public class maths  
{  
    public static void main(String args[])  
    {  
        int x=3, y=2,cb=729; double a=-16.3,b=Math.random(),c=Math.random();
        System.out.println("The absolute value is"+Math.abs(x));
        System.out.println("The square root value is"+Math.sqrt(y));
        System.out.println("The power value is"+Math.pow(x,y));
        System.out.println("The round off value is"+Math.round(Float.NaN));
        System.out.println("The max value is"+Math.max(x,y));
        System.out.println("The min value is"+Math.min(x,y));
        System.out.println("The random values of b and c are"+b+" "+c);
        System.out.println("The ceil value is"+Math.ceil(a));
        System.out.println("The floor value is"+Math.floor(a));
        System.out.println("The cuberoot value is"+Math.cbrt(cb));
        System.out.println("The log value of 10 is"+Math.log(10));
        System.out.println("The exponential valueof 5 is"+Math.exp(5));
        System.out.println("The rint value of 25.3 is"+Math.rint(25.53));
        System.out.println("The sin value is"+Math.sin(30*3.141/180));
        System.out.println("The cos value is"+Math.cos(60*3.141/180));
        System.out.println("The tan value is"+Math.tan(45*3.141/180));
    }
}

Java Math Methods

The java.lang.Math class contains various methods for performing basic numeric operations such as the logarithm, cube root, and trigonometric functions etc. The various java math methods are as follows:

Basic Math methods

MethodDescription
Math.abs()It will return the Absolute value of the given value.
Math.max()It returns the Largest of two values.
Math.min()It is used to return the Smallest of two values.
Math.round()It is used to round of the decimal numbers to the nearest value.
Math.sqrt()It is used to return the square root of a number.
Math.cbrt()It is used to return the cube root of a number.
Math.pow()It returns the value of first argument raised to the power to second argument.
Math.signum()It is used to find the sign of a given value.
Math.ceil()It is used to find the smallest integer value that is greater than or equal to the argument or mathematical integer.
Math.copySign()It is used to find the Absolute value of first argument along with sign specified in second argument.
Math.nextAfter()It is used to return the floating-point number adjacent to the first argument in the direction of the second argument.
Math.nextUp()It returns the floating-point value adjacent to d in the direction of positive infinity.
Math.nextDown()It returns the floating-point value adjacent to d in the direction of negative infinity.
Math.floor()It is used to find the largest integer value which is less than or equal to the argument and is equal to the mathematical integer of a double value.
Math.floorDiv()It is used to find the largest integer value that is less than or equal to the algebraic quotient.
Math.random()It returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Math.rint()It returns the double value that is closest to the given argument and equal to mathematical integer.
Math.hypot()It returns sqrt(x2 +y2) without intermediate overflow or underflow.
Math.ulp()It returns the size of an ulp of the argument.
Math.getExponent()It is used to return the unbiased exponent used in the representation of a value.
Math.IEEEremainder()It is used to calculate the remainder operation on two arguments as prescribed by the IEEE 754 standard and returns value.
Math.addExact()It is used to return the sum of its arguments, throwing an exception if the result overflows an int or long.
Math.subtractExact()It returns the difference of the arguments, throwing an exception if the result overflows an int.
Math.multiplyExact()It is used to return the product of the arguments, throwing an exception if the result overflows an int or long.
Math.incrementExact()It returns the argument incremented by one, throwing an exception if the result overflows an int.
Math.decrementExact()It is used to return the argument decremented by one, throwing an exception if the result overflows an int or long.
Math.negateExact()It is used to return the negation of the argument, throwing an exception if the result overflows an int or long.
Math.toIntExact()It returns the value of the long argument, throwing an exception if the value overflows an int.

Logarithmic Math Methods

MethodDescription
Math.log()It returns the natural logarithm of a double value.
Math.log10()It is used to return the base 10 logarithm of a double value.
Math.log1p()It returns the natural logarithm of the sum of the argument and 1.
Math.exp()It returns E raised to the power of a double value, where E is Euler's number and it is approximately equal to 2.71828.
Math.expm1()It is used to calculate the power of E and subtract one from it.

SLAB PROGRAMMING

SOLVED AS PER AS AUDIENCE REQUEST

A CLOTH SHOWROOM HAS ANNOUNCED THE FOLLOWING FESTIVAL DISCOUNTS AND ASSURED GIFTS ON THE PURCHASE OF ITEMS BASED ON THE TOTAL COST OF THE ITEMS PURCHASED SEE THE IMAGE ATTACHED BELOW FOR FURTHER INFORMATION ON THIS PROGRAM






import java.util.*;
class slab
{
    void main()
    {
        Scanner ob=new Scanner (System.in);
        double dis,net;
        int n;
        String g;
        System.out.println("Enter the amount of purchase");
        n=ob.nextInt();
        if(n<=2000)
        {
            dis=n*5/100.0;
            g="WALL CLOCK";
        }
        else if( n>=2001 && n<=5000)
        {
            dis=n*10/100.0;
           g="School bag";
        }
        else if(n>=5001 && n<=10000)
        {
            dis=n*15/100.0;
            g="ELECTRIC IRON";
        }
        else
        {
            dis=n*20/100.0;
            g="WRIST WATCH";
        }
        net=n-dis;
     System.out.println("total cost="+n);
     System.out.println("Dicount amount="+dis);
       System.out.println("net amount="+net);
         System.out.println("prize that you have woned: "+g);
     
    }
}

HOW TO CONCATENATE 2 INTEGERS IN JAVA IN A VERY SIMPLE METHOD

OTHER SITES HAD DONE THAT IN VERY DIFFICULT METHOD BUT WE WILL TEACH YOU HOW TO DO IT SIMPLY JUST FOLLOW THE CODE BELOW:

import java.util.*;
public class concatinate
{
    void main()
    {
        int a,b,k=1,i;
        long s;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter any two number");
        a=sc.nextInt();
        b=sc.nextInt();
        for(i=b;i>0;i=i/10)
        {
            k=k*10;
        }
        s=a*k+b;
        System.out.print(s);
    }
}




**EVERYDAY WE ARE CONSTANTLY UPDATING OUR SITE WITH MORE STUFFS AND PROGRAMS TO HELP YOU OUT AND MAKE YOU UNDERSTAND VERY CORRECTLY**
**FIRST APPROACH AN IDE AND TRY BY YOURSELF AND THEN COME TO UNDERSTAND AND COPY**
**HAVE DOUBT ASK IN THE COMMENT SECTION**
**WANNA CHECK YOUR PROGRAM!!!!
POST IT
OUR PROFESSIONAL TEACHER WILL CHECK IT WITHIN 24 HRS
GET IT SOLVED FOR FREE
OUR AGENTS ARE ALWAYS ONLINE 
TO HELP YOU OUT AND MAKE YOU UNDERSTAND**

**NOTE**

*THIS IS A ABSOLUTELY FREE SITE WITH NO ADS TO DISTURB YOU AND YOUR MINDSET****
**TO GIVE YOU FREELY THE CODING FOR JAVA**
**AND WE MAKE SURE TO HELP YOU TO SCORE OUT THE BEST MARKS IN COMPUTER SCIENCE**
**ESPECIALLY MADE FOR SCHOOL STUDENTS**

4 Comments

Please Select Embedded Mode To Show The Comment System.*

It looks like you're using an ad blocker. We rely on ads to keep our site free, please whitelist us!

Click here to continue

Please whitelist our site to continue enjoying our content.

Whitelist | Close