About Me

My photo
Vijayapur, Karnataka, India
I am interested in Teaching.

Monday, 19 June 2023

Simple Java Programs for beginners


Filename: HelloWorld.java

// My First Java Program, Machine says Hello to the world!

class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World!"); 

    }

}


Q. How to compile?

C:\Users\Hp>javac HelloWorld.java


Q. How to run?

C:\Users\Hp>java HelloWorld

Hello, World!



File Name: addition.java

 // Java program to find addition of two integers

import java.util.Scanner;


public class addition

{

public static void main(String args[])

{

Scanner input=new Scanner(System.in);

int a,b,ans;


System.out.println("Enter first integer value:");

a=input.nextInt();


System.out.println("Enter second integer value:");

b=input.nextInt();


ans=a+b;


System.out.println("Addition of "+ a + "and " + b + " is " + ans);

System.out.println("Thank you...This application is developed by : Yours Name Please ");

}

}


How to compile ?

c:\users\hp> javac addition.java[Enter Key]

How to run ?

C:\Users\Hp>java addition

Enter first integer value:
2
Enter second integer value:
3
Addition of 2and 3 is 5
Thank you...This application is developed by : Mr. John



Know it!

 The java.util is one such package that contains a collection of different classes and frameworks.

Scanner is a class available in the java.util package. It is used to take input from a user for any primitive datatype (int, float, string, and so on).

Before using the Scanner class, we need to import it.

import java.util.Scanner;

We can then create an object of the Scanner class by using the following syntax:

Scanner sc= new Scanner(System.in);

We are using sc as an example here, but we can also use any other variable name instead.


import java.util.Scanner; class ScannerExample { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter your Roll number"); int id = sc.nextInt(); System.out.println("Enter your grade"); char grade = sc.next().charAt(0); System.out.println("Roll Number :" + id); System.out.println("Grade :" + grade); } }


Q. How to compile?


C:\Users\Hp>javac ScannerExample.java



How to run?

C:\Users\Hp>java ScannerExample

Enter your Roll number

10

Enter your grade

A

Roll Number :10

Grade :A


Know it:
Scanner class in Java supports nextInt(), nextLong(), nextDouble() etc. But there is no nextChar() (See this for examples) To read a char, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string, the number 0 in the function in CharAt(NUMBER)  represents the index of the single word of the string taken input, and set that index character to the char variable.


No comments: