Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Suryateja Pericherla Categories: Basic. No Comments on Java program for demonstrating data types, variables, operators, arrays, and control structures
0
(0)

Aim

To write a program for demonstrating data types, variables, operators, arrays, and control structures in Java.

 

Theory

Data Types

A data type specifies the type of value a variable can store or the type of an expression. Java is a strongly typed language means that you should specify the type of a variable before using it in a Java program.

 

There are eight primitive types in Java namely: byte, short, long, int, float, double, char and boolean. They can be categorized as shown below:

https://www.startertutorials.com/corejava/wp-content/uploads/2014/09/Java-Datatypes.jpg

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


Also, every class and interface existing in Java is also a type (predefined). By creating a class or an interface, you are creating a user defined type. The size and range of values for each primitive data type is specified below:

http://www.startertutorials.com/corejava/wp-content/uploads/2014/09/Java-data-types-sizes-and-ranges.jpg

 

Variables

A variable is a named location in memory (RAM) to store data. A variable can be created or declared in Java by using the below syntax:

datatype  variable_name;

 

A variable_name can be any valid identifier in Java. The datatype specifies the type of value you are going to store in the variable. Example for declaring a variable in Java is shown below:

int  x;

 

After declaring variables, we can initialize them as shown below:

variable_name = value;

 

So, we can initialize the variable x as shown below:

x = 10;

 

We can combine variable declaration and initialization into a single line as shown below:

int  x = 10;

 

Based on the location where the variable is declared and how it is declared, variables in Java are divided into three types. They are:

  • Instance variables
  • Class variables
  • Local variables

 

Instance Variables: A variable which is declared inside a class and outside all the methods, constructors and blocks is known as an instance variable.

 

Class Variables: A variable which is declared inside a class and outside all the methods, constructors, blocks and is marked as static is known as a class variable. More on static keyword in another article.

 

Local Variables: Any variable which is declared inside a class and inside a block, method or a constructor is known as a local variable.

 

Operators

An operator allows the programmer or the computer to perform an operation on the operands. An operand can be a literal, variable or an expression. Different categories of operators in Java are:

http://www.startertutorials.com/corejava/wp-content/uploads/2014/10/Operators.jpg

 

Arrays

An array is a set of homogeneous variables sharing the same name. Homogeneous in the sense, all the elements in the array must be of the same data type. All the elements of an array are stored side-by-side in the memory.

 

An array can be one-dimensional, two-dimensional or multi-dimensional. Creation of a one-dimensional array is a two-step process. First, we have to create an array variable and second; we have to use the new operator to allocate memory for the array elements.

 

Syntax for declaring an array variable is as shown below:

data-type array-name[ ];

 

Example for declaring an array is shown below:

int a[ ];

 

Syntax for allocating memory for the array elements is as shown below:

array-name = new data-type[size];

 

Example for allocating memory for the array elements is shown below:

a = new int[10];

 

Two steps for creating an array can be combined into a single step as shown below:

int a[ ] = new int[10];

 

Control Statements

In Java, control statements can be categorized into the following categories:

  • Selection statements (if, switch)
  • Iteration statements (while, do-while, for, for-each)
  • Jump statements (break, continue, return)

 

Selection statements

As the name implies, selection statements in Java executes a set of statements based on the value of an expression or value of a variable. A programmer can write several blocks of code and based on the condition or expression, one block can be executed.

 

Selection statements are also known as conditional statements or branching statements. Selection statements provided by Java are if and switch.

 

Iteration Statements

While selection statements are used to select a set of statements based on a condition, iteration statements are used to repeat a set of statements again and again based on a condition for finite or infinite number of times.

 

Iteration statements provided by Java are: for, while, do-while and for-each.

 

Jump Statements

As the name implies, jump statements are used to alter the sequential flow of the program. Jump statements supported by Java are: break, continue and return.

 

Pseudo code/Steps

  1. Create an array and read array elements (numbers).
  2. Print the following menu to the user and read the users choice.
    1. Operations available on array:
    2. Sum of elements
    3. Product of elements
    4. Max of elements
    5. Average of elements
    6. Numbers divisible by 2 and 5
    7. Exit
  3. As long as user does not enter 0 as a choice, the above menu should be repeatedly displayed.
  4. Use a switch case statement and write code for each of the choices above.

 

Program

//Program to demonstrate data types, variables, operators, arrays, and control statements.
import java.util.Scanner;
class Driver
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter size of array: ");
		int n = input.nextInt();
		int a[] = new int[n];
		System.out.println("Enter " + n + " numbers");
		for(int i=0; i<n; i++)
			a[i] = input.nextInt();
		int ch = 0;
		do
		{
			System.out.println("Operations available on area");
			System.out.println("1. Sum of elements");
			System.out.println("2. Product of elements");
			System.out.println("3. Max of elements");
			System.out.println("4. Average of elements");
			System.out.println("5. Numbers divisible by 2 and 5");
			System.out.println("0. Exit");
			System.out.println("Enter your choice (number): ");
			ch = input.nextInt();
			switch(ch)
			{
				case 1:
					int sum = 0;
					for(int i=0; i<n; i++)
						sum = sum + a[i];
					System.out.println("\nSum of elements = " + sum);
					break;
				case 2:
					int prod = 1;
					for(int i=0; i<n; i++)
						prod = prod * a[i];
					System.out.println("\nProduct of elements = " + prod);
					break;
				case 3:
					int max = 0;
					for(int i=0; i<n; i++)
					{
						if(max < a[i])
							max = a[i];
					}
					System.out.println("\nMax element = " + max);
					break;
				case 4:
					int nsum = 0;
					for(int i=0; i<n; i++)
						nsum = nsum + a[i];
					double avg = nsum/(double)n;
					System.out.println("\nAverage of elements = " + avg);
					break;
				case 5:
					for(int i=0; i<n; i++)
					{
						if(a[i]%2 == 0 && a[i]%5 == 0)
							System.out.print(a[i] + " ");
					}
					System.out.println("\n");
				default:
					break;
			}
		}while(ch != 0);
	}		
}

 

Input and Output:

Enter size of array:
5

Enter 5 numbers
10
2
15
30
55

Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
1

Sum of elements = 112
Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
2

Product of elements = 495000
Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
3

Max element = 55
Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
4

Average of elements = 22.4
Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
5
10 30

Operations available on array:
1. Sum of elements
2. Product of elements
3. Max of elements
4. Average of elements
5. Numbers divisible by 2 and 5
0. Exit
Enter your choice (number):
0

 

Result

Data types, variables, operators, arrays, and control statements in Java were successfully demonstrated.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

Your email address will not be published. Required fields are marked *

Blogarama - Blog Directory