Java Basics for Beginners to Learn Java Programming

In this Java article, we will learn the basics of Java, including all the basic Java topics with examples. These are the topics that you need to know to start learning and doing practicals in Java. This article will help you understand the Java basics. Knowing the basic concepts of any programming language can only help you master it. So, let us start the tutorial.

basics in java

In this Java Basics tutorial, we will discuss the following things:

  • Introduction to Java
  • Editions of Java
  • Features of Java
  • Applications of Java
  • Java Environment- JVM, JRE, and JDK
  • Keywords in Java
  • Java Variables
  • Java Data types
  • Operators in Java
  • Java Methods
  • Comments in Java
  • Java Class
  • Java Object
  • Object Creation in Java
  • Arrays in Java
  • Java constructors
  • Access Modifiers in Java
  • Jump Statements in Java
  • Conditional Statements in Java
  • Loops in Java
  • Packages in Java
  • String in Java
  • Interface in Java
  • Abstract class in Java
  • Object-Oriented concepts of Java
  • Abstraction
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Exception in Java
  • Exception Handling in Java

So, let us begin with the Java basics for Beginners.

Introduction to Java

Java programming language is a high-level, object-oriented, general-purpose, and secure programming language. It was developed by James Gosling at Sun Microsystems in 1991. At that time, they called it OAK. Sun Microsystem changed the name to Java in 1995. In 2009, Oracle Corporation took over Sun Microsystem.

Java is the most widely used programming language. It is designed for the distributed environment of the Internet. Java is freely accessible to users, and we can run it on all the platforms. Java follows the WORA (Write Once, Run Anywhere) principle, and is platform-independent.

Editions of Java

There are three editions of Java. Each Java edition has different capabilities. The editions of Java are:

1. Java Standard Editions (SE): We use this edition to create programs for a desktop computer.
2. Java Enterprise Edition (EE): We use this edition to create large programs that run on the server and to manage heavy traffic and complex transactions.
3. Java Micro Edition (ME): We use this edition to develop applications for small devices such as set-top boxes, phones, and appliances, etc.

Features of Java

1. Simple: Java is simple because its syntax is simple and easy to understand. Java eliminates many complex and ambiguous concepts of C++. For example, the use of explicit pointers and operator overloading are not in Java.

2. Object-Oriented: Everything in Java is in the form of the object. In other words, it has some data and behavior. A Java program must have at least one class and object.

3. Robust: Java always tries to check errors at runtime and compile time. Java uses a garbage collector to provide a strong memory management system. Features like Exception handling and garbage collection make Java robust or strong.

4. Secure: Java is a secure language, as Java does not use explicit pointers. All Java programs run in the virtual machine. Moreover, Java contains a security manager that defines the access levels of Java classes.

5. Platform-Independent: Java provides a guarantee that to write code once and run it anywhere(at any platform). The compiled byte code is platform-independent, and we can run it on any machine irrespective of the Operating system.

Java Platform Independence

6. Portable: We can carry the bytecode of Java to any platform. There are no implementation-dependent features in Java. Java provides predefined information for everything related to storage, such as the size of primitive data types.

7. High Performance: Java provides high performance with the use of the Just-In-Time (JIT) compiler.

8. Distributed: Java is a distributed language as it provides networking facilities. Java works very well in the distributed environment of the Internet. This is because Java supports TCP/IP protocol. EJB(Enterprise Java Beans) and RMI(Remote Method Invocation) of Java are used to create a distributed system.

9. Multi-threaded: Java is a multi-threaded language as it can handle more than one job at a time.

Applications of Java Programming

Java is a widespread language. The following are some application areas in which we find Java usable:

  1. Desktop applications
  2. Web applications
  3. Mobile applications (Android)
  4. Cloud computing
  5. Enterprise applications
  6. Scientific applications
  7. Operating Systems
  8. Embedded systems
  9. Cryptography
  10. Smart cards
  11. Computer games
  12. Web servers and application servers

Java Environment- JVM, JRE, and JDK

Java Environment

1. JVM (Java Virtual Machine)

Java Virtual Machine provides a runtime environment in which we can execute the bytecode. JVM is platform-dependent. It performs the following tasks:

  • Loading the code
  • Verifying the code
  • Executing the code
  • Providing a runtime environment

2. JRE (Java Runtime Environment)

JRE is a collection of tools. These tools together allow the development of applications and provide a runtime environment. JVM is a part of JRE. JRE is also platform-dependent like JVM.

3. JDK (Java Development Kit)

Java Development Kit provides an environment that helps to develop and execute the Java program. There are Development Tools in JDK to provide an environment to develop Java programs. JDK, along with the JRE, contains other resources like the interpreter, loader. compiler, an archiver (jar), and a documentation generator (Javadoc). These components together help you to build Java programs.

Java Keywords

Keywords are the special words that are basically reserved keywords in any programming language. We cannot use them in the rest of the programs. We can only use them as the name of variables in Java, class, or method. Java has around 50 keywords which are basics to java:

abstractfornewenumsuper
assertgotopackageextendsswitch
booleanifprivatefinalsynchronized
breakimplementsprotectedfinallythis
byteimportpublicfloatthrow
caseinstance ofcontinuewhilethrows
catchintdefaultreturntransient
charinterfacedoshorttry
classlongdoublestaticvoid
constnativeelsestrictfpvolatile

Java Variables

Computer programs read data from input devices like keyboard, mouse etc. They process this input data and write it to an output device or network. Java stores the program data in variables. Java program first declares the variables, reads data into these variables, executes operations on the variables, and then writes them somewhere again.

There are the following types of variables in Java basics:

  1. Local Variables
  2. Class Variables (Static Variables)
  3. Instance Variables (Non-static Variables)

Java Data Types

There is a basic java data type for each variable in Java. The data type of a variable determines the type of data the variable can contain, and what operations we can execute on it. Every bit of processed data every day is divided into types. The type of data is called a data type. There are various kinds of data types in Java.

Broadly, the data types are mainly of two categories:

a. Primitive Data Types in Java

Primitive data types are fundamental data types offered by Java. These are the basic data values. These data types are hard coded into the Java compiler so that it can recognize them during the execution of the program.

There are 8 types of primitive data types in Java:
a. int
b. float
c. char
d. boolean
e. byte
f. short
g. long
h. double

b. Non-Primitive Data Types in Java

Non-Primitive data types are the reference data types. These are the special data types that are user-defined. The program already contains their definition. Some examples of non-primitive or reference data types are classes, interfaces, String, arrays, etc.

Java Operators

Java Operators are the special type of tokens. When they are coupled with entities such as variables or constants, they result in a specific operation. The operation can be any, such as addition, multiplication or even shifting of bits, etc.

There are following types of Java operators;:

  • Arithmetic Operators
  • Logical Operators
  • Unary Operators
  • Assignment Operators
  • Ternary Operators
  • Relational Operators
  • Bitwise Operators
  • Shift Operators
  • instanceOf operator

Java Method

A method or function basically defines a behavior. There can be a number of methods in Java. In methods, there are logics written. We can manipulate data in methods and also execute actions on them.

They have a syntax similar to classes:

< returnType > <methodName > {
  action1;
  action2;
}

For Example:

void print() {
  System.out.println(“Hey I am learning Java at TechVidvan”);
}

Comments in Java

Comments are needed whenever the developer needs to add documentation about a function that is defined within the program. This is to enhance code readability and understandability. Comments are not executed by the compiler and simply ignored during execution.

The comments are of the following types:

a. Single-Line Comments in Java

The single-line comments consist of a single line of comment. We generally write them after a code line to explain its meaning. We mark the single-line comments with two backslashes(//).

For Example:

class SingleLineComment //Declaring the class
{
  public static void main(String[] args) {
    String str = “Tech Vidvan”
    //Declaring string with the value-”Tech Vidvan”
  }
}

String str = “DataFlair”;
// The value of i is set to 6 initially. The string has value “DataFlair”

b. Multi-Line Comments in Java

Multi-line comments, as the name suggests, span for multiple lines throughout the code. We generally write to them at the beginning of the program to elaborate on the program. Developers also use them to comment out blocks of code during debugging. We mark them using starting tag(/*) and an ending tag(*/).

For Example:

class MultiLineComment {
  public static void main(String[] args) {
    /* All this is under a multiline comment
   	The compiler won’t execute it
  	 	Thank you */
  }
}

Java Class

Class in Java is the blueprint that defines similar types of objects derived from it. A class represents a set of methods and properties that are common to all the objects. A class is one of the fundamental building blocks of Object-Oriented programming in Java. We can define a class in Java using the class keyword.

The syntax of the class is:

< access - specifier > class < ClassName > {
  instance variables;
  class method1() {}
  class method2() {}
} //end class

Example:

public class TechVidvan {
  int number;
  void teach() {
    System.out.println(“Learning java from TechVidvan”);
  }
}

Java Object

An object in java is an identifiable entity that has some characteristics and behavior. We create objects from class in Java. For example, a Fan is an object that has three characteristics: It has three blades, It has a brown color, etc. Its behavior is: it rotates at some speed. We can create the object of a class once we define a class.

The syntax of creating objects in Java is:

< className > <objectName > =new < className> ();

Example:

TechVidvan Java = new TechVidavn();

Object Creation in Java

Object in Java can be created in any of the following ways using:

  • new operator
  • new instance
  • clone() method
  • deserialization

Arrays in Java

An array in Java is a linear and homogeneous collection of the same type of elements. In array, there is contiguous memory allocation. An array is basically a group of similar variables referred under a common name. An array is a user-defined data type.

There are two types of arrays in Java:

  1. One-dimensional arrays
  2. Multi-dimensional arrays

Syntax of array:

int intArray[];	//declaring array
intArray = new int[20];  // allocating memory to array

Java Constructors

A Constructor in Java is a block of code that creates an object. Therefore, it is also called an object builder in Java. The constructor is very similar to a Java method. The main difference between them is that a constructor does not have a return type, not even void, unlike methods. We can often call it a method. The constructor automatically gets invoked during the object created using a new operator. The constructor’s name should be the same as the class name.

Example:

public class TechVidvan {
  public TechVidvan() {
    //code inside constructor
  }
}

There are two types of constructors in Java:

  1. Default constructor
  2. Parameterized constructor

Access Modifiers in Java

Access modifiers in Java enable users to limit the access of the entities or data they are defined with. Java provides following access specifiers:

1. public: There is no restriction of access and the data is accessible to every class or interface inside the same or different packages.
2. private: The private specifier allows entities to be accessible only inside the class in which we declare them.
3. protected: The class members declared with the protected keyword are accessible to classes within the same package or subclasses of different packages.
4. default: If there is no access modifier mentioned then Java uses the default access modifier. This access specifier limits the access within the same package only.

Jump Statements in Java

Jump Statements are the statements that help us to continue or discontinue a loop during the equation of a program. There are three types of jump statements in Java:

i. Break statement in Java

The ‘break’ statement or the ‘break’ keyword breaks the nearest loop inside which it is present. The execution of the program continues from the next line just when the current scope ends.

ii. Continue Statement in Java

The continue keyword or the statement continues the execution of the program from the next iteration of the loop. It causes the loop to skip the current iteration.

iii. Return statement in Java

The return statement is generally useful in Java methods. When the function completes its execution, it returns the value. After the execution of the return statement, the remaining statements of the function after the return statement does not execute.

Loops in Java

Loops in Java

Loops are the iterative statements that run a particular set of programs for a fixed number of times. Some of the types of iterative statements in Java are:

i. For loop in java

The ‘for’ loop causes a code snippet to run for a predetermined number of times. In a single statement, there is initialization, updation and test condition expressions.

For Example:

for (int num = 0; num < 5; num++) {
  System.out.println(“Hello”);
}

This prints Hello five times on the output screen

ii. Java While loop

The while loop runs indefinitely until the condition becomes false.

For Example:

while (num < 6) {
  System.out.println(“Hello”);
  num++;
}

This prints Hello on the screen five times until the value of num becomes 6

iii. Java do-while loop

The do-while loop works the same as the while loop. The only is that in the do-while loop, the execution occurs at least once even if the condition is false.

For Example:

do {
  System.out.println(“Hello”);
}
while ( num > 6 );

Conditional Statements in Java

Conditional Statements in java

Conditional statements are the statements that are purely based on the condition flow of the program. There are mainly three types of conditional statements in Java:

i. Java if statement

The if statement suggests that if a particular statement results in true then the block enclosed within the if statement gets executed.

For example:

if (condition) {
  //action to be performed of the condition is true
}

ii. Java if else statement

The if-else statement states that if a particular condition is true then the if block gets executed. If the condition is false, then the else block gets executed.

Example:

if (condition) {
  //action1, if conditions true
}
else {
  //action2, if condition is false
}

iii. Java Else if statement

The else if statement encloses an if statement within an else blocks.

Example:

if (condition) {
  action 1
}
else if (condition2) {
  action 2
}

iv. Java Switch case

The switch case is responsible for checking multiple conditions. The sitch case is based on the value of the variable that we pass in the switch statement. The value of the variable shows the flow of the control to either of the case blocks that we write.

Example:

switch (variableName)
case value1:
  action1;
  break;
case value2:
  action2;
  break;
default:
  action3;
  break;

Packages in Java

A package in Java is a group of classes, interfaces, and sub-packages of the same kind. Packages are of two categories:, the built-in package, that are provided by Java, For example, java, lang, util, awt, javax, swing, net, io, sql etc, and the user-defined packages.

Example of Java package:

We can create a java project using the package keyword.

package com.techvidvan.packageprogram; //package creation
class SimpleProgram {
  public static void main(String args[]) {
    System.out.println("Hello Reader, Welcome to TechVidvan");
  }
}

String in Java

Java String is a reference data type that represents text enclosed within double quotes( “ ” ). String is a sequence of characters, that are useful to print any text or message. Strings are immutable, i.e. we cannot change them once created. The string always ends with a null character or ‘\0’.

There are two ways to create a Java string are:

  • Using a string literal in Java
    String name = “TechVidvan Java tutorial”;
  • Using a new keyword
    String name = new String(“TechVidvan Java tutorial”);

Interface in Java

An Interface in Java is a collection of abstract methods in Java. We will learn more about interfaces in the following tutorials.

We define interfaces as below:

interface < interfaceName > {
  //static functions
  //abstract methods
}

Example:

interface techVidvan {
  abstract void teachJava();
  abstract void teachPython();
  static void evaluate();
}

Abstract Class in Java

An Abstract Class in Java has one or more abstract methods. Abstract methods are methods without the body. An abstract class is similar to the interface, but the difference is that it can contain default method implementation. We use the abstract keyword to create a class or method abstract.

Object-Oriented Concepts in Java

As we all know that Java is an object-oriented language, there are many concepts of the same. Some object-oriented concepts in Java are:

1. Abstraction

An abstraction is a technique of hiding irrelevant details from the user, and showing only the necessary ones. For example, the driver knows how to drive a car; he does not need to know how the car runs. In Java, we can achieve abstraction using abstract class and interface.

2. Encapsulation

An encapsulation is a process of wrapping up data and functions/methods into a single unit. An example of encapsulation is the class in Java that contains both properties and methods.

3. Inheritance

Inheritance is the mechanism by which one class acquires all the features of and properties from another class. We can achieve Inheritance in Java by using the ‘extends’ keyword. Inheritance facilitates the reusability of the code.

4. Polymorphism

Polymorphism is the capability to occur the same thing in multiple forms. In other words, Polymorphism states single action in different ways. For example, a girl in the classroom behaves like a student, in house behaves like a daughter. There are two types of polymorphism in Java: Runtime polymorphism(Method Overriding) and Compile-time polymorphism (Method Overloading).

Exception in Java

Java exception arises during the execution or runtime of a program. Exceptions occur unexpectedly, and they can result in disrupting the normal flow of the program. An exception is something that every programmer faces at any point of coding. Exceptions can arise from different kinds of situations like hardware failure, entering the wrong data, network connection failure, Database server down, etc.

Types of Exception in Java:

1. Checked Exception in Java

Checked Exception, also called the compile-time exception, occurs at the compile time. The programmers need to write a code to handle them. Some examples of checked exceptions are IOException, SQLException, etc.

2. Unchecked Exception in Java

Unchecked Exception, also called Runtime Exceptions, because it occurs at runtime. It depends upon the programmer to catch the runtime or unchecked exceptions.
Some examples of unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

3. Java Error

Error is not an exception, but rather, it is an issue that emerges out of the control of the user or the developer. Programmers generally overlook errors in their code. Some examples of errors in Java are VirtualMachineError, AssertionError, etc.

Exception Handling in Java

The process of dealing with exceptions is called Exception Handling in Java. Java provides a robust and efficient way to handle exceptions. Exception Handling helps you to maintain the flow of execution and get desired results.

To handle exceptions in Java, there are some important keywords or blocks that you should know:

  1. Try catch block
  2. Throw.throws keywords
  3. The finally keyword

1. try-catch block in Java

We use a combination of try-catch blocks to detect and catch an exception. We have to place the try-catch block around the code that can generate an error or exception. The code inside the try-catch is called the protected code.

Syntax of try-catch block:

try {
  //Protected code
}
catch(ExceptionName e1) {
  //Catch block
}

2. Throws Keyword in Java

If there is a method that can not handle a checked exception then we must declare this method using throws keyword in Java. The throws keyword appears at the end of a method’s signature.

Example:

public void myMethod() throws IOException {}

3. Throw Keyword in Java

We can throw an exception using a throw keyword. We can throw by instantiating it using a new keyword by using the throw keyword.

For example:

throw new ClassNotFoundException();

4. Finally block in Java

Java finally block is the block of code that always executes, no matter if there is an exception or not. The finally block allows us to run any statement irrespective of the code present inside the try block.

A finally block has the following syntax:

try {
  //Protected code
}
catch(ExceptionType1 e1) {
  // Catch block
}
catch(ExceptionType2 e2) {
  // Catch block
}
finally {
  // The finally block always executes.
}

Conclusion

Java is one of the widely-used and popular programming languages. We can see Java holds the first position in the TIOBE index, for the last 2 years. Java is not only used in application development, but also in the fields like Big Data, networking, Data Science, etc. In this tutorial, we took a brief look at the basics of Java programming language. We learned the basic concepts of Java in this article that you should know to start programming in Java.

Hope you found this article useful. Do check TechVidvan Java Tutorial series to learn more!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.