Java - Exercise 1

Java

In this exercise section of the tutorial we will write some basic Java program.

Don't worry if you don't understand the code. We will talk in detail about the program in later part of this tutorial series.

Alright, open your IDE and lets write some Java code.

1. Write a program in Java to print "We are learning Java."

For this we will use the System.out.println() method.

class Example {
  public static void main(String args[]) {
    System.out.println("We are learning Java.");
  }
}

Output:

We are learning Java.

2. Write a program in Java to print your name

Try this yourself.

3. Write a program in Java to add 10 and 20 and print the result

We will create three integer variables a, b and sum.

We use variable to store value in Java.

And since the variables will store integer value so, we will set the date type as int.

Data type of a variable tells us about the type of value stored in the variable.

class Example {
  public static void main(String args[]) {
    int a = 10;
    int b = 20;
    int sum = a + b;
    System.out.println("Sum: " + sum);
  }
}

Output:

Sum: 30

Explanation

int a = 10;

We are creating variable a of type int to store integer value.

Then we are assigning integer value 10 using the = assignment operator.

And we have ended the statement using the ; semicolon.

Similarly, we are creating another integer variable b and assigning it an integer value 20.

int b = 20;

Next we have the sum integer variable that holds the sum of the two integer values. We are adding the values using the + addition operator.

int sum = a + b;

Finally we are printing the result using the println() method.

System.out.println("Sum: " + sum);

We are using the + in the above code to concatenate string and value to get the final result.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT