Simple Java Program

Welcome,

I am going to show a simple and basic java program and explain it step by step. Don't worry this is not a Hello World Program but a simple one .

Let's get started. 

For every program you need to first a problem statement and write the code to solve the problem.

My advice is that if you want to learn java instead of searching for problems in sites(eg. hackerank..) you just open your Netbeans or Eclipse IDE and start solving your own problems (think something new and basic and try to code) for eg. calculate your father's profit for month or something like that. it doesn't have to be hard. Just try solving very basic problems everyday. If you create your problems you will be able to understand problem statements given to you in future very easily.

*If you don't have Netbeans or eclipse you can also run your java code using Notepad.*
To run in Notepad:
      1. Type your code in Notepad and save it as filename.java
      2. Open Command prompt and go to your file directory 
      3. Compile your file by typing javac filename.java
      4. To run your code type java filename


Now, we will code for simple mathematical operations😉.

1. Addition:


let's take two variables a & b and add the value to another variable Sum.

 
1.  public class addition{
     public static void main(String args[]){
       int a=5;
       int b=10;
       int sum=a+b;
       System.out.println(sum); 
} }

step 1: First you are creating a java class .
step 2: To be available for anyone outside the class by declaring public. void make sure method doesn't return anything and string args[] to store line arguments.
step 3: initialize a & b with values.
step 4: storing addition result in a variable sum.
step 5: printing the result.

2. Subtraction, Multiplication , Division

  we only have to change one line in each.

 
2.  public class addition{
     public static void main(String args[]){
       int a=5;
       int b=10;
       int sum=a+b;
       int subtraction=a-b;
       int multiplication=a*b;
       int division=a/b;
       System.out.println(sum);
System.out.println(subtraction);
System.out.println(multiplication);
System.out.println(division);
} }


In this program we are giving input directly to the variable. we can also have input which is entered by user every time we compile the program. 

We can do that by using Scanner . I will cover that in next post.


Thank you🙏


Comments