Java Programming: The Complete Reference You Need

Java is a powerful programming language used in the current IT industry. Java Programming concepts are the highly-searched keywords for having an instant reference for Java Programming fundamentals.

This article is designed in such a way that you get a quick overview of all the significant concepts of Java programming along with practical examples for a better learning experience.

Java Programming begins by understanding the basics of Java. The basics mainly deal with the following:

  1. Java Development Kit (JDK)
  2. Java Runtime Environment (JRE)
  3. Java Virtual Machine (JVM)

When you download and install Java into your local machine, regardless of which operating system you are using, you will get the JDK, JRE, and JVM along with your download file. We will explore these three in a bit more detail.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Java Development Kit

In general, Java Development Kit can be considered a software environment that comes with a set of libraries. It also has software tools required for software development. 

Java Runtime Environment

Java Runtime Environment is a software layer that lies on top of the Host Operating System. JRE is responsible for the application software to run.

Java Virtual Machine

Java Virtual Machine is responsible for providing the Java run-time environment. JVM converts the code written in Java into machine level language (Byte Code). It then compiles and runs it.

With the basics discussed, let us move ahead with the fundamentals.

Fundamentals

In this section, we will discuss the various crucial concepts we need, to get started with Java programming.

Datatypes

The first amongst the fundamentals in Java Programming is Datatypes. A Datatype is a preprogrammed attribute that tells the compiler about the type of data it is about to process. Java uses standard datatypes similar to C-Programming Languages, which are mentioned as follows:

/Java-Programming-Datatypes

Now that we explored the datatypes, let us get to know the variables and keywords in Java.

Variables

The term variable is self-explanatory. The value it stores is prone to change at any point in time. When a variable is declared, a memory gets registered in the memory.

Example:

int var = 10;

Followed by Variables, we shall continue with Keywords in Java.

Keywords

In any programming language, keywords are special and reserved words that possess a special meaning and are prohibited from being used as a standard variable. Following are some of the keywords used in Java.

Java-Programming-keywords

Followed by Keywords, we shall continue with Operators in Java.

Operators

The Operators in Java are instructions passed by the user to the processor. These Operators guide the processor about the arithmetic and logical operations to be performed on the variables storing data.

Java-Programming-Operators-in-java

Let us look into a simple program to understand the operators in Java in a better way.

Example:

package simplilearnJava;

import java.util.Scanner;

public class Operators {

public static void main(String args[]) {

try (Scanner sc = new Scanner(System.in)) {

while (true) {

System.out.println("");

System.out.println("Enter the numbers to perform arthematic operations ");

System.out.print("Enter the first number : ");

int x = sc.nextInt();

System.out.print("Enter the second number : ");

int y = sc.nextInt();

System.out.println("Choose any operation that you want to perform ");

System.out.println("Choose option 1 for ADDITION");

System.out.println("Choose option 2 for SUBTRACTION");

System.out.println("Choose option 3 for MULTIPLICATION");

System.out.println("Choose option 4 for DIVISION");

System.out.println("Choose option 5 for MODULUS");

System.out.println("Choose option 6 for EXIT");

int n = sc.nextInt();

switch (n) {

case 1:

int add;

add = x + y;

System.out.println("Result : " + add);

break;

case 2:

int sub;

sub = x - y;

System.out.println("Result : " + sub);

break;

case 3:

int mul;

mul = x * y;

System.out.println("Result : " + mul);

break;

case 4:

float div;

div = (float) x / y;

System.out.print("Result : " + div);

break;

case 5:

int mod;

mod = x % y;

System.out.println("Result : " + mod);

break;

case 6:

System.exit(0);

}

}

}

}

}

Conditional Statements

Conditional Statements in Java Programming are the logical statements that evaluate the given mathematical or logical expression based on a condition provided by the user. In Java Programming Language, we have four different types of Conditional Statements. They are as follows:

  1. if statements 
  2. if-else statements
  3. if-else Ladder statements
  4. switch statements

if statement

The "if loop" has one condition to check for the mathematical or logical statement's validity. If the state is true, then the statement will b executed, else it will not. The following flow chart should help in understanding the work-flow of the conditional statement. 

Java-Programming-if-condition

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

public class IfStatement {

public static void main(String[] args) {

int num = -100;

if (num > 0) {

System.out.println("Number is positive.");

}

System.out.println("IF CONDITION TERMINATED. Control is outside the condition block");

}

}

if-else statement

The if-else statement is entirely similar to the if-condition statement. The only addition is that it has an additional else statement. The condition gets evaluated into the else segment when the if-condition statement is failed. The following flow chart should help in understanding the work-flow of the conditional statement. 

Let us check an example for a better learning experience.

Example: 

package simplilearnJava;

import java.util.Scanner;

public class Loop {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the first number : ");

int num = sc.nextInt();

if (num >= 0) {

System.out.println("Number is positive.");

} else {

System.out.println("The number is negative.");

}

}

}

if-else-ladder statement

The if-else-ladder statement is an advanced version of the if-else statement. There will be multiple else blocks instead of one. The following flow chart should help in understanding the work-flow of the conditional statement. 

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

import java.util.Scanner;

public class Loop {

public static void main(String[] args) {

try (Scanner sc = new Scanner(System.in)) {

System.out.println("Enter your chioce, 1 for the Noodles, 2 for Milkshake, 3 for fruits, 4 Coffee");

int choice = sc.nextInt();

if (choice == 1) {

System.out.println("Noodles");

} else if (choice == 2) {

System.out.println("Milkshake");

} else if (choice == 3) {

System.out.println("fruits");

} else if (choice == 4) {

System.out.println("Coffee");

} else {

System.out.println("Invalid input");

}

}

}

}

switch statement

The switch statement in Java is similar to the else-if ladder. The only difference is that it has various options, and a specific option is selected based on the condition specified against the switch statement. 

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

import java.util.Scanner;

public class switchcase {

public static void main(String[] args) {

try (Scanner sc = new Scanner(System.in)) {

System.out.println("Enter an input");

int week = sc.nextInt();

String name;

switch (week) {

case 1:

name = "Monday";

break;

case 2:

name = "Tuesday";

break;

case 3:

name = "Wednesday";

break;

case 4:

name = "Thursday";

break;

case 5:

name = "Friday";

break;

case 6:

name = "Saturday";

break;

case 7:

name = "Sunday";

break;

default:

name = "Invalid Input";

break;

}

System.out.println(name);

}

}

}

Moving ahead, we will continue with the Conditional Loops.

Loops

Conditional Loops in Java Programming are similar to Conditional Statements. The only difference is the conditional loops execute one single code segment for a specific number of times until the given condition is completely satisfied. Java Programming has three different types of conditional loops, as mentioned below.

  1. for loop
  2. while loop
  3. do-while loop

for loop

The "for loop" consists of three segments. 

Initialization

The initialization is where the loop counter variable is initialized to 0, 1, or any number per the user's requirement.

Condition

The condition part is where the counter variable is set against the condition of the user. The loop is evaluated until the condition is true, else it fails and exits the loop.

Loop Counter

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

The last part is the counter condition. It is an increment or decrement operator that executes every time the loop finishes one of its execution cycles.

The following flow chart should help in understanding the work-flow of the conditional loop. 

Java-Programming-For-Loop

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

public class loopfor {

public static void main(String[] args) {

for (int i = 1; i <= 10; ++i) {

System.out.println("Looped " + i + " times");

}

}

}

while loop

While loop is different from for loop. it does not have an initialization variable or the increment/decrement variable. It only has the condition. 

The following flow chart should help in understanding the work-flow of the conditional loop. 

Java-Programming-While-Loop

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

import java.util.Scanner;

public class whileloop {

public static void main(String[] args) {

try (Scanner sc = new Scanner(System.in)) {

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

int num = sc.nextInt();

int i = 2;

boolean flag = false;

while (i <= 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.");

}

}

}

do-while loop

The do-while loop is entirely similar to the while loop. The only difference is that the condition is checked after the loop is executed.

The following flow chart should help in understanding the work-flow of the conditional loop. 

Java-Programming-Do-While

Let us check an example for a better learning experience.

Example:

package simplilearnJava;

public class DoWhileloop {

public static void main(String[] args) {

int i = 1;

do {

System.out.println(i);

i++;

} while (i <= 20);

}

}

With this, we have finished the fundamentals of Java Programming. Let us now move ahead into the object-oriented Java programming concepts.

Object-Oriented Programming in Java

Object-oriented programming is everything about the objects and classes, which are also known as the building blocks. The main motto of OOPs is to bind the data members and data manipulating methods together.

We will learn more about OOPs, starting with the objects and classes.

Objects and Classes

Java-Programming-classes-and-objects-in-java

A class is like a blueprint using which the objects are instantiated. On the other hand, the objects are the ones that are built by inheriting the properties of the class. Now, object-oriented programming has four pillars, as described below

Abstraction

Abstraction in Java is an object-oriented programming phenomenon of hiding the user's intricate code implementation details and only providing the user with the necessary information in parallel. 

Abstraction in Java is achieved by using two ways as mentioned below:

  1. Abstract Class in Java
  2. Interface in Java

Let us go through an example of an abstract class for better understanding.

Example:

package simplilearnJava;

public abstract class Person {

private String Name;

private String Gender;

public Person(String nm, String Gen) {

this.Name = nm;

this.Gender = Gen;

}

public abstract void work();

@Override

public String toString() {

return "Name=" + this.Name + "::Gender=" + this.Gender;

}

public void changeName(String newName) {

this.Name = newName;

}

public void Exam() {

// TODO Auto-generated method stub

}

}

Class

package simplilearnJava;

public class Employee extends Person {

private int EmpId;

public Employee(String EmployeeName, String Gen, int EmployeeID) {

super(EmployeeName, Gen);

this.EmpId = EmployeeID;

}

@Override

public void Office() {

if (EmpId == 0) {

System.out.println("Employee Logged Out");

} else {

System.out.println("Employee Logged In");

}

}

public static void main(String args[]) {

Person employee = new Employee("Pavithra", "Female", 1094826);

employee.Office();

employee.changeName("Pavithra Tripathy");

System.out.println(employee.toString());

}

}

Let us go through an example of an Interface for better understanding.

Example:

package simplilearnJava;

public interface Area {

public void Square();

public void Circle();

public void Rectangle();

public void Triangle();

}

//Class

package simplilearnJava;

import java.util.Scanner;

public class shapeArea implements Area {

public void Circle() {

Scanner kb = new Scanner(System.in);

System.out.println("Enter the radius of the circle");

double r = kb.nextInt();

double areaOfCircle = 3.142 * r * r;

System.out.println("Area of the circle is" + areaOfCircle);

}

@Override

public void Square() {

// TODO Auto-generated method stub

Scanner kb2 = new Scanner(System.in);

System.out.println("provide the length of the side of the square");

double s = kb2.nextInt();

double areaOfSquare = s * s;

System.out.println("Area of the square is" + areaOfSquare);

}

@Override

public void Rectangle() {

// TODO Auto-generated method stub

Scanner kb3 = new Scanner(System.in);

System.out.println("Enter the length of the Rectangle");

double l = kb3.nextInt();

System.out.println("Enter the breadth of the Rectangle");

double b = kb3.nextInt();

double areaOfRectangle = l * b;

System.out.println("Area of the Rectangle is" + areaOfRectangle);

}

@Override

public void Triangle() {

// TODO Auto-generated method stub

Scanner kb4 = new Scanner(System.in);

System.out.println("Enter the base of the Triangle");

double base = kb4.nextInt();

System.out.println("Enter the height of the Triangle");

double h = kb4.nextInt();

double areaOfTriangle = 0.5 * base * h;

System.out.println("Area of the Triangle is" + areaOfTriangle);

}

public static void main(String[] args) {

shapeArea geometry = new shapeArea();

geometry.Circle();

geometry.Square();

geometry.Rectangle();

geometry.Triangle();

}

}

Encapsulation

In Java, we have four different types of Inheritance, as shown below.

encapsulation

Encapsulation in Java programming is an object-oriented feature of binding the data manipulating methods and the data members together as one unit.  

Let us go through an example for better understanding.

Example:

package simplilearnJava;

public class Encapsulation {

private String Name;

private String ID;

private int age;

public int getAge() {

return age;

}

public String getName() {

return Name;

}

public String getID() {

return ID;

}

public void setAge(int newAge) {

age = newAge;

}

public void setName(String newName) {

Name = newName;

}

public void setIdNum(String newID) {

ID = newID;

}

}

package simplilearnJava;

public class Run {

public static void main(String args[]) {

Encapsulation encapsulate = new Encapsulation();

encapsulate.setName("Harry");

encapsulate.setAge(25);

encapsulate.setIdNum("829468");

System.out.print(

"Name : " + encapsulate.getName() + " Age : " + encapsulate.getAge() + " ID : " + encapsulate.getID());

}

}

Inheritance

Inheritance in Java is as simple as the term inheritance means. Here, the child class will inherit the properties of the parent class.

Java-Programming-Inheritance

Single Inheritance

Single Inheritance involves only one parent class and one child class; the child class inherits all its parent class properties. For a better understanding, let us go through an example.

Example:

//Single

package simplilearnJava;

class Student {

void Play() {

System.out.println("Playing Fooball...");

}

}

class Bob extends Student {

void Study() {

System.out.println("Studing Physic...");

}

}

public class Single {

public static void main(String args[]) {

Bob d = new Bob();

d.Study();

d.Play();

}

}

Multilevel Inheritance

Multilevel Inheritance is similar to Single Inheritance. The only difference is, there are chances for the child class to inherit the properties of parent classes from multiple levels. For a better understanding, let us go through an example.

Example:

//Multilevel Inheritance

package simplilearnJava;

class Bike {

public Bike() {

System.out.println("Segment: 1000cc");

}

public void BikeType() {

System.out.println("Bike Type: Sports");

}

}

class NinJa extends Bike {

public NinJa()

{

System.out.println("Make NinJa");

}

public void brand() {

System.out.println("Manufacturer: Kawasaki");

}

public void speed() {

System.out.println("Max Speed: 290Kmph");

}

}

public class NinJa1000R extends NinJa {

public NinJa1000R() {

System.out.println("NinJa Model: 1000R");

}

public void speed() {

System.out.println("Max Speed: 280Kmph");

}

public static void main(String args[]) {

NinJa1000R obj = new NinJa1000R();

obj.BikeType();

obj.brand();

obj.speed();

}

}

Hierarchical Inheritance

Hierarchical Inheritance, the term explains it all. Here, we will have one parent class, and two or more child classes will inherit the parent class's properties. For a better understanding, let us go through an example.

Example:

//Hierarchical Inheritance

package simplilearnJava;

class Employee {

double leaves = 25.00;

}

class PEmployee extends Employee {

float totalHoursPerDay = (float) 8.00;

}

class TEmployee extends Employee {

float totalHoursPerDay = (float) 10.50;

}

public class EmployeeSalary {

public static void main(String args[]) {

PEmployee permenant = new PEmployee();

TEmployee temporary = new TEmployee();

System.out.println("Total Number of leaves for Permanent Employee are :" + permenant.leaves);

System.out.println("Total number of working hours for Permanent Employee are:" + permenant.totalHoursPerDay);

System.out.println("Total number of temporary Employee Total Number of leaves are :" + temporary.leaves);

System.out.println("Total number of working hours for Temporary Employee are :" + temporary.totalHoursPerDay);

}

}

Hybrid Inheritance

Hybrid Inheritance is an advanced type of Inheritance. The Hybrid type of Inheritance is a mixture of Single, Multilevel, and Hierarchical Inheritance. For a better understanding, let us go through an example.

Example:

//Hybrid Inheritance

package simplilearnJava;

class C {

public void Print() {

System.out.println("C is the Parent to A,B,D");

}

}

class A extends C {

public void Print() {

System.out.println("A has Single Inheritance with C and shares Hierarchy with B");

}

}

class B extends C {

public void Print() {

System.out.println("B has Single Inheritance with C and shares Hierarchy with A");

}

}

public class D extends A {

public void Print() {

System.out.println("D has Single Inheritance with A and Multi-Level inheritance with C");

}

public static void main(String args[]) {

A w = new A();

B x = new B();

C y = new C();

D z = new D();

y.Print();

w.Print();

x.Print();

z.Print();

}

}

Also, in Java Programming, we have an IS-A relation and HAS-A relation.

Java-Programming-IS-A-in-java

IS-A Relation

The IS-A Relation is based on the type of Inheritance implemented, and next, the decision is based on whether it is an interface inheritance or class inheritance. Let us look into an example for a better understanding.

Example:

//IS-A Relation

package simplilearnJava;

import java.util.*;

class Customer {

public String Name;

public String City;

Customer(String Name, String City) {

this.Name = Name;

this.City = City;

}

}

class Bank {

private final List<Customer> customers;

Bank(List<Customer> customers) {

this.customers = customers;

}

public List<Customer> TotalAccountsInBank() {

return customers;

}

}

public class IsARelation {

public static void main(String[] args) {

Customer C1 = new Customer("Raju", "Bangalore");

Customer C2 = new Customer("Shiva", "Hyderabad");

Customer C3 = new Customer("Sachin", "Mumbai");

Customer C4 = new Customer("Prashanth", "Vizag");

Customer C5 = new Customer("John", "Goa");

List<Customer> Customers = new ArrayList<Customer>();

Customers.add(C1);

Customers.add(C2);

Customers.add(C3);

Customers.add(C4);

Customers.add(C5);

Bank ABCBank = new Bank(Customers);

List<Customer> cust = ABCBank.TotalAccountsInBank();

for (Customer cst : cust) {

System.out.println("Name of the Customer : " + cst.Name + "" + "City : " + cst.City);

}

}

}

HAS-A Relation

The HAS-A type of relationship is based on the reference of the current class to another class. It is treated as a composition. Let us look at an example for a better understanding.

Example:

//HAS-A Relation

package simplilearnJava;

class School {

private String name;

School(String name) {

this.name = name;

}

public String SchoolName() {

return this.name;

}

}

class Student {

private String name;

Student(String name) {

this.name = name;

}

public String StudentName() {

return this.name;

}

}

public class HasARelation {

public static void main(String[] args) {

School schl = new School("St.John's School");

Student candidate = new Student("Tobey Marshall");

System.out.println(candidate.StudentName() + " is an Ex-Student of " + schl.SchoolName());

}

}

Followed by Inheritance in Java, we will move ahead with Polymorphism in Java.

Polymorphism

Polymorphism in Java is an object-oriented Java programming concept that deals with executing mathematical and logical operations in different perspectives based on the method call and method parameters.

Java-Programming-types-of-polymorphism

Let us look into an example of Polymorphism.

Example:

package simplilearnJava;

class AnimalSounds {

public void Sound() {

System.out.println("The animals make different sounds when asked to speak. For example:");

}

}

class Cow extends AnimalSounds {

public void Sound() {

System.out.println("The cow says: moh moh");

}

}

class cat extends AnimalSounds {

public void Sound() {

System.out.println("The cat says: mew mew");

}

}

class Dog extends AnimalSounds {

public void Sound() {

System.out.println("The dog says: bow wow");

}

}

public class AnimalMain {

public static void main(String[] args) {

AnimalSounds Animal = new AnimalSounds();

AnimalSounds cow = new Cow();

AnimalSounds cat = new cat();

AnimalSounds Dog = new Dog();

Animal.Sound();

cow.Sound();

cow.Sound();

Dog.Sound();

}

}

There are two fundamental types of Polymorphism in Java, as mentioned below.

Run-Time Polymorphism

In Run-Time Polymorphism, the data manipulating method call will be resolved during the execution stage. Let us go through an example so that we can understand the concept in a better way.

Example:

package simplilearnJava;

class CargoPilot {

public void FlyPlane() {

System.out.println("This is the Cargo Pilot, Ready to Take off");

}

}

class CivilianPilot extends CargoPilot {

public void FlyPlane() {

System.out.println("This is the Civilian Pilot, Ready to Take off");

}

}

public class Takeoff {

public static void main(String args[]) {

CargoPilot CPObj = new CargoPilot();

CPObj.FlyPlane();

//CivilianPilot CivilianObj = new CivilianPilot();

//CivilianObj.FlyPlane();

}

}

Compile-Time Polymorphism

In Compile-Time Polymorphism, the method call will be resolved during the compilation stage. Let us go through an example of understanding the concept in a better way.

Example:

package simplilearnJava;

public class Addition {

public int add(int x, int y) {

return (x + y);

}

public double add(double d, double e, double f, double g) {

return (d + e + f + g);

}

public double add(double a, double b) {

return (a + b);

}

public static void main(String args[]) {

Addition a = new Addition();

System.out.println(a.add(25, 30));

System.out.println(a.add(10.0, 15.0, 20.0, 25.0));

System.out.println(a.add(127.5, 123.5));

}

}

Access Modifiers

Access Modifiers in Java are some unique keywords that define the compiler about the accessibility of an individual data member, data manipulating method, or a class. There are four different access modifiers in Java.

default

The JVM default access modifier is used when the user does not manually provide any specific access modifier. The default access modifier allows the Java compiler to access the data members and data methods from anywhere in the program.

public

The public access modifier allows the Java compiler to access the data members and data methods from anywhere in the entire program. To understand better, let us execute a program.

Example:

//Public

package inheritance;

public class Summation {

public int add(int x, int y) {

return x + y;

}

}

package inheritance2;

import inheritance.*;

public class Child {

public static void main(String args[]) {

Summation A = new Summation();

System.out.println(A.add(100, 200));

}

}

private

The private access modifier is used when the user wants a specific data member or data method to be accessible within a particular class and not outside the class. Let us go through an example.

Example:

package inheritance;

class Print {

private int x = 5;

void Display() {

System.out.println("Hello World");

}

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

}

}

public class call {

public static void main(String args[]) {

Print A = new Print();

System.out.println(A.getX());

A.Display();

}

}

protected

The protected type of access modifier is the same as the private modifier. The only difference is that the accessibility of the data member and data method will be confined to the entire package, unlike to only a specific class as the private modifier. Let us check an example.

Example:

//Protected

package inheritance;

public class Parent

protected void Print() 

System.out.println("Hello World"); 

package inheritance2;

import inheritance.*;

public class Child extends Parent {

public static void main(String args[]) {

Child x = new Child();

x.Print();

}

}

package Simplilearn;  

class Parent{  

void msg(){System.out.println("Hello World");}  

package Simpli;  

import Simplilearn.*;  

class Child{  

public static void main(String args[]){  

Parent P = new Parent();//Compile Time Error  

P.msg();//Compile Time Error  

}  

}

Java Collections

Collections in Java programming are known as data structures capable of storing and manipulating different data types in real-time.

There are various types of Java Collections, as mentioned below.

Java-Programming-Collections-in-java-1

Java-Programming-Collections-in-java-2

Exception Handling

In Java Programming, exception handling is a predefined mechanism employed to eliminate the exceptions and errors that disrupt a Java program's regular operation. Let us check an example for a better understanding.

Example:

package simplilearnJava;

import java.io.File;

import java.io.FileReader;

public class exception {

private static String s;

public static void main(String args[]) {

File file = new File("C://Data.txt");

FileReader fr = new FileReader(file);

}

}

//Exception - ArrayIndxOutOfBound

package simplilearnJava;

import java.util.Arrays;

import java.util.Scanner;

public class IndexOutOfBound {

public static void main(String args[]) {

int[] Arr = {(int) 20.0,(int) 30.0,(int) 40.0,(int) 50.0,(int) 50.0};

System.out.println("The array elements are: ");

System.out.println(Arrays.toString(Arr));

Scanner scan = new Scanner(System.in);

System.out.println("Please enter the address of the required element:");

float num = scan.nextFloat();

System.out.println("Total number at your selected address is "+Arr[(int) num]);

}

}

//Exception - NullPointer

package simplilearnJava;

import java.util.Arrays;

import java.util.Scanner;

public class NullPointer {

private static String stringg ;

public static void main(String[] args) {

stringg = "simplilearn";

foo(null);

bar(null);

}

static void foo(String abc) {

try {

System.out.println("The initial character in the string is:" + abc.charAt(0));

} catch (NullPointerException e) {

System.out.println("Exception - NullPointerException!");

}

}

static void bar(String abc) {

if (abc == null)

System.out.println("The initial character in the string is: " + abc.charAt(0));

else

System.out.println("NullPointerException!");

}

}

There are two different varieties of exceptions in Java, as shown below.

Checked Exceptions

An exception that could either be caught or declared inside a method in which it is thrown is referred to as a Checked Exception. Let us go through an example.

Example:

package simplilearnJava;

import java.io.*;

public class Checked {

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

FileReader file = new FileReader("C:\\Users\\ravi.kiran\\Documents\\data.txt");

BufferedReader Input = new BufferedReader(file);

for (int c = 0; c < 5; c++)

System.out.println(Input.readLine());

Input.close();

}

}

Unchecked Exceptions

Unchecked Exceptions are the exceptions that remain unexpected and cannot be handled during the compilation stage. Let us go through an example for better understanding.

Example:

package simplilearnJava;

public class Unchecked {

public static void main(String args[]) {

int array[] = { 1, 2, 8, 3, 4, 5, 6, 7, 9, 10 };

System.out.println(array[11]);

}

}

Moving ahead, we have the file manipulating operations. 

File Operations

File Handling can be defined as a procedure to manipulate data via a file system. It includes CREATE, GET, READ, and WRITE operations. We will go through an example for each type of file manipulating operation in Java.

//Create

package simplilearnJava;

import java.io.File;

import java.io.IOException;

public class Create {

public static void main(String[] args) {

try {

File Obj = new File("Simplilearn.txt");

if (Obj.createNewFile()) {

System.out.println("File created: " + Obj.getName());

} else {

System.out.println("File already exists.");

}

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

}

}

//Write

package simplilearnJava;

import java.io.FileWriter;

import java.io.IOException;

public class Write {

public static void main(String[] args) {

try {

FileWriter myWriter = new FileWriter("Simplilearn.txt");

myWriter.write("Files in Java might be tricky, but it is fun enough!");

myWriter.close();

System.out.println("Hello! Welcome to Simplilearn.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

}

}

//Read

package simplilearnJava;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Read {

public static void main(String[] args) {

try {

File myObj = new File("SimplilearnDoc.txt");

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

System.out.println(data);

}

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

}

}

Learn top skills demanded in the industry, including Angular, Spring Boot, Hibernate, Servlets, and JSPs, as well as MVC, web services, and SOA to build highly web scalable apps with the Full Stack Java Developer Masters Program.

Next Steps

Java Enterprise Edition can be your next stop as they are essential to go through before you start coding. It helps you master how to resolve errors and exceptions in real-time Java.

The link to your next step is here. Java EE

If you wish to have in-depth knowledge about the Java programming language and details on getting certified as an Expert Java developer, feel free to explore Simplilearn's Full Stack Java Developer, carried out by industry experts offer in real-time. Specifically, check the Full Stack Java Developer Master's Program from Simplilearn today!

If you have any queries about this "Java Programming" article, please leave them in the comments section, and our team of experts will answer them for you at the earliest!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.