Java Basics

Introduction

Java technology is both a programming language and a platform. It is a high-level, class-based, and object-oriented programming language. Java is secure and a powerful language. Java runs on multiple platforms. It means that it can work on any software or hardware platform. It has a virtual machine specification. It has its own runtime environment JRE (Java Runtime Environment) and an API (Application Programming Interface) Specification.

Java Programming Language 

The Java programming language is a high-level language that can be characterized by all of the following buzzwords:

  • Simple
  • Object-oriented
  • Distributed
  • Multithreaded
  • Dynamic
  • Portable
  • Robust
  • Secure

In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

java-software-development-process

An overview of the software development process. 

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

java-same-application-on-multiple-plateforms

Through the Java VM, the same application is capable of running on multiple platforms. 

The Java Platform 

A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.

The Java platform has two components

  • The Java Virtual Machine
  • The Java Application Programming Interface (API)

You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms.

The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.

java_plateform 

The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.

The terms"Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.

Example of Java 

In this program, we will create a class TestExample and print the statement.

public class TestExample {  
    public static void main(String args[]) {  
        System.out.println("This is a Simple Example of Java");  
    }  
} 

Output

test-example

When is Java used?

Mainly, Java is developed for small embedded systems like set-top boxes but nowadays, there are many Java devices, used in the market. Now, Java is used in set-top-boxes, many digital devices, mobiles, games, etc.

Java Applications

There are 4 types of Applications, where Java is used:

  1. Standalone Application
    In Java, we use AWT and Swing to create Standalone Applications. Standalone Applications are known as desktop application, which is installed on every machine.
  2. Web Application
    In a Web Application, we use Servlet and JSP technologies in Java. Web Applications are used to design a dynamic page and it runs on the server side.
  3. Enterprise Application.
    In Enterprise Applications, we use EJB in Java. These types of applications are distributed in nature like Banking Applications etc. Its main advantages are robust security, load balancing, and clustering.
  4. Mobile Application.
    In Mobile Applications, we use Android and Java ME in Java. It is mainly designed for mobile devices.

History Of Java

Java programming language was made by James Gosling and released in 1995. James Gosling started the Java language project in 1991. It’s organized mainly for digital devices like set-top boxes. James Gosling's team called it a Green Team. The language, initially called Oak, as the Oaktree is a symbol of strength and strong. It’s also a national tree of many other countries but it is already a trademark of Oak Technologies because they changed that name to “JAVA”.

The question arises, Why did Green Team members choose Java name for a programming language?

James Gosling and other team members choose Java because they want something, which can cast the features of the language. Due to this, why did they choose a Java name, and all the team members like that name? Java is the first coffee name, which was produced on the island of Indonesia. Java is developed by James Gosling at Sun Microsystems engineers and released in 1995. Now, it is a subsidiary of Oracle Corporation.

Sun engineers released the first version of JDK 1.0 on January 23, 1996. The latest version release of the Java Standard Edition is Java SE 8.

Java Versions

There are many Java versions, which were already been released. 

  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan 1996)
  3. JDK 1.1 (19th Feb 1997)
  4. J2SE 1.2 (8th Dec 1998)
  5. J2SE 1.3 (8th May 2000)
  6. J2SE 1.4 (6th Feb 2002)
  7. J2SE 5.0 (30th Sep 2004)
  8. Java SE 6 (11th Dec 2006)
  9. Java SE 7 (28th July 2011)
  10. Java SE 8 (18th March 2014).
  11. Java SE 9 (September 21, 2017)
  12. Java SE 10 (March 20, 2018) 

What are the major features of Java?

Object-Oriented Programming Language

Java is an object-oriented programming language.  It means that all things are objects in Java and in other words, we can say that Java is a collection of objects

object-oriented

Simple

Java is simple and easy to learn, compared to any other language because it removes many complex parts in the programming and makes it a simple programming language. It is based on OOPS and if you already know the concepts of OOPS, you can easily learn Java.

Platform Independent 

Java has a special feature, as it runs on multiple platforms. It means, when we write any code, the Java compiler changes that source code into byte code and the byte code is platform-independent. We can run it on any software or hardware platform. Due to this, we call it also as a write once and run anywhere.

java-plateform-independent

Secure

It has many features, which make it secure like it has its own runtime environment, and due to this, it does not interact with OS. It is safe against any virus too.

Portable

Java programming language is portable because we write the code once, Java compiler compiles it as byte code and the byte code is run on every platform.

Robust 

Java has robust memory management and the lack of pointers avoids security problems. It has an automatic garbage collection, exception handling, and type-checking mechanism in Java.

Distributed

With the help of EJB and RMI in Java, we can design distributed Applications and we can use any file by calling a method from any machine through the internet.

High performance 

Java performance is high for any other language because it has many features, which build it faster than others like just in time compiler.

Multi-threaded

In multithreading, many threads work together, so with the help of this feature, the developers can do multiple works at a time. It helps to save time and save memory and multithreading is used for the development of games also.

Dynamic 

Java is more dynamic than other languages and provides whole information, which is easily verifiable, and free from ambiguity and we write bug-free programs.

Differentiation between C++ and Java

Comparison C++ Java
Platform-independent C++ is a platform-dependent language. Java is a platform-independent language.
Used for C++ is mostly used for System programming. Java is mostly used for application programming.
goto statement C++ supports the goto statement. Java doesn't support the goto statement.
multiple inheritances C++ supports multiple inheritances. Java doesn't support multiple inheritances.
Operator overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ makes use of pointers. We can write a pointer program in C++. Java supports pointers internally but we can't write a program in Java.
Compiler and interpreter C++ uses only the compiler. Java uses both a compiler and an interpreter.
Call by value and Call by reference C++ supports the call by value and call by reference both. Java supports only calls by value.
Structure and union C++ supports structures and unions Java doesn't support structures and unions.
Thread support It doesn't have built-in support for the threads. It relies on third-party libraries for thread support. It has built-in thread support.
Documentation comment C++ doesn't support documentation comments. Java supports documentation comments.

Note. Now, we will create a simple program of Java. First, we need to check, which software, we need to write a program in Java.

  • Linux or Windows xp/7/8 operating system.
  • Java JDK 8
  • Notepad or any other text editor

How to write a program in Java?

public class TestExample1 {  
    public static void main(String args[]) {  
        System.out.println("Hello Csharp Corner");  
    }  
}  

Step 1. Write that program in Notepad first.

Step 2. Save this file as a TestExample1.java.

Step 3. Afterward, open the command prompt window.

Step 4. Compile the program: javac TestExample1.java.

Step 5. Run the program: java TestExample1.

Output

test-example1

Explanation of the program-

  1.  class TestExample1{
    the class keyword is used to declare a class in Java such as TestExample1 is a class name.
  2. Public static void main(String args[]){
    • public is an access modifier and is publically accessible everywhere means it’s visible to all.
    • static is a keyword. When we use static keywords with any method, it is called as a static method. It is used basically in memory management and there is no need to create an object to call it a static method.
    • void is a return type and it’s not returning any value to a method.
    • main is used to start a program. Without the main, you cannot run your program.
    • String [] args is used for a command-line argument.
  3. System.out.println() 
     it is used to print a statement.
    • System is a class name, which is an inbuilt class.
    • out is a static object of the class.
    • println is a method to print a statement. 

One thing is important to know, how to set a path in Java. If we are not first, set a path. Hence, it gives an error that “javac is not recognized as an internal or external command”. The path is not required, if you save your file in JDK/bin directory and if you have not saved the file inside JDK/bin directory. Hence, it gives an error and you need to set a path to solve the problem.

How the Java program internally works?

Previously, we learn, how to design and create a program in Java. Now, we learn about, how the program works internally.

First, we use any editor or IDE to write source code. Afterward, this source code (.java file) is compiled by the Java compiler (javac) and the Java compiler changes the file in Java Bytecodes (.class). Run that file (java) and get an output.  

internal-working-of-program-in-java

At a runtime- how the Java program works?

java-program-runtime-working

At the runtime, first, the classloader loads the class file, the bytecode verifier verifies the code, which is legally correct, and the last interpreter reads the bytecode file and runs it.

How to set a path in Java?

We already know, the set path is important, because when the path is not set, it gives an error and our program is not run at that time. When we use javac and java commands, our system does not know about them. Due to this, it’s required to set the path.

Let’s see, how to set the path for Windows: Let’s see, how to set the path for Windows:

  1.  We can set the path at temporary bases such as:
    First, open the command prompt, copy the path of the JDK/bin directory, and paste it in the command prompt: set path=copied_path.
  2. It is a waste of time, as it needs to set the path every time. it’s good to set the path on permanent bases:
    Right-click My Computer and its properties, advanced tab - environment variables - new tab - write path in the variable name – copy the path bin from the bin directory and write it in the variable value - ok.

 set-pathin-java

Setting path in others like Linux, and UNIX.

Set the path in Linux, which is as same as setting the path in Windows. The only difference is that in Linux, we use export rather than set such as-

export PATH=$PATH:/home/jdk1.6.01/bin/.

What are JDK, JRE, and JVM?

JDK

JDK stands for Java development kit. It physically exists. It contains all the development tools, which we use in Java such as compilers and debuggers etc. and It also contains everything, which is in the JRE.

JRE

JRE stands for Java runtime environment. It physically exists. It provides a runtime environment and contains Java libraries, JVM (Java virtual machine and other files which are used in Java).

JVM

JVM stands for Java virtual machine. It does not physically exist because it is a virtual machine in Java and it is used to run the Java bytecode. Since it does not understand the source code and when the compiler changes the source code into bytecode. This time, it’s used to run bytecode and this bytecode is portable. We can run the bytecode on any platform and that’s why Java is called an independent platform or independent language.

java-jdk-jre-jvm

How JVM works internally?

JVM (Java virtual machine) is a very important part of Java, which analyzes and executes Java bytecode. Hence, we need to know, how JVM works internally. JVM is a virtual machine. JVM is platform-dependent because configurations of all OS are different and it helps in the execution of the program.

Main features of JVM

  1. Network byte order- In Java, when we create class files, the class file uses the network byte order and JVM uses the network byte order. This is used for network transfer. 
  2. Clear defining the primitive data type- The JVM defines the primitive data type to maintain its guarantee of platform independence.
  3. Garbage Collection- The class object is explicitly created by the user and it is automatically destroyed through garbage collection.
  4. Symbolic Reference- In Java, except for primitive data types, all the classes and all interfaces are referred to as Symbolic References.
  5. Stack-based Machine- All the famous architectures run, based on the registers but Java virtual machine runs, based on a stack.

JVM Performs many works internally:

  • It helps to load the code.
  • Check the code internally.
  • Helps in the execution of code.
  • Provide runtime environment.

Now, let’s see the internal work process of JVM.

JVM-internal-working

Explanation of Figure

  • Classloader- In JVM, the classloader is mainly used to load the class files.
  • Class Area- It is used to store each class structure like field and method.
  • Heap- Heap memory is used at runtime, in which objects are allocated.
  • Stack- Java stack is used to store frames. Mainly, it is used in threads, because the single thread has a private JVM stack and it is created at the same time when a thread is created.
  • PC Register- PC Register stands for Program Counter Register. It contains the address of JVM.
  • Native Method Stack- It is used to store the native methods, which are used in the Application.
  • Execution Engine- It has three main things.
  • Virtual processer- It is used at the time of execution.
  • Interpreter- It is used to read the bytecode and Just-In-Time compiler (JIT): It is used to reduce the time, required for compilation and improves the performance of compile time.

Unicode System in Java

Unicode is a Universal international standard encoding. It is a new language standard. This is efficient in representing most of the world’s written languages. Many other languages use the ASCII code system but Java uses the UNICODE system.

Many other language standards caused two problems that are:

  1. Particular code value corresponds to the different letters in the various language standards.
  2. The encoding for the languages with large character sets has a variable length. Some common characters are encoded as single bytes, while other requires two or more byte

Unicode solves the two problems due to which Java uses the Unicode system.

In Unicode, a character holds 2 bytes due to which Java also uses 2 bytes for the characters.

  • Its lowest value is - \u0000 and
  • The highest value is - \uFFFF.

Java Tokens

Java Tokens are the smallest individual building block or smallest units of a Java program; the Java compiler uses it for constructing expressions and statements. Java program is a collection of different types of tokens, comments, and white spaces. 

When you compile a program, the compiler scans the text in your source code and extracts individual tokens. While tokenizing the source file, the compiler recognizes and subsequently removes whitespaces (spaces, tabs, newline, and form feeds) and the text enclosed within comments. 

Java tokens can be classified as follows-

1) Reserved Keywords in Java

Keywords are pre-defined or reserved words in a programming language. You can't use the keyword as an identifier in your Java programs, it's reserved words in the Java library and used to perform an internal operation. Here is the list of reserved keywords of Java.

java-reserved-keywords

2) Identifiers in Java

A Java identifier is the symbolic name that a programmer gives to various programming elements such as a variables method, class, array, etc. These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords.

Example of Valid Identifiers-

  • myVariable
  • MyClass
  • ClassExample
  • x
  • x1
  • _myvariable
  • sum_of_array
  • cSharpCorner

3) Constants or Literals in Java

Constants are also like normal variables. But, the only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called literals. That can be classified as integer literals, string literals, and boolean literals.

Example

final data_type variable_name;

4) Special Symbols in Java

Java has some special meaning and thus, cannot be used for some other purpose.  The following special symbols are used in Java.

  • Brackets[]- Opening and closing brackets are used as array element references. These indicate single and multidimensional subscripts.
  • Parentheses()- These special symbols are used to indicate function calls and function parameters.
  • Braces{}- These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement.
  • comma (, )- It is used to separate more than one statement like for separating parameters in function calls.
  • Semicolon- It is an operator that essentially invokes something called an initialization list.
  • Asterisk (*) It is used to create a pointer variable.

Operators in Java

Operators are special symbols that are used to perform mathematical and logical operations on the operands and return the result. There are several types of operators in java that are used to perform different operations. For example, the  (+) operator symbol is used to add two or more operands and returns the addition as a result.

There are many types of operators are available in Java.

Java Assignment Operator

An assignment operator is one of the most used and common operators, which we use to assign a value on its right to the operand on its left. 

int a = 5;  
String msg = "Hello"; 

Arithmetic Operators

Arithmetic operators are used to achieving mathematical calculations like algebra. The following table lists arithmetic operators. 

int p = 25;      
int q = 15;      
int res = p + q; //addition    
System.out.println("p + q = " + res);      
res = p - q; //substraction          
System.out.println("p - q = " + res);      
res = p * q; //multiplication    
System.out.println("p * q = " + res);      
res = p / q; //division           
System.out.println("p / q = " + res);   

Relational Operators

Relational operators are used to judging against the two operands and give results in a boolean form. The following table lists all the relational operators. 

int p = 25;            
 int q = 35;            
boolean res ;            
 res = p == q;            
System.out.println("p == q : " + res);            
res = p != q;            
System.out.println("p != q : " + res);     
res = p > q;     
System.out.println("p is greater than q : " + res);     
res = p >= q;     
System.out.println("p is greater than or equal to q : " + res);     
res = p < q;     
System.out.println("p is less than q : " + res); 

Unary Operators

Java Unary Operators are engaged in a single operand. 

int p = 20;      
int res;      
System.out.println( "p : " +p);      
res = ++p;      
System.out.println("++p = " + res);      
res = p++;   

Logical Operators

Logical operators are used to doing logical operations in Java. It operates on two boolean values and returns a boolean value as a result.  

boolean p = true;      
boolean q = false;      
boolean res = (p && q);      
System.out.println("p && q = " + res);      
res = (p || q);      
System.out.println("p || q = " + res);      
res = !p;      
System.out.println("!p = " + res); 

Conditional(Ternary) Operators

The Java conditional operators select one of two expressions for evaluation, which is based on the value of the first operands.  

int p = 10;      
int q = 20;      
int res = (p > 10) ? p : q;      
System.out.println("result 1 is: " + res);      
res = (q > 10) ? p : q;      
System.out.println("result 2 is: " + res);

Bitwise Operators 

Bitwise operators perform bit shift operations on integral types only and not other types. 

int b = 7;    
System.out.println("a&b = " + (a & b));    
System.out.println("a|b = " + (a | b));    
System.out.println("a^b = " + (a ^ b));   

For more information about Java Operators Please Click Here.

Variables in Java

The variable is a reserved memory location to hold a value. In other words, when we want to store any value and give it a name, that value takes a reserved space in memory and it’s called a variable.

The variable has any value, which is located in the memory.

How do we declare the Variables in Java?

int x ;     (int is a data type and x is a variable name).  
int y;  
int x, y;  
int x = 4 , y = 5;  
byte p = 65;  
double pi = 3.1415;  
char q = ‘s’ ; 

The complete program is listed below.

public class VariableExampleProgram {  
    int x = 4;     //(int is a data type and x is a variable name).  
    int y = 5;  
    byte p = 65;  
    double pi = 3.1415;  
    char q = 's';  
    public void display() {  
        System.out.println("Value of x =" + x);  
        System.out.println("Value of y =" + y);  
        System.out.println("Value of p =" + p);  
        System.out.println("Value of pi =" + pi);  
        System.out.println("Value of q =" + q);  
    }  
    public static void main(String agrs[]) {  
        VariableExampleProgram var = new VariableExampleProgram();  
        var.display();  
    }  
} 
 

Outpu

variable-example-output

Scope of Variables in Java

Global Variables- These variables must be declared inside a class (outside any function). They can be directly accessed anywhere in the class. We can declare class variables anywhere in class, but outside methods.

Syntax

int a;  

private String b; 

Local Variables- Variables declared inside a method have a method-level scope and can’t be accessed outside the method. Local variables don’t exist after the method’s execution is over

Syntax

public void display() {  

int x = 10 ;  

}   

For more information about Variables in Java  Click here.

Data Types in Java

A data type or simply type is an attribute of data that tells the compiler or interpreter how the programmer intends to use the data. For example, a string is a data type that is used to classify text and an integer is a data type used to classify whole numbers.

There are 2 types of Data types in Java 

Primitive data type

Java supports eight primitive data type, which is predefined by Java language and named as a keyword.

Data type  Default size Default value
Byte    1 byte 0
Short    2 byte 0
Int     4 byte 0
Long     8 byte 0L
Float      4 byte 0.0f
Double 8 byte 0.0d
Char  2 byte   ‘\u0000’
Boolean    1 bit false

Maximum value and minimum value

  • Byte- Minimum value is -128 (-2^7) and Maximum value is 127 (inclusive)(2^7 -1)
  • Short-   Minimum value is -32,768 (-2^15) and Maximum value is 32,767 (inclusive) (2^15 -1)
  • Int- Minimum value is -2,147,483,648.(-2^31) and Maximum value is 2,147,483,647(inclusive).(2^31 -1)
  • Long- Minimum value is -9,223,372,036,854,775,808.(-2^63) and Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
  • Char-   Minimum value is '\u0000' (or 0) and Maximum value is '\uffff' (or 65,535 inclusive).

Non-Primitive Data Type

Non-Primitive data types are also known as Reference data types. A reference variable is used to refer to any object of the declared type and by default, its value is null. Class object strings and various types of array variables are reference data types.

Java Control Statements

A program executes from top to bottom so a control statement works as a determiner for deciding the next task of the other statements whether to execute or not. Control statements are used to control the flow of execution.

If-statement

If the statement is very basic of all control flow statements. It is used to test the condition if the condition is right. Hence, it returns the output TRUE. It returns the only boolean value true or false

if-statement-flowchart

Syntax

if(condition){  

// statement.  

}    

Example  

int no = 25;  
if (no > 18) {  
      System.out.println("Number is greater than 18");  
}      

Explanation- In the following example, we are checking if the number is greater than 18 to execute the code. 

If-else statement

If – else statement is also used to test the condition but it provides a secondary path of the execution. It returns if statement when the condition is right and when the condition is wrong. Hence, it returns the else statement.

if-else-statement-flowchart

Syntax

If (condition) {  

   // statement code.  

} else {  

//statement}

Example

int num = 15;  
if (num % 2 == 0) {  
    System.out.println("this number is even");  
} else {  
     System.out.println("this number is odd");  
} 

Explanation- In the following example, we are checking if the number is divisible by 2 and the remainder is 0 then print the statement "this number is even", else will print "this number is odd".

Nested If-else statement

if-else-if statement checks the one condition from the multiple statements. It is a different statement from others.

nested-if-else-statement

Syntax

if(condition1){ 

// code.  

} else if (condition2) {  

//code.  

 

Else if (condition3){  

//code.  

}  

else {  

//code.  

}   

Example

int marks = 80;  
if (marks < 50) {  
   System.out.println("C grade");  
} else if (marks >= 50 && marks < 60) {  
    System.out.println("C+ grade");  
} else if (marks >= 60 && marks < 70) {  
    System.out.println("B grade");  
} else if (marks >= 70 && marks < 80) {  
    System.out.println("B+ grade");  
} else if (marks >= 80 && marks < 90) {  
    System.out.println("A grade");  
} else if (marks >= 90 && marks < 100) {  
    System.out.println("A+ grade");  
} else {  
    System.out.println("Unfounded");  
} 

ExplanationIn the following example, we are checking the grade of the student whose mark is 80 "compiler checks the if conditions, and then if the statement is true the output is A Grade will be printed ", else will print "unfounded". 

Switch statement

Java switch statement is also a control flow statement. It is used when we want to be tested for equality against a list of values. The switch statement returns one statement from the multiple conditions.

switch-statement-flowchart

Syntax

switch(expression){

case value1:

// code.

break;     //it is not compulsory(Optional).

case value2;

// code.

break; 

default: 

// code. 

}

Example

char grade = 'C';  
        switch (grade) {  
            case 'A':  
                System.out.println("Excellent");  
                break;  
            case 'B':  
                System.out.println("Very Good");  
                break;  
            case 'C':  
                System.out.println("Good");  
                break;  
            case 'D':  
                System.out.println("Passed");  
            case 'F':  
                System.out.println("Better try again");  
                break;  
            default:  
                System.out.println("Invalid ");  
        }  
        System.out.println("Your grade is " + grade);  


Explanation: In the following example, we are checking the grade of the student whose given grade is C  "compiler checks the cases and when the condition is true the output is good Grade will be printed ", and if the given grade is not matched with any case the default statement will be printed.

Loops in Java

Loop control statements are used when code may either be executed a fixed number of times or while some condition is true. Java gives you a choice of three types of loop statements: while, do-while, and for. 

The for loop

For statement makes it easier to count the iterations of a loop and works well, where the number of iterations of the loop is referred to before the loop is entered.

Syntax

for(initialization; test condition; increment or decrement)

Statements; 

}

The main purpose is to repeat the statement when the condition remains true. It is similar to the while loop. Also, for loop specifies an initialization instruction and an increment or decrement of the control variable instruction. Hence, this loop is specially designed to perform a repetitive action with a counter.

for-loop-flowchart

How for a loop work? 

  1. Initialization is executed. This is executed only once.
  2. The condition is checked. If it is true, the loop continues otherwise the loop exit and the statement is skipped.
  3. Statements are executed. It can be either a single instruction or a block of instructions enclosed within the curly brackets {}.
  4. Finally, the increment or decrement of the control variable field is executed and then the loop gets back to step 2.

Example

public class ForLoopExample {  
    public static void main(String[] args) {  
        for (int i = 1; i < 8; i++) {  
            System.out.println("for loop : " + i);  
        }  
    }  
} 

Output

for-loop-example-output

For-each loop

It is a Java 5 feature. For each loop or enhanced for loop is used to traverse an array or collection in Java. It is simple to use than for loop because, in it, we don’t need to increment the value and use subscript notation.

It works based on the element and not an index basis. It returns an element one by one in the defined variable.

Syntax

for(Type var: array) 

// statements or code. 

} 

Example

public class ForEachExm {  
        public static void main(String[] args) {  
            int arr[] = {1, 2, 3, 4, 5};  
            for (int s : arr) {  
                System.out.println("Array:" + s);  
            }  
        }  
    } 

Output

foreach-program-output

while loop

It is used to execute a block of a statement as long as a given condition is true. And when the condition becomes false, the control will come out of the loop. The condition is checked every time at the beginning of the loop.

Syntax

while(test condition) 

// body of the loop; 

}

while-loop-flowchart

Here, the test condition is an expression, which expresses how many times the loop run. The body of the loop is a single statement or group of statements, which is enclosed in the braces and they are repeatedly executed till the value of the test condition evaluates to true. The control jumps to the first statement, if the condition initially itself is false, the body of the loop will never be executed. It is also called an entry-control loop.

The execution of the body of the loop depends upon the value of the test condition. 

Example 

public class WhileLoopExample {  
    public static void main(String[] args) {  
        int n = 1;  
        while (n <= 10) {  
            n++;  
        }  
    }  
} 

Output

while-loop-example-program

Do-while loop

There is another loop control structure that is very similar to the while statement called as do while statement.  The only difference is that the expression which determines whether to carry on looping is evaluated at the end of each loop.

Syntax

do { 

Statements; 

} while (test condition);

do-while-flowchart

In the do-while loop, the loop body is executed at least once, if the condition is false. The loop repeats the body when the condition is true. However, in the while loop, the statement doesn’t execute the body of the loop even once, if the condition is false. This “do-while loop” is also called the exit-control loop.

Example

public class DoWhileExm {  
        public static void main(String[] args) {  
            int n = 1;  
            do {  
                System.out.println("do-while loop : " + n);  
                n++;  
            } while (n < 10);  
        }  
    } 

Output

do-while-example-output

Java Jump Statements

In Java, jump statements are mainly used to transfer control to another part of our program depending on the conditions. These statements can be used to jump directly to other statements, skip a specific statement, and so on.

1) break

If we want to go out of a loop then we use a break statement. If we use a break statement in a loop then execution will continue with the immediate next statement outside the loop. After a break, all the remaining statements in the loop are skipped. 

break-statement-flowchart

The break statement is different from the exit. Break jumps the control out of the loop and exit stops the execution of the entire program.

2) continue

Continue statement is sometimes required to skip some part of the loop and to continue the execution with the next loop iteration. The continue statement is mainly used inside the loop helps to bypass the section of a loop and pass the control to the start of the loop to continue the execution with the next loop iteration.

continue-statement-flowchart

Find more about the break and continue  Click Here

Methods in Java

A method is a block of code that only runs when it is called.  You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Methods are used for reuse code: define the code once, and use it many times.

Syntax

class <class-name> { 

    modifier dataType methodName () { 

         //block of code to be executed     } } 

//calling the method, from anywhere 

className.methodName();

The complete program is listed below.

public class MethodExample {  
        static void myMethod() {  
            System.out.println("Hello World!");  
        }  
        public static void main(String[] args) {  
            myMethod();  
        }  
    } 

The output of the following code generates the following output.

method-example-output

Call by value and Call by reference in Java 

Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. 

Call by Value

In call by value method, the value of the actual parameters is copied into the formal parameters. we can say that the value of the variable is used in the function call in the call-by-value method. we can not modify the value of the actual parameter by the formal parameter.

In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.

The complete program is listed below.

public class CallByValueExample {  
    public static void main(String[] args) {  
        int a = 30;  
        int b = 45;  
        System.out.println("Before swapping, a = " + a + " and b = " + b);  
        // Invoke the swap method  
        swapFunction(a, b);  
        System.out.println("After swapping, a = " + a + " and b is " + b);  
    }  
  
    public static void swapFunction(int a, int b) {  
        System.out.println("Before swapping(Inside), a = " + a + " b = " + b);  
        int c = a;  
        a = b;  
        b = c;  
        System.out.println("After swapping(Inside), a = " + a + " b = " + b);  
    }  
} 

The output of the following code generates the following output.

call-by-value-example-output

Call by Reference 

In call by reference, the address of the variable is passed into the function call as the actual parameter. The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.  Both the actual and formal parameters refer to the same locations, so any changes made inside the function are reflected in the actual parameters of the caller.

The complete program is listed below.

public class CallByReferenceExample{  
    public static void main(String[] args) {  
        IntWrapper a = new IntWrapper(30);  
        IntWrapper b = new IntWrapper(45);  
        System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);  
        swapFunction(a, b);  
        System.out.println("After swapping, a = " + a.a + " and b is " + b.a);  
    }  
  
    public static void swapFunction(IntWrapper a, IntWrapper b) {  
        System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);  
        // Swap n1 with n2  
        IntWrapper c = new IntWrapper(a.a);  
        a.a = b.a;  
        b.a = c.a;  
        System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);  
    }  
}  
  
class IntWrapper {  
    public int a;  
    public IntWrapper(int a) {  
        this.a = a;  
    }  
} 

The output of the following code generates the following output.

call-by-reference-example-output

List of Data Structures in Java

A data structure is a particular way of organizing data in a computer so that it can be used effectively.  For example, we can store a list of items having the same data type using the array data structure. It reduces the time and space complexity.

1) Java Arrays

The array is a data structure used to store homogeneous elements at contiguous locations. The size of an array must be provided before storing data. In an array, elements are accessed using indexes. Each element can be uniquely identified by its index in the array.

For example: If we store the data of the students of a class we can use an array to store that data.

For more about Java, Arrays Click Here

2) Java Stack

Stack data structure represents the LIFO(Last In First Out) mechanism. It is an abstract data type that serves as a collection of elements. The stack data type has two operations that can be performed on the data in the stack.

  • Push- Push operation is used to add the element on the top into the collection.
  • POP- Pop operation is used for removing the element from the end of the collection.

3) Java Queue

Queue data structure represents the FIFO(First In First Out) mechanism. It is also an abstract data type that serves as a collection of elements. In the queue data structure, the element which will be added last will be the element that will be removed first. The queue has two data types that can be performed on the data in the queue.

  • Enqueue- Enqueue operation is used to add the element on the top into the collection.
  • Dequeue- Dequeue operation is used to remove the element from the top of the collection.

4) Java Tree

A tree consists of a set of elements (nodes) that can be linked to other elements, sometimes hierarchically and sometimes not. The tree data structure can be defined as a set of nodes that are connected to another node. 

5) Java ArrayList Class

This class uses dynamic arrays for storing elements, and arrays are sequentially arranged in the memory. It implements the List interface and extends the AbstractList class. It can contain duplicate elements, and it maintains insertion order. The elements can be accessed using index notation. This class contains various inbuilt methods, which help in making data retrieval and manipulation easy.

To find more about ArrayList in Java Click Here

6) Java Linked List

This class uses a doubly-linked list to store elements. It maintains insertion order, and it can be used as a list, stack, or queue. It implements the List and Dequeue interfaces and extends the Abstract class. The add and remove methods are used to add and delete. The size method returns the number of lists in the list.

7) Java HashMap 

This is used to store key-value pairs. It implements the Map interface and is not a part of the collection. HashMap uses the hashing technique to store key-value pairs. The key-value pair is called a bucket. Each bucket is stored in an array in the HashMap class. The hashing function works on the key and returns an index at which the bucket is stored. There are chances of two keys returning the same index upon hashing.

Summary

In this article, we learned about all the basics of the Java programming language. we studied the history of Java, features, set the path of Java, variables, data types, operators and data structures of Java programming language with the syntaxes and examples of Java.