A Complete Java Basics Tutorial

Java is a popular general-purpose programming language and computing platform. It is a high level, class-based, and object-oriented programming language. Java runs on multiple platforms. It means that it can work on any software or hardware platform. It has a virtual machine specification.

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 secured 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 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 the 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.
  1. public class TestExample {  
  2.     public static void main(String args[]) {  
  3.         System.out.println("This is a Simple Example of Java");  
  4.     }  
Output
test-example 
 

When is Java used?

 
Mainly, Java is developed for a small embedded system like set-top boxes but nowadays, there are many Java devices, used in a market. Now, Java 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 a 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 Java language project in 1991. It’s organized mainly for digital devices like set-top boxes. James Gosling team called it as 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 “JAVA”.
 

The question arises, Why Green Team member 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 they choose 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 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 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

 
Java is an object-oriented programming language.  It means that all things are objects in Java and 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 languages 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, Java compiler changes that source code into byte code and the byte code is a platform-independent. We can run it 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 makes it secure like it has 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 lack of pointers avoids security problem. 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 Application 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 languages because it has many features, which builds it faster than others like just in time compiler.
 

Multi-threaded

 
In multithreading, many threads work together, so that 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 to other languages and provides whole information, which is easily verifiable, free from ambiguity and we write bug-free programs.
 

Differentiation between C++ and Java

 
Comparision  C++  Java
Platform-independent C++ is platform-dependent language.
Java is a platform-independent language.
Used for C++ 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 operators overloading. Java doesn't support operator overloading.
Pointers C++ makes use of pointers. We can write a pointer program in C++. Java support pointers internally but we can't write a program in Java.
Compiler and interpreter C++ uses only the compiler. Java uses both compiler and interpreter.
Call by value and Call by reference C++ supports call by value and call by reference both. Java supports only call by value.
Structure and union  C++ supports structures and unions Java does't support structures and unions.
Thread support It doesn't have built-in support for the threads. It relies on the third-party libraries for thread support. It has built-in thread support.
Documentation comment C++ does't support documentation comments. Java supports documentation comments.
 
Now, we will create a simple program of Java. First, we need to check, in 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?

  1. public class TestExample1 {  
  2.     public static void main(String args[]) {  
  3.         System.out.println("Hello Csharp Corner");  
  4.     }  
  5. }  
     
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 keyword 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 main, you cannot run your program.
    • String [] args is used for a command-line argument.

  3. System.out.println() 
     it used to print a statement.
     
    • System is a class name, which is 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 Java compiler (javac) and 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, classloader loads the class file, bytecode verifier verifies the code, which is legally correct and last interpreter reads bytecode file and run it.
 

How to set 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 command prompt, copy the path of 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 bin directory and write it in the variable value - ok.
     
 set-pathin-java
 

Setting path in other like Linux, 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 as 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 a 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 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 Symbolic Reference.
 
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 loads 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, 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 thread, 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 is 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 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 the large character sets has a variable length. Some common characters are encoded as single bytes, other requires two or more byte
Unicode solves the two problems due to which Java uses Unicode system.
 
In Unicode, a character holds 2 byte due to which Java also uses 2 byte for the characters.
 
Its lowest value is - \u0000 and
 
Highest value is - \uFFFF.
 

Java Tokens

 
Java Tokens are the smallest individual building block or smallest unit 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, its reserved words in 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 as 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 having 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 reference. 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 marks the start and end of a block of code containing more than one executable statement.
  • comma (, ): It is used to separate more than one statements 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 some special symbols that are used to perform mathematical and logical operations on the operands and returns 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. 
  1. int a = 5;  
  2. String msg = "Hello"
     

Arithmetic Operators

 
Arithmetic operators are used to achieve mathematical calculations like algebra. The following table lists arithmetic operators. 
  1. int p = 25;      
  2. int q = 15;      
  3. int res = p + q; //addition    
  4. System.out.println("p + q = " + res);      
  5. res = p - q; //substraction          
  6. System.out.println("p - q = " + res);      
  7. res = p * q; //multiplication    
  8. System.out.println("p * q = " + res);      
  9. res = p / q; //division           
  10. System.out.println("p / q = " + res);   

Relational Operators

 
Relational operators are used to judge against the two operands and give results in a boolean form. The following table lists all the relational operators.
  1. int p = 25;            
  2.  int q = 35;            
  3. boolean res ;            
  4.  res = p == q;            
  5. System.out.println("p == q : " + res);            
  6. res = p != q;            
  7. System.out.println("p != q : " + res);     
  8. res = p > q;     
  9. System.out.println("p is greater than q : " + res);     
  10. res = p >= q;     
  11. System.out.println("p is greater than or equal to q : " + res);     
  12. res = p < q;     
  13. System.out.println("p is less than q : " + res);  
     

Unary Operators

 
Java Unary Operators are engaged in a single operand. 
  1. int p = 20;      
  2. int res;      
  3. System.out.println( "p : " +p);      
  4. res = ++p;      
  5. System.out.println("++p = " + res);      
  6. res = p++;   
     

Logical Operators

 
Logical operators are used to do logical operations in Java. It operates on two boolean values and returns a boolean value as a result.  
  1. boolean p = true;      
  2. boolean q = false;      
  3. boolean res = (p && q);      
  4. System.out.println("p && q = " + res);      
  5. res = (p || q);      
  6. System.out.println("p || q = " + res);      
  7. res = !p;      
  8. 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. 
  1. int p = 10;      
  2. int q = 20;      
  3. int res = (p > 10) ? p : q;      
  4. System.out.println("result 1 is: " + res);      
  5. res = (q > 10) ? p : q;      
  6. System.out.println("result 2 is: " + res); 
     

Bitwise Operators 

 
Bitwise operators perform bit shift operation on integral types only and not other types. 
  1. int b = 7;    
  2. System.out.println("a&b = " + (a & b));    
  3. System.out.println("a|b = " + (a | b));    
  4. System.out.println("a^b = " + (a ^ b));   
     
For more information about Java Operators Please Click Here.
 

Variables in Java

 
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 as a variable.
 
Variable has any value, which is located in the memory.
 

How we declare the Variables in Java?

  1. int x ;     (int is a data type and x is a variable name).  
  2. int y;  
  3. int x, y;  
  4. int x = 4 , y = 5;  
  5. byte p = 65;  
  6. double pi = 3.1415;  
  7. char q = ‘s’ ; 
     
The complete program is listed below.
  1. public class VariableExampleProgram {  
  2.     int x = 4;     //(int is a data type and x is a variable name).  
  3.     int y = 5;  
  4.     byte p = 65;  
  5.     double pi = 3.1415;  
  6.     char q = 's';  
  7.     public void display() {  
  8.         System.out.println("Value of x =" + x);  
  9.         System.out.println("Value of y =" + y);  
  10.         System.out.println("Value of p =" + p);  
  11.         System.out.println("Value of pi =" + pi);  
  12.         System.out.println("Value of q =" + q);  
  13.     }  
  14.     public static void main(String agrs[]) {  
  15.         VariableExampleProgram var = new VariableExampleProgram();  
  16.         var.display();  
  17.     }  
  18.  
Output
 
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 which 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 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 objects string and various type 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
  1. int no = 25;  
  2. if (no > 18) {  
  3.       System.out.println("Number is greater than 18");  
  4. }        
Explanation: In the following example, we are checking if the number is greater then 18 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 else statement.
 
if-else-statement-flowchart
Syntax
 
If (condition) { 
   // statement code. 
} else { 
//statement}
 
Example
  1. int num = 15;  
  2. if (num % 2 == 0) {  
  3.     System.out.println("this number is even");  
  4. else {  
  5.      System.out.println("this number is odd");  
  6.  
Explanation: In the following example, we are checking if the number is divisible by 2 and 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
  1. int marks = 80;  
  2. if (marks < 50) {  
  3.    System.out.println("C grade");  
  4. else if (marks >= 50 && marks < 60) {  
  5.     System.out.println("C+ grade");  
  6. else if (marks >= 60 && marks < 70) {  
  7.     System.out.println("B grade");  
  8. else if (marks >= 70 && marks < 80) {  
  9.     System.out.println("B+ grade");  
  10. else if (marks >= 80 && marks < 90) {  
  11.     System.out.println("A grade");  
  12. else if (marks >= 90 && marks < 100) {  
  13.     System.out.println("A+ grade");  
  14. else {  
  15.     System.out.println("Unfounded");  
ExplanationIn the following example, we are checking the grade of the student whose marks is 80 "compiler checks the if conditions and when 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 the values. 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
  1. char grade = 'C';  
  2.         switch (grade) {  
  3.             case 'A':  
  4.                 System.out.println("Excellent");  
  5.                 break;  
  6.             case 'B':  
  7.                 System.out.println("Very Good");  
  8.                 break;  
  9.             case 'C':  
  10.                 System.out.println("Good");  
  11.                 break;  
  12.             case 'D':  
  13.                 System.out.println("Passed");  
  14.             case 'F':  
  15.                 System.out.println("Better try again");  
  16.                 break;  
  17.             default:  
  18.                 System.out.println("Invalid ");  
  19.         }  
  20.         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 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 loop work? 

  1. Initialization is executed. This is executed only once.
  2. 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 step2.
Example
  1. public class ForLoopExample {  
  2.     public static void main(String[] args) {  
  3.         for (int i = 1; i < 8; i++) {  
  4.             System.out.println("for loop : " + i);  
  5.         }  
  6.     }  
  7.  
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
  1. public class ForEachExm {  
  2.         public static void main(String[] args) {  
  3.             int arr[] = {12345};  
  4.             for (int s : arr) {  
  5.                 System.out.println("Array:" + s);  
  6.             }  
  7.         }  
  8.     } 
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. 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 as an entry-control loop.
 
The execution of the body of the loop depends upon the value of the test condition. 
 
Example 
  1. public class WhileLoopExample {  
  2.     public static void main(String[] args) {  
  3.         int n = 1;  
  4.         while (n <= 10) {  
  5.             n++;  
  6.         }  
  7.     }  
  8.  
Output
while-loop-example-program 
 

Do-while loop
 

There is another loop control structure which 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 while loop, the statement doesn’t execute the body of the loop even once, if the condition is false. Due to this “do-while loop” is also called the exit-control loop.
 
Example
  1. public class DoWhileExm {  
  2.         public static void main(String[] args) {  
  3.             int n = 1;  
  4.             do {  
  5.                 System.out.println("do-while loop : " + n);  
  6.                 n++;  
  7.             } while (n < 10);  
  8.         }  
  9.     } 
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 next loop iteration. 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 
 
For more about the break and continue  Click Here
 

Methods in Java

 
A method is a block of code which 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.
  1. public class MethodExample {  
  2.         static void myMethod() {  
  3.             System.out.println("Hello World!");  
  4.         }  
  5.         public static void main(String[] args) {  
  6.             myMethod();  
  7.         }  
  8.     } 
     
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.
  1. public class CallByValueExample {  
  2.     public static void main(String[] args) {  
  3.         int a = 30;  
  4.         int b = 45;  
  5.         System.out.println("Before swapping, a = " + a + " and b = " + b);  
  6.         // Invoke the swap method  
  7.         swapFunction(a, b);  
  8.         System.out.println("After swapping, a = " + a + " and b is " + b);  
  9.     }  
  10.   
  11.     public static void swapFunction(int a, int b) {  
  12.         System.out.println("Before swapping(Inside), a = " + a + " b = " + b);  
  13.         int c = a;  
  14.         a = b;  
  15.         b = c;  
  16.         System.out.println("After swapping(Inside), a = " + a + " b = " + b);  
  17.     }  
  18.  
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 actual parameters of the caller.
The complete program is listed below.
  1. public class CallByReferenceExample{  
  2.     public static void main(String[] args) {  
  3.         IntWrapper a = new IntWrapper(30);  
  4.         IntWrapper b = new IntWrapper(45);  
  5.         System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);  
  6.         swapFunction(a, b);  
  7.         System.out.println("After swapping, a = " + a.a + " and b is " + b.a);  
  8.     }  
  9.   
  10.     public static void swapFunction(IntWrapper a, IntWrapper b) {  
  11.         System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);  
  12.         // Swap n1 with n2  
  13.         IntWrapper c = new IntWrapper(a.a);  
  14.         a.a = b.a;  
  15.         b.a = c.a;  
  16.         System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);  
  17.     }  
  18. }  
  19.   
  20. class IntWrapper {  
  21.     public int a;  
  22.     public IntWrapper(int a) {  
  23.         this.a = a;  
  24.     }  
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. Size of an array must be provided before storing data. In array, elements are accessed using indexes. Each element can be uniquely identified by their 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 which can be performed on the data into 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 in the last will be the element that will be removed first. The queue has two data types which can be performed on the data into 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) which can be linked to other elements, sometimes hierarchically and sometimes not. The tree data structure can be defined as a set of nodes which 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 the index notation. This class contains various inbuilt methods, which help in making data retrieval and manipulation easy.
 
For more about ArrayList 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.