top of page
Writer's picturePushp Raj

Introduction to Java DataTypes, Loops & More

Updated: Jan 24


Java DataTypes, Loops & More
Java DataTypes, Loops & More

Variables are used to store information. But a fundamental question arises: What data type is the variable storing? If the individual data types of variables are unknown, the computation of a program can be more precise. As a result, the concept of data kinds emerges. We will study Java Data Types using examples in this course.


What are Datatypes?

Every piece of data that is processed every day is classified into kinds. Datatype refers to the type of data. Java makes use of a variety of data types.


Data Types in Java

However, the data types are primarily divided into two categories:


  • Primitive Data Types: These data types are hard coded into the compiler and will be recognized when running the program. Examples include int, float, and so on.

  • Non-Primitive Data Types: These types are sorts of user-specified data, i.e., their description is contained in the program. Classes, interfaces, and so on are some examples.

Primitive Data Types


Java basic data types are defined by the programming language, in this instance, Java. It would be impossible to frame programs without primitive data types. Non-primitive data types are built on the foundation of primitive data types.


  • Boolean Data Type in Java

The Boolean data type only has two potential values: true and false. Simple flags that track true/false circumstances are stored in this data type. Although the Boolean data type specifies one bit of information, its "size" cannot be precisely determined.

Example:

Boolean one = false

  • Byte Data Type

An example of a primary data type is the byte data type. It is a signed two's complement integer of 8 bits. It has a value range of -128 to 127. (inclusive). It has a minimum of -128 and a high of 127. It has a default value of 0. The byte data type saves memory in massive arrays where it is most needed. It is because a byte is four times smaller than an integer, and it saves space. It can also be used in place of the data type "int."

Example:

byte a = 10, byte b = -30

  • Short Data Type

A 16-bit signed two's complement integer is the short data type. Its value range is -32,768 to 32,767. (inclusive). It has a minimum of -32,768 and a maximum of 32,767. It has a default value of 0. The short data type, like the byte data type, can be used to save memory. A short data type is twice as small as an integer.

Example:

Short a = 10000, short b = -5000


  • Int Data Type

The int data type is a signed two's complement 32-bit integer. Its value range is - 2,147,483,648 (-231) to 2,147,483,647 (-231). (inclusive). It has a minimum of - 2,147,483,648 and a maximum of 2,147,483,647. It has a default value of 0. Unless there is no memory constraint, the int data type is usually used as the default data type for integral values.

Example:

int x = 100000, int y = -200000

  • Long Data Type

A 64-bit two's complement integer is the long data type. It has a value range of -9,223,372,036,854,775,808(-263) to 9,223,372,036,854,775,807(-263 -1). (inclusive). It has a minimum of 9,223,372,036,854,775,808 and a maximum of 9,223,372,036,854,775,807. It has a default value of 0. When you need a more extensive range of values than int provides, utilize the long data type.

Example:

long c = 100000L, long d = -200000L


  • Float Data Type

Float is a single-precision 32-bit IEEE 754 floating point data type. It has an infinite value range. If you need to preserve memory in big arrays of floating-point integers, use a float (rather than a double). Never use the float data type for accurate numbers like currency. It has a default value of 0.0F.

Example:

float f1 = 234.5f

  • Double Data Type

The IEEE 754 double data type is a double-precision 64-bit floating point. It has an infinite value range. Like the float data type, the double data type is commonly used for decimal values. In addition, the double data type should never be used for accurate numbers such as cash. It has a default value of 0.0d.

Example:

double d1 = 16.9

  • Char Data Type

The char data type represents a single 16-bit Unicode character. Its value range is from 'u0000' (or 0) to 'uffff.' (or 65,535 inclusive). Characters are stored using the char data type.

Example:

char letterJ = 'J'

Why does char in Java use two bytes, and what is u0000?

Java uses the Unicode system rather than the ASCII code system. The Unicode system's lowest range is u0000.


Non-Primitive Data Types


These are the datatypes that have instances like objects. As a result, they are referred to as reference variables. Classes, arrays, strings, and interfaces are the most common types.

  • Classes

These are the user-defined data types. It has class methods and member variables. Objects have blueprinted them.

Example:

class Cipherschools{

int a, b, c;

void teach() {

System.out.println(“Hi I am teaching at Cipherschools”);

}

void learn() {

System.out.println(“Hi I am learning at Cipherschools”);.

}

}

  • Interfaces

These are comparable to courses. However, there is one significant difference: the methods are abstract by default. They have nobody, in other words. Similarly, interfaces, like objects, are class blueprints.

If the class implements an interface, it is expected to provide details for each interface function. If not, the class must be declared abstract.

Example:

interface CipherSchools {

void teach();

void learn();

}

class CipherSchoolsCls implements CipherSchools {

public void teach() {

System.out.println("I teach at CipherSchools ");

}

public void learn() {

System.out.println("I learn at CipherSchools");

}

public static void main(String[] args) throws IOException {

CipherSchoolsCls ob = new CipherSchoolsCls();

ob.teach();

ob.learn();

}

}

  • Strings

You may know that string is a collection of characters, but in Java String is an entirely distinct class. It is found in “Java.lang.String”. Strings, conversely, conclude with a '0' character. String manipulation methods in Java include substring, length, and many others.


Example:

String s=" CipherSchools is a fun place to learn";

String sub=s.substring(0,13);

System.out.println(sub);


Output:

CipherSchools


  • Arrays

Arrays are types of memory that can hold a collection of similar data. They are cataloged. Arrays always begin indexing at 0. Java supports dynamic array allocation. Arrays can be used as method parameters, local variables, and static fields in Java.

Example- int arr[] = new int[50];


This results in the creation of a storage area for 50 integers.

import java.io. * ;

import java.util. * ;

class CipherSchoolsArray {

public static void main(String[] args) throws IOException {

int i;

Scanner sc = new Scanner(System. in );

int arr[] = new int[] {1,2,3,4,5};

int arr1[] = new int[5];

for (i = 0; i < 5; i++) {

System.out.println("Enter your number");

arr1[i] = sc.nextInt();

}

System.out.println(“The array which was previously assigned”);

for (i = 0; i < 5; i++) {

System.out.println(arr[i]);

}

System.out.println("");

System.out.println("The array you entered is:");

for (i = 0; i < 5; i++) {

System.out.println(arr1[i]);

}

}

}


Types of Loops in Java

In Java, looping is defined as running some lines of code in an orderly sequence until a condition is met. We need the condition since we do not want the loop to run indefinitely. The loop is terminated as soon as this condition is met.

There are four types of loops in Java, as mentioned below:


  • for loop

  • Enhanced for loop

  • while loop

  • do-while loop


  • for loop


The loop itself is defined by three key factors in Java for a loop. The initialization statement, a testing condition, and an increment or decrement portion for incrementing/decrementing the control variable are all included.


The basic syntax of Java for loop is as follows:


for(initializing statement;testing condition;increment/decrement)

{

//code to be iterated

}


The loop structure begins with the initializing statement. It includes a variable with an initial value specified by the programmer. When the control changes into the loop, this is the control variable's value. This statement, however, is only executed once.


If a variable is declared within this section, the variable's scope remains limited to the loop.


Example:


import java.io. * ;

public class ForLoop {

public static void main(String[] args) {

int i;

for (i = 0; i <= 10; i++) {

System.out.println("Studying for loops at CipherSchools");

System.out.println("Value of i = " + i);

}

}

}


  • Enhanced for loop


This is comparable to a for loop but offers additional capabilities. It can be used to iterate over a collection's elements without knowing the index of each component. You don't even need to know how extensive the collection is.


This improved for loop, however, has significant drawbacks. This loop object is immutable, meaning the values received during loop execution are read-only. Unlike other loops, this loop does not allow you to alter the values in the collection.


In Java, extended for loop syntax is:


for(<datatype> <variable_name>:<collection_name>)

{

//Statements;

}

Example


import java.io. * ;

public class EnhancedFor {

public static void main(String[] args) {

String array[] = {

"CipherSchools",

"C",

"Java"

};

for (String a: array) {

System.out.println(a);

}

}

}

  • While loop

While loops are helpful, we cannot always know the extent of a loop when we define one. For example, if we were given a dynamic collection and told to iterate through each piece, for loops would be useless because we needed to know the size of the collection. Then we'd have to utilize a while loop or an improved for loop.

A while loop repeats a collection of statements until the boolean condition returns false. The loop iterates as long as the supplied condition evaluates to true.

The condition of the loop structure is first verified, and the control enters the loop structure only if the condition evaluates to true. As a result, it is known as an entry-controlled loop. The loop's body usually contains a variable that controls the previously indicated boolean condition.

The basic syntax of a Java while loop is as follows:

while(boolean condition)


{

//statements;

}

The loop ends when the condition returns false.

Example:

import java.io. * ;

public class WhileLoop {

public static void main(String[] args) {

int i = 0;

while (i < 5) {

System.out.println("CipherSchools");

System.out.println("The value of i is = " + i);

i++;

}

System.out.println("The value of i became " + i + " hence it broke out of the loop");

}

}

  • do-while loop

The do-while loop in Java first runs the statement and then checks for the condition. Aside from that, it is comparable to the while loop. The distinction is that if the condition is true at the start of the loop, the statements are still executed, but in the case of a while loop, the statements are not run at all.

Because it checks the condition after the statements inside it are executed, this is an exit-controlled loop.

Example:

import java.io. * ;

public class DoWhileLoop {

public static void main(String[] args) {

int i = 0;

do {

i++;

System.out.println("Cipherschools");

System.out.println("The value of i is " + i);

}

while ( i != 5 );

}

}

  • Nested Loops

As the name implies, nested loops are effectively one loop operating inside another. The inner loop begins after the first iteration of the outer loop. When the inner loop completes its iterations and departs, the first iteration of the outer loop is completed, and the second iteration begins. This continues until the outermost loop completes its iterations.

However, nested loops do not always imply two loops. You can nest as many loops as you like within each other if there are two loops, one inside the other, each with N iterations and the other with M iterations. Then the total number of iterations would be M x N.

The Syntax for Nested Loops in Java

for(initializer;condition;increment/decrement)


{


for(initializer;condition;increment/decrement)

{

//code to be nested

}

Example:

public class NestedLoop {

public static void main(String[] args) {

int i, j, k;

k = 0;

for (i = 0; i < 6; i++) {

for (j = 0; j < 6; j++) {

System.out.print(k + "\t");

k++;

}

System.out.println("");

}

}

}


As there are many different forms of loops present in Java, let’s see it working through our video tutorials – How to use loops in Java


Conditional Statements

These claims are solely dependent on the program's condition flow. It is broken into three sections as follows:

  • if the statement

The statement implies that if a specific statement returns true, the block wrapped within the if statement is executed.

Syntax:

if (condition) {

action to be performed

}

Example:

int a = 20;

int b = 18;

if (x > y) {

System.out.println("a is greater than b");

}

  • if else statement

If a condition in this statement is true, then the if block is executed. Otherwise, the else block is run.

Syntax:

if (condition) {

action1;

}

else {

action2

}

Example:

int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

}

// Outputs "Good evening."

  • Else-if Statement

This sentence contains an else block that surrounds an if statement.

Syntax:

if (condition) {

action 1

}

else if (condition2) {

action 2

}

Example:

int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

}

// Outputs "Good evening."

  • Switch statement

The switch case is used to examine various conditions. The variable's value determines it. The value of the mentioned variable indicates the flow of control to either of the mentioned case blocks.

The syntax of the switch case is mentioned below.

switch (var_name)

case value1:

action1;

break;

case value2:

action2;

break;

default:

action3;

break;

Example:

// Java Program for checking the size

// using the switch...case statement

class Main {

public static void main(String[] args) {

int number = 44;

String size;

// switch statement to check the size

switch (number) {

case 29:

size = "Small";

break;

case 42:

size = "Medium";

break;

// match the value of the week

case 44:

size = "Large";

break;

case 48:

size = "Extra Large";

break;

default:

size = "Unknown";

break;

}

System.out.println("Size: " + size);

}

}

  • Iteration Statements

These statements in programming are primarily known as loops and run a specific set of programs a fixed number of times.

Iterative statements include the following:

  • For loop

The for loop is in charge of running the code snippet inside it a predefined number of times.

Example:

for (i = 0; i < 5; i++) {

System.out.println(“Cipherschools”);

}

  • While loop

This loop continues continuously until the condition is met.

Example:

while (i < 6) {

System.out.println(“Cipherschools”);

i++;

}

  • Do-while Loop

This is equivalent to the while loop. The sole difference is that the execution occurs once, even if the condition is false.

Example:

do {

System.out.println(“Cipherschools”);

}

while ( i > 6 );

Jump Statements/Control Flow Statements

We sometimes need to break a loop while it is running.

1. Break Statement

This breaks the nearest loop mentioned within. When the current scope expires, the execution resumes from the next line.

2. Continue Statement

This executes the loop from the next iteration and skips the current execution.

Example:

while (i < 10) {

if (i == 3) continue;

i++;

}

3. Return Statement

Return statements are commonly used in methods to return a value when the function has completed its execution. The remaining function is not executed after the return statement has been executed.

Conclusion

Finally, data types, conditions, and loops are fundamental notions in the Java programming language that provide considerable advantages. Programmers can improve data accuracy, decrease errors, and make code more readable and easier to maintain by selecting appropriate data types.

Conditions allow developers to regulate program flow by making decisions based on user input or other criteria, increasing flexibility and adaptability. Loops are handy for handling enormous amounts of data or completing complex calculations, resulting in more efficient and effective code.

Combining these notions into Java programs improves program accuracy, flexibility, and efficiency, making Java a versatile and powerful language for constructing complex software applications.


25 views

Comments


Subscribe to Our Newsletter

Thanks for submitting!

bottom of page