Java fundamental programs for beginners:

     Java is a object oriented programming language. It was developed by James Gosling in sun micro systems. It is a general-purpose language. It uses classes for creating programs.

A simple program is given below.

Class greeting is used to display a message “Have a nice day” using system.out.println()

class  greeting

{

 public static void main(String args[])

{

System.out.println("Have a nice day");

}

}

Save this file as “greeting.java”. compile and execute this file to get the output.

Output:

C:\raji\blog>javac greeting.java

C:\raji\blog>java greeting

Have a nice day

Next, an arithmetic operation : Multiplication of two numbers

Here, a class arith is created. Two integer values are assigned as input. Using print statement, the two values are multiplied and displayed.

class arith

{

 public static void main(String args[])

 {

  int a = 10;

  int b = 20;

  System.out.println("The multiplication of two numbers are:"+(a*b));

 }

}

Here is the output.

C:\raji\blog>javac arith.java

C:\raji\blog>java arith

The multiplication of two numbers are:200

Note:

Use the same code except the operation(a*b) for other arithmetic operations. Replace by below code.

For addition of two numbers:

  System.out.println("The sum of two numbers are:"+(a+b));

 For subtraction of two numbers:

  System.out.println("The subtraction of two numbers are:"+(a-b));

For division of two numbers:

  System.out.println("The division of two numbers are:"+(a/b));

Next programs uses the conditional statement if,else.

Fundamental java program: Check the given number is odd or even

import java.util.Scanner;

class oddeven

{

 public static void main(String args[])

 {

        Scanner scanner = new Scanner(System.in);

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

        int no = scanner.nextInt();

        if(no % 2 == 0)

         System.out.println("This is an even number");

        else

         System.out.println("This is an odd number");

 }

}

The output is shown.

C:\raji\blog>javac oddeven.java

C:\raji\blog>java oddeven

Enter a number: 34

This is an even number

C:\raji\blog>java oddeven

Enter a number: 23

This is an odd number

These are the Java fundamental programs for beginners.

No comments:

Post a Comment