Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Java Tutorial For Beginners – Java Programming Made Easy!

Last updated on Jun 19,2023 209.7K Views

Aayushi Johari
A technophile with a passion for unraveling the intricate tapestry of the... A technophile with a passion for unraveling the intricate tapestry of the tech world. I've spent over a decade exploring the fascinating world of...
1 / 72 Blog from Java Core Concepts

In use, today are quite a billion general-purpose computers and a billion more java-enabled cell phones, smartphones, and handheld devices like tablet computers. by this, we can get to know that the java program language is the vast emerging language in today’s world. The other blogs in this Java tutorial series written by our Java Training experts will cover all the important topics of Java & J2EE in depth.

Now, let us move ahead in this Java Tutorial blog, where we will understand each aspect of Java in the following sequence.

What is Java?

Java is an object-oriented programming language. it is now the world’s widely used computer programming language used for building web and desktop applications. It is preferred for meeting many organizations’ enterprise programming requirements and has also become the language of choice for implementing Internet-based applications and Softwares for devices.

Types of Java Applications


1) Standalone Application
Also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. Media player, antivirus, etc. AWT and Swing are some examples of standalone applications that require Java for creating standalone applications.
2) Web Application
the web application runs on the server-side and creates a dynamic page. Many technologies demand the java programming language for creating web applications in Java.

3) Enterprise Application
enterprise application is distributed in nature, for example, banking applications. It is advantageous in many aspects like high-level security, load balancing, and clustering.

4) Mobile Application
mobile application is created for mobile devices is called a . Currently, Android and Java ME fulfill the requirement for creating mobile applications.

Java Platforms / Editions


Platforms of the Java programming language are as follows:

  1. Java Platform, Standard Edition (Java SE)
  2. Java Platform, Enterprise Edition (Java EE)
  3. Java Platform, Micro Edition (Java ME)
  4. Java FX.

History of Java


Java was invented by James Gosling, popularly known as the father of Java, in 1995. leading a team of researchers at Sun Microsystems, James Gosling made efforts to create a new programming language that would allow consumers to electronically communicate with each other through devices. 
fun Fact: the old name of Java is Oak. Oak was a programming language created by James Gosling in 1989, which later evolved to be named Java.

Features of Java


Notable features of Java are as follows:

Object-Oriented:

Java is an Object-oriented programming language as it allows the implementation of an object-oriented design as a working system.

Platform Independent:

unlike other programming languages, java is not compiled into a specific machine instead into a platform-independent byte code which is then distributed over the web and interpreted by the Java Virtual Machine(JVM).

Secure:

Java’s secure feature enables to development of virus-free, tamper-free systems. software like Macafee, Norton is built in Java programming.

Robust:
Java makes an effort to focuses on handling unexpected termination and unexpected actions error checking and runtime. checking.

Multithreaded:
Java’s multithreaded feature allows writing programs that can perform many tasks simultaneously. This feature allows the developers to construct interactive applications that can run smoothly.

Why Learn Java Programming?


Benefits to learn Java programming language:

  1. Java is very easy to learn.
  2. Java developers are in demand
  3. it easy to get a job as a Java programmer.
  4. It has a good collection of open-source libraries.
  5. Java is free.

Java – Object & Classes

Object:

An object is an instance of a class. It is an entity that has a state and behavior which can be physical or logical.

Class:

A class is a collection of objects with common properties. It is a template or blueprint that creates an object. It is a logical entity and can’t be physical. it comprises of:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

What are the types of Java programs?

Java Applets:

Java applet is a graphical user interface on which you can place GUI components or draw using techniques. It is embedded in an HTML page and is executed by using a Java-enabled web browser.

syntax:

  • import java.awt.Graphics;

to enable applet to draw graphics

  • import javax.swing.JApplet;

used to create applets.

Installation of Java

The first step of learning Java would be to install and set up Java Environment. I will redirect you to the download link for Java. Once you enter the downloading web page, you will be able to see something like this as shown below.

Installation of Java

Once you download the required JDK file, go ahead and set the environment for Java. Go to windows advanced settings and select environment variables. You should be able to see the following Dialogue box as shown below.

Steps to locate Environment variables.

  • Go to Start and search for ‘System’
  • Click on ‘System’
  • Click on ‘Advanced system settings’
  • Click on ‘Environment Variables’ under ‘Advanced’ tab  as shown below

System-Properties-java-installation-How-to-Install-Selenium-in-Java-Edureka Java Tutorial

Next, under system variables choose new and enter the variable name as ‘JAVA_HOME’ and the full path to Java installation directory as per your system as shown below

Below figure depicts the configuration of environment variable name and value.

Java Tutorial: New-System-Variable-java-installation-How-to-Install-Selenium-Edureka

Next thing that you have to do is to configure your environment variables. Let’s see how to do that. Here, you have to edit the path of the system variable as shown below.

Java Tutorial: Environment-Variable-path-java-installation-How-to-Install-Selenium-Edureka

Under ‘Variable value’, at the end of the line, enter the following path –  %JAVA_HOME%bin;
Now, you can click ‘OK’ and you are done.

Now to cross-check the installation, just run following command in cmd – java -version. It should display the installed version of Java in your system.

Java Tutorial

Now You have successfully installed Java into your local system.

Java Example

lets us understand java with one of it programming code:

the below example illustrates the Java programming language and some of its features:

________________________________________________


 	public class Edureka
           { 
 	public static void main(String args[])
 	{ 
 System.out.println("Welcome to Edureka!!");
 	} 
 	}

________________________________________________

Output: Welcome to Edureka!!

Explanation:

Line 1: we declare a class. The class keyword introduces a class declaration and is immediately followed by the class name.

Line 2: declares the body of the class declaration

Line 3: it is the starting point of the java application

line 4: begins the body of the method declaration

line 5: instruct the computer to perform an action, i.e to print the string of characters contained between the double quotation marks.

line 6&7: indicates the end of the main method and class declaration’

Features of Java

 

Open Source

Java since its birth, till today, is an open-source product and it has all the public access. programmers are free to post entire source code for anyone to download, copy, redistribute them, which is usually part of the GPL  (General Public License,) the license that usually comes with open-source software.

High Performance

Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java enables high performance with the use of the just-in-time compiler.

Multi-Threading

Java multithreading feature makes it possible to write a program that can do many tasks simultaneously. The benefit of multithreading is that it utilizes the same memory and other resources to execute multiple threads at the same time, like While typing, grammatical errors are checked along.

Secure

When it comes to security, Java is always the first choice. With java secure features it enables us to develop virus-free, temper free system. Java program always runs in Java runtime environment with almost null interaction with system OS, hence it is more secure.

Platform independent

Unlike other programming languages such as C, C++ etc which are compiled into platform-specific machines. Java is guaranteed to be write-once, run-anywhere language. On compilation, Java program is compiled into bytecode. This bytecode is platform-independent and can be run on any machine, plus this bytecode format also provides security. Any machine with Java Runtime Environment can run Java Programs.

Portability

The cross-platform feature enables the Java code to be highly portable. Programmers can write code in windows and execute the same code in Linux Operating System.

Object-Oriented

In java, everything is an object which has some data and behaviour. Java can be easily extended as it is based on Object Model.

Robust

Java makes an effort to eliminate error-prone codes by emphasizing mainly on compile-time error checking and runtime checking. But the main areas which Java improved were Memory Management and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.

Let’s get started with the first topic in the Java Tutorial blog i.e Hello World Program.

 

Hello World Program

I will give you a simple overview of how a Java program looks like. In the below code, I have created a class – MyFirstJavaProgram and printed “Hello World”. Go ahead and try to execute the below example in your Eclipse IDE. Do not worry, we will discuss the Java class in a while.

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

//Output:

Hello World

Next, let us understand different member variables in Java. 

Java – Basic Syntax

Case Sensitivity − Java is case sensitive

Class Names − For all class names, the first letter should be in Upper Case.

Method Names − All method names should start with a Lower Case letter.

Program File Name − The name of the program file should exactly match the class name.

public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

Java Tutorial: Member Variables

A member variable plays a major role in a class as it is used to store a data value. When we define a class, we can declare a member variable. These variables are members of a class.
Member variables are further classified into three types:

  • Local variable
  • Instance variable
  • Class/Static variable

Let me discuss each one of them:

Local variable: These are the variables which are declared within the method of a class. Let’s understand this with a programmatic example:

public class Car {
      public void display(int m){  // Method
           int model=m;  // Created a local variable model
           System.out.println("Model of the car is" +model);
     }
}

In the above code, my local variable is ‘model’ which I have declared inside a method ‘display’ which has a parameter-‘m’. 

Instance variable: Instance variable is declared in a class but outside a method, constructor or any block. Let’s understand this with a programmatic example. 

public class Car {
      public String color;     // Created an instance variable color
      Car(String c){
            color=c;
      }
      public void display() {  // Method 
            System.out.println("color of the car is"+color);
      }
public static void main(String args[]){
           Car obj=new Car("black");
                  obj.display();
      }
}

In the above code, ‘colour’ is my instance variable which has a value “black” associated with it.

Class variable: Class variables are also called as static variables. These variables have only one copy that is shared by all the different objects in a class. Let’s understand this with a programmatic example. 

public class Car {
      public static int tyres;   // Created a class variable tyres
      public static void main(String args[]){
           tyres=4;
           System.out.println("Number of tyres are"+tyres);
      }
}

All cars must be having 4 tyres, right? So in my above code, I have declared a static variable as ‘tyre’ whose value remains same throughout the class.

Let’s move ahead in this Java Tutorial blog and look at our next topic i.e data types and operators in Java.

 

Java Tutorial: Datatypes 

A data type is used to represent different values which are stored in a variable. They are mainly classified into 4 different aspects – Integer, Float, Character and Boolean. You can refer to the below image to understand the different data types with respect to the memory allocated to them.

DataType - Java Tutorial - Edureka

As you can see in the above image, data types are of 4 major types.

  • The first data type is an Integer which stores a numerical value.
  • Now, if a numerical value contains the decimal part, it will be referred to as a float Datatype.
  • Next, if you wish to store a character, then the third data type i.e char is used. In char, you can store any alphabetical character as well as a special character.
  • The last data type is Boolean which stores only ‘true’ or ‘false’ value.

 

Let’s move forward and look at the various data operations which you can perform in Java.

 

Java Tutorial: Data Operators

There are mainly 4 different types of operators, which are listed below:

  • Arithmetic Operator: Perform arithmetic operations such as addition, subtraction, multiplication, division and modulus.
  • Unary Operator: Unary operators are used to increments or decrements a particular value. For example: ++ stands for increment, – – stands for decrements.
  • Relational Operator: It defines some kind of relation between two entities. For example: <, >, <=, >=, !=, ==.
  • Logical Operator: Logical operators are typically used with boolean (logical) values.

To know more about operators in Java, please go through this article link

Meanwhile, you may go through this Java Tutorial video where all the concepts related to Java has been clearly explained using an example:

Java Tutorial for Beginners | Java Programming Tutorial | Edureka

Next, let us move forward in Java Tutorial blog and understand the concept of control statements.

 

Java Tutorial: Control statements

Control statements are the statements that define the flow of your program. There are the following types of control statements in Java

Loops-in-Java-Conditional-statements-Types-Edureka

They suggest the computer that it should carry out the execution of a particular segment of code, given the condition stated is true and valid. The Conditional Statements are classified as shown below

If Condition

If Statement is a programming conditional statement that executes a code segment over a condition, provided if it is true and valid. Below is an example of an If statement.

//Find if the number is positive or negative.

Package ifloop;
public class ifloop {
public static void main(String[] args) {
        int number = -10;
        if (number &amp;amp;gt; 0) {
              System.out.println("Number is positive.");
        }
        System.out.println("The number is negative.");
    }
}

//Output:

The number is negative.

 

Else-If Condition

Else If Conditional Statement is used to execute one statement out of the two. The Conditional Statement executes the code segment provided is true and valid. Below is an example of an If statement.

//Find if the number is Even or Odd

package Esleifloop;
import java.util.Scanner;
public class elseifloop {
     public static void main(String[] args) {
          Scanner kb = new Scanner(System.in);
          System.out.println("Enter any integer value");
          int a=kb.nextInt();
          if(a%2==0){
                System.out.println("even number");
         } 
         else{
                System.out.println("odd number");
         }
     }
}

//Output:

Enter any integer value
21
odd number

 

Else-If Ladder

Else if Ladder is set of consecutive Else-If statements which are used to execute one true and valid statement out of a collection of given statements. Below is an example for Else-If Ladder.

C++-Tutorial-else-if-ladder-C-Edureka.jpg

//Selecting the Vehicle of your Choice.

package elseifladder;
import java.util.Scanner;
public class ladder {
public static void main(String[] args) {
      Scanner kb = new Scanner(System.in);
      System.out.println("Enter your chioce, 1 for the Sedan, 2 for SUV, 3 for Sports, 4 Cross Breed");
      int choice=kb.nextInt();
      if(choice==1){
            System.out.println("Sedan Class");
      }
      else if(choice==2){
            System.out.println("SUV Class");
      }
      else if(choice==3){
            System.out.println("Sports Class");
      }
      else if(choice==4){
            System.out.println("Cross-Breed Segment");
      }  
      else {
            System.out.println("Invalid Choice");
      }
   }
}

//Output:

Enter your choice, 1 for the Sedan, 2 for SUV, 3 for Sports, 4 Cross-Breed

3
Sports Class

 

Nested If Condition

Nested-If is a conditional statement where one Else-If statement is embedded into another If statement. The following program is an example for Nested If condition.

C#-Tutorial-nested-if-C-Edureka.jpg

//Find the greatest number out of the given three numbers

package nestedif;
public class nested {
      public static void main(String[] args) {
            int n1 = 20, n2 = 30, n3 = 10, greatest;
            if (n1 &amp;amp;gt;= n2) {
                 if (n1 &amp;amp;gt;= n3) {
                      greatest = n1;
                 }  
                 else {
                      greatest = n3;
                 }
            } 
            else {
                 if (n2 &amp;amp;gt;= n3) {
                     greatest = n2;
                 } 
                 else {
                     greatest = n3;
                 }
            }
            System.out.println("Largest number is " + greatest);
      }
}

//Output:

Largest number is 30

Build real-world apps from scratch and showcase your skills with our hands-on Flutter APP Development Course.

Ternary Operator

Ternary Operator is a conditional statement which has three arguments. First one is a conditional argument and the second is the result upon a true comparison, and the third is the result upon a false comparison.

//Find the greatest of the two numbers

package Ternary;
import java.util.Scanner;
public class Ternaryoperators {
     public static void main(String[] args) {
          Scanner kb = new Scanner(System.in);
          System.out.println("Enter any integer value to a");
          int a=kb.nextInt();
          System.out.println("Enter any integer value to b");
          int b=kb.nextInt();
          int greater = (a &amp;amp;lt; b) ? a : b;
          System.out.println(greater);
     }
}

//Output:

Enter any integer value to a
10
Enter any integer value to b
25
25

 

Now, we will understand the Iteration in Java. There are 3 Iteration Loops in Java

Loops-in-Java-Types-Edureka

For Loop

For loop is a Control Flow Statement which allows you to execute a specific code segment for a finite number iterations. A for loop has three arguments, namely, initialization variable, Counter variable, and increment/decrement variable.

Below is the flow chart Related to For Loop.

Following code is an example for For Loop.

//Print the elements in an array using normal For Loop

package forloop;
public class forloop {
      public static void main(String[] args) {
            String[] arrData = {"JOHN", "JERRY", "RALPH", "JIM", "TOM"};
            System.out.println("Using normal For Loop:");
            for(int i=0; i&amp;amp;lt; arrData.length; i++){
                    System.out.println(arrData[i]);
             }
      }
}

//Output:

Using normal For Loop:
JOHN
JERRY
RALPH
JIM
TOM

 

Enhanced For Loop

Enhanced/Advanced For loop is similar to a for loop, but, it minimizes the code length and excludes counter variable and initialization variable. The control flows directly into the array/collection and executes operations on the elements by accessing their index.

Below is the flow chart Related to enhanced For Loop.

Following code is an example for Enhanced For Loop.

//Print the elements in an array using enhanced/advanced For Loop

package advforloop;
public class advforloop {
       public static void main(String[] args) {
             String[] arrData = {"JOHN", "JERRY", "RALPH", "JIM", "TOM"};
             System.out.println("Using Enhanced For Loop:");
             for (String strTemp : arrData){
                    System.out.println(strTemp);
             }
        }
}

//Output:

Using Enhanced for loop:
JOHN
JERRY
RALPH
JIM
TOM

 

Nested For Loop

Nested for loop embeds another For loop within itself. The outer loop triggers the inner loop. The inner loop executes completely and then triggers the outer loop for updating the iteration. This process continues until the outer loop executes completely.

Below is the flow chart Related to Nested For Loop.

Loops-in-Java-Nested-for-loop-Edureka

Following code is an example for Nested For Loop.

//Print the elements in a two-dimensional array using normal For Loop

package nestedforloop;
public class nested {
      public static void main(String[] args){
            int[][] arr = { { 1, 2 }, { 3, 4 } };
                   for (int i = 0; i &amp;amp;lt; 2; i++)
                         System.out.println("Row" + i + " - ");
                         for (int j = 0; j &amp;amp;lt; 2; j++)
                               System.out.println(arr[i][j]);
                         }
                   System.out.println("");
                   }
           }
}

//Output:

Row 0 - 12
Row 1 - 34

 

While Loop

While loop is a Contol Flow Statement that executes itself repeatedly until a given boolean condition is satisfied. While loop can be considered as a repeating If statement.

Below is the flow chart for While Loop.

C++-tutorial-While-loop-Edureka

Following code is an example for While Loop.

//Find if the number is a Prime Number or not using a While Loop

package whileloop;
import java.util.Scanner;
public class whiledemo {
      public static void main(String[] args) {
           Scanner kb = new Scanner(System.in);
           System.out.println("Enter any number");
           int num=kb.nextInt();
           int i = 2;
           boolean flag = false;
           while(i &amp;amp;lt;= num/2)
          {
                if(num % i == 0)
                {
                      flag = true;
                      break;
                }
               ++i;
          }
          if (!flag)
               System.out.println(num + " is a prime number.");
          else
               System.out.println(num + " is not a prime number.");
          }
}

//Output:

Enter any number
5
5 is a prime number.

 

Do While Loop

Do While loop is considered to be a conditional statement completely similar to a normal While loop. The only difference is that the Do While loop has the boolean/conditional statement is placed at the end of the loop. This makes the Do While loop to execute at least for once.

Below is the flow chart for Do While Loop.

C++ Tutorial-do while loop

Following code is an example for Do While Loop.

//Insert elements in an array and add them using normal While Loop

package dowhileloop;
import java.util.Scanner;
public class dowhile {
    public static void main(String[] args) {
        Double a, Summation = 0.0;
        Scanner kb = new Scanner(System.in);
        do {
                   System.out.print("Enter a number to perform addition and zero to exit: ");
                   a = kb.nextDouble();
                   Summation += a;
       } 
       while (a != 0.0);
       System.out.println("Sum of the numbers = " + Summation);
    }
}

//Output:

Enter a number to perform addition and zero to exit: 10
Enter a number to perform addition and zero to exit: 20
Enter a number to perform addition and zero to exit: 30
Enter a number to perform addition and zero to exit: 40
Enter a number to perform addition and zero to exit: 0
Sum of the numbers = 100.0

 

Infinite Loop

Infinite Loop is not actually a practically designed loop. Instead, It is a situation where the condition of the loop fails and the execution persists until you stop it manually.

Loops-in-Java-Infinite-loop-Edureka

Following code is an example for Infinite Loop.

//Generate Infinite Loop

package infiniteloop; 
public class infinity { 
       public static void main(String[] args) { 
             int i=0; 
             while(true) { 
                     System.out.println("Edureka"); 
                     i++;
             } 
        } 
}

//Output:

Edureka
Edureka
Edureka
.............

Next, let us see what are classes and objects in Java.

 

Java Tutorial: Classes and Objects

A class in Java is a blueprint which includes all your data.  A class contain fields(variables) and methods to describe the behaviour of an object. Let’s have a look at the syntax of a class.

class Abc {
      member variables // class body
        methods
 }

But how can you access these member variables and methods? Here comes the concept of Object.

An object is a major element in a class which has a state and behaviour. It is an instance of a class which can access your data. Let’s see the syntax to create an object in Java:

Object - Java Tutorial - Edureka
Here, Student is your class name followed by the name of the object. Then there is a “new” keyword which is used to allocate memory. Finally, there is a call to the constructor. This call initializes the new object.
Now let’s see how can you call a method using an object in Java:

class Student()
      void display(); {                      // Method
     ------                                         // logic of method
}
public static void main(String args[]){
      Student obj=new Student();    // Created an object
      obj.display();                           // Method called
}   

Want to know more about them? I would suggest you to see this Java class video which will take you through in-depth details of Java classes and the different key-components in Java. Go ahead, enjoy the video and tell me what you think.

Java Classes | Java Classes and Objects | Java Training | Edureka

 

Next, let us move ahead in our Java Tutorial blog where we’ll be discussing another key concept i.e. Arrays.

 

Java Tutorial: Arrays

Arrays in Java is similar to that of C++ or any other programming language. An array is a data structure which holds the sequential elements of the same type.

Let’s say you want to store 50 numbers. Instead of declaring individual variables, such as number0, number1, … and so on. You can declare one array variable – “numbers” and use number[0], the number[1] to represent individual variables. This will ease your task and minimizes the redundancy.

Each array has two components: index and value. Refer to the below image for better understanding:

Arrays - Java Tutorial - Edureka

Here the indexing starts from zero and goes till (n-1) where n= size of the array. Let’s say you want to store 10 numbers, then the indexing starts from zero and goes till 9.

There are two types of arrays in Java:

  • Single-dimension Array
  • Multi-dimension Array

Single-dimension Array: In a single-dimension array, a list of variables of the same type can be accessed by a common name. You can initialize the array using the following syntax:

int a[] = new int[12];

You can refer to the below image where I have stored data with respect to the given index.

Singledimension - Java Tutorial

Multidimension Array: In a multi-dimension array, your data is stored in a matrix form. Here, you can initialize the array using the following syntax:

int table[][]= new int[4][5];

It is quite similar to the matrix that we use in mathematics. Refer to the below image where I have stored data with respect to different dimensions.

MultiDimensionArray - Java Tutorial - EdurekaThus, arrays help you in optimizing the code where you can insert the data at any location. 

Let’s see the below code to understand the concept of the array in Java.

import java.util.*;
public class ArrayExample {
      public static void main( String args[])
     {
     double invoice[][]= new double[10][2];  // Initializing array
          Scanner obj= new Scanner(System.in);    // creating a scanner object to take input from user
          for(i=0;i<10;i++){                       // nested for loops
              for(j=0;j<2;j++);
               {
               System.out.println("Enter the value");
               invoice[i][j]=obj.nextDouble();         // store values to array    
          for(i=0;i<10;i++){
              for(j=0;j<2;j++)
               {
                System.out.println(invoice[i][j]);
               }
         }
     }
}

In the above code, I have explained how you can take input for the array and print the same.
I hope you guys are clear with how an array looks like and how do you initialize one.
 Now, let’s summarize the above topics and see the entire structure of a Java program.

 

Java Tutorial: Structure of a Program

Till now, we have learned about member variables, data types, control statements, classes and objects. Let’s see how all of them are structured together in a class in Java.

public class Car{                    // Class creation
       String color;                        // Member variables   
       String model;
       public void SpeedCheck(int s)        // Method 
         {
         int speed=s;
           if(speed>100)                        // Control statement
           {
           System.out.println(" You are driving very fast");
           }
           else
           {
            System.out.println("You are driving at normal speed");
           }
public static void main ( String args[]) 
         {
         Car obj= new Car();                  // Object creation
         obj.speed(60);
         }

 

Finally, we come to our last topic in the Java Tutorial blog i.e Object Oriented programming concepts.

 

File Input/Output Handling

Java has a dedicated library to handle all its input and output functionalities. It is the java.io package/library that handles all the input/output streams in Java. Java has two types of streams, they are:

  • Input Stream
  • Output Stream

Input Stream

It is responsible for reading data from all the sources.

Output Stream

It is responsible for writing the data to the destination.

//Example:

package edureka;

import java.io.*;
public class fileStreamTest {
         public static void main(String args[]) {
                try {
                      byte bWrite[] = { 1, 2, 3, 4, 5 };
                      OutputStream os = new FileOutputStream("Edureka.txt");
                      for (int x = 0; x < bWrite.length; x++) {
                            os.write(bWrite[x]);
                      }
                      os.close();
                      InputStream is = new FileInputStream("Edureka.txt");
                      int size = is.available();
                      for (int i = 0; i < size; i++) {
                            System.out.print((char) is.read() + " ");
                      }
                      is.close();
                      } 
                catch (IOException e) {
                       System.out.print("Exception");
                 }
         }
}

Now, we shall move into Object-oriented programming concepts in Java.

 

Java Tutorial: OOPs Concept

We have already discussed classes and objects in Java. Let’s discuss the 4 main concepts of object-oriented programming – Inheritance, Encapsulation, Polymorphism and Abstraction.

Let’s begin with the first concept i.e. Inheritance.

Inheritance: Most of you must be familiar with inheritance. Inheritance is a process where one class acquires the properties of another. But whose properties are inherited? Here we have two classes, a child class which inherits the properties of a base class.
A Class which inherits the properties are known as Child class. It is also referred to as a derived class or a subclass. Next, the class whose properties are inherited are known as Parent class or a base class.

Let’s understand these classes by looking at this real-life example of animals.

Inheritance - Java Tutorial - Edureka

In the above image, Animal is the superclass whereas amphibians, reptiles, mammals and birds are your child classes which are inheriting the properties from ‘Animal’ class.

In Java, inheritance is used to avoid code redundancy. Also, inheritance has many types, don’t worry, we will be going into more depth in my next blog on object-oriented programming.

Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit. Refer to the below image where all your methods, variables are bound together in a single class.

Encapsulation - Java Tutorial - Edureka

In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class.

Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms. The most common use of polymorphism in OOPs occurs when a parent class is used to refer to a child class object. Polymorphism is also achieved through function overloading. Don’t worry! I will be explaining the whole concept in my next blog. For now, let’s take a real-life scenario where a teacher tells the student to draw different shape/figure having different functionalities.

Polymorphism - Java Tutorial - Edureka

Let’s say I want to draw a specific shape which already has multiple functions present as part of my program. So the functions that are dealing with shape, I’ll call them as a draw(). Now based on the values that I have passed to these functions, it will draw different shapes. Let’s say in case of a rectangle, I am passing two values – length and breadth. Similarly, for a circle, I am passing a radius. Based on the values you pass, the different function will be called that serve different purposes. So this can be achieved through function overloading. Stay tuned, the concept of function overloading will be covered in detail in my next blog.

Abstraction: It is basically the quality of dealing with ideas rather than events. Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. Let’s see this real-life example of a car where i’ll help you understand what exactly abstraction is.

Abstraction - Java Tutorial - Edureka

If you consider the case of this car, here the mechanic is repairing a certain function in a car. But the user or you can say driver doesn’t want to know about these things, he just wants his car back in a working condition. So here, you basically segregate the implementation and show the other person what he actually wants to see and that exactly refers to abstraction.

This is the end of the second blog in the Java Tutorial blog series. I hope you guys are clear about each and every aspect that I have discussed above. In my next blog, I will be explaining object-oriented programming concepts of Java in detail with examples.

To learn object-oriented programming in java in a better way, please go through this article link.

 

Exception Handling

An exception can be defined as an unexpected problem that arises during the execution of the program. The exception interrupts the sequential and normal flow of the program. Hence, it becomes mandatory to resolve these exceptions to avoid any problems.

An exception can be of any type, such as,

  • Invalid data that is given by the user
  • A file location that cannot be accessed
  • Loss of network or other hardware issues

Let us check array index out of bounds exception example.

package edureka;
public class Edureka {
    public static void main(String args[]) {
          try {
                 int a[] = new int[21];
                 System.out.println("Accessing element:" + a[22]);
          } 
          catch (ArrayIndexOutOfBoundsException e) {
                 System.out.println("Exception thrown :" + e);
          }
          System.out.println("Out of the block");
    }
}

//Output:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 22
Out of the block

 

Now that you have understood basics of Java, check out the Java Course training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java Tutorial” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
17 Comments
  • Md.Shajzad Hossain says:

    The biggest online tutorials library having a collection of the most acclaimed tutorials on various technical and non technical subjects.

    Execute and Share your C, C++, Java, Python, Perl, PHP, Node.js, Javascript, Javascript 3, Javascript 4; HTML-5 or any project in your social networks using simple links.

  • sakshi says:

    Thank you so much for sharing such a informative article !

    this blog are very easy to understanding for beginners !

  • sakshi singh says:

    Thank you for sharing such a informative article !
    this blog are very easy to understand for beginners like me.
    all concepts are explain very clearly.

  • Thank you Aayushi Johari for this “Java Tutorial For Beginners – Java Programming Made Easy!” wonderful article. Java is the best programming language for IT jobs. So I have started studying java through online courses. I found your article very useful. You have given an excellent introduction for java and it’s very useful for me and other beginners. You have explained step by step with programming examples. I will try the same and practice from given example. Looking forward for your next article … keep sharing with us…

    • EdurekaSupport says:

      Hey Ayush, thanks for giving our blog a read. We are really glad you loved our blog. Do subscribe to our blog and stay tuned for future updates. Cheers!

  • Aaron Samuel says:

    Superb explaining.. i used it for recalling all essential concepts.. Really appreciate and love the work..thank you Aayushi
    and thank you Edureka..

  • Krystal says:

    A very useful piece for freshers like me.

    • EdurekaSupport says:

      Hey Krystal, thank you for reading our blog. We are glad to know that you liked our tutorial. Do subscribe and stay connected with us. Cheers :)

  • Very useful tutorials and very easy to understand. Keep Rock. Thank you.

    • EdurekaSupport says:

      Thnk you Roshini for appreciating our work. We keep updating our channel regularly. Do check out our other blogs and let us know how you liked it. Cheers :)

  • João Luís says:

    I Aayushi Johari.
    Yes thanks a lot for the tutorials :-)

    • EdurekaSupport says:

      Hey Joao! Thank you for appreciating our work. Do check out our website t know more about the courses we offer: https://www.edureka.co/
      Cheers :)

  • João Luís says:

    Hi Aayushi Johari.
    Thanks for the tutorials they are very nice :-)

    • EdurekaSupport says:

      Hey Luis! Thank you for your kind words. Keep reading our blogs and keep learning. Cheers :)

  • rachid says:

    thank’s for this tutorial the best tuorial for java for beginers

    • EdurekaSupport says:

      Hey Rachid! We are delighted to know that you liked our blog. Do read more of our blogs, like & share to learn more about the latest technologies.

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Java Tutorial For Beginners – Java Programming Made Easy!

edureka.co