Java Tutorial for beginners

incoggeek
Javarevisited
Published in
13 min readOct 11, 2022

Introduction

Hello guys, 🙋‍♂️

I hope you are doing well.

I’m back with another programming language tutorial. And if you find this helpful please let me know. So now let’s begin….

Photo by Clément Hélardot on Unsplash

What is programming language and its need?

  • To communicate with people, we use one of the most comfortable languages similarly when it comes to communicating with the computer we use one programming language such as Java, C, C++ and so. A programmer instructs a computer to perform a task through a programming language.
  • Java is an object-oriented programming language. It was developed by Sun Microsystems in 1991 and James Gosling was one of the founders called Oak.

Features

Simple

The Java language is easy to learn and its coding style is easy to read and write. It contains many features of other Languages like C and C++ and Java removes complexity because it doesn’t use pointers and doesn’t support Multiple Inheritance.

Platform Independent

This is where Java’s “Write Once, run anywhere” motto comes in. It means that you can develop on one environment (Operating System) and run on another without modifying the code.

Architectural Neutral

Java application runs the same bytecodes regardless of any environment (Operating System). The compiler generates an architecture-neutral object file format to enable a Java application to execute program even if things like CPU architecture is changed.

Dynamic and Extensible

Java has Dynamic and Extensible means with the help of OOPS you can add classes and plug in new methods to classes, creating new classes through subclasses. This makes Java very easy to augment with your classes or even modify.

Portable

Java programs can execute the same program in any environment (Linux, Windows, Mac etc.) for which a Java run-time system (JVM) exists without changing the code.

Robust

Java has some features like strongly typed checking, garbage collection and exception handling that helps to prevent ungrateful termination of program and compilation errors.

Secure

Since bytecode is interpreted by JVM (Java Virtual Machine). Inside JVM, there’s a bytecode verifier that ensures bytecode is generated by valid compiler and doesn’t contains malicious code and security manager that responsible for security. This is also known as sandbox checking.

Object Oriented

Encapsulation The process of binding data and corresponding behaviour (methods) into a single unit is nothing but encapsulation. If any component follows data hiding and abstraction such type of component is said to be encapsulated component.

Encapsulation = Data hiding + Abstraction

Data hiding

Outside persons cannot access our internal data directly or our internal data should not go out directly. This OOP feature is nothing but data hiding. After authentication, an outside person can access our internal data. For instance, after proving valid username and password we can able to access Gmail.

  • It is highly recommended to declare data members (variables) as private.
  • Data hiding provides security

Abstraction

In Object-oriented programming, abstraction is a process of providing functionality to the users by hiding its implementation details from them. In other words, the user will have just the knowledge of what an entity is doing instead of its internal working.

Advantages

  • Security
  • Easy enhancement
  • Reduce system complexity
  • Maintenance

Tightly encapsulated class

A class is said to be a tightly encapsulated class if and only if each and every variable is declared as private whether the class contain a corresponding getter and setter or not.

Inheritance

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

Polymorphism

It enables developers to write code that can work differently based on the context, makes your code more flexible, and extensible.

Multi-threaded

Java provides built-in support for multithreaded programming. Multithreaded programming contains two or more parts that can run concurrently. Each piece of such a program is called a thread, and each thread defines a separate path of execution. The primary purpose of multithreading is to provide simultaneous execution of two or more parts of a program to make maximum use of CPU time.

Distributed

Distributed application is a software executed or run on multiple computers in a network. They interact in order to achieve a specific task, and you have these applications running on both the client and server system. Basically you have multiple users trying to access the system at once. The interaction here is between the client systems that access the data and the server that processes the data.

Compiled and Interpreted

Java is a compiled and interpreted language, source code is converted into bytecode by java compiler and interpreted by Java virtual machine (JVM). Thus, Java gets both privilege.

High-Performance

Java is far better than other interpreted programming languages but not up to the mark than compiled language such as C, C++

Dynamic

In Java, Header file would be loaded only if program requires otherwise it wouldn’t. Thus, it provides dynamic loading.

How does it work?

Source code is converted into bytecode via java compiler and bytecode is interpreted via java virtual machine.

How Java Program Executes
JDK

💡 Java Development Kit (JDK): Java Development Kit provides an environment to develop and run programs. Java Run Time Environment (JRE): Java Run Time Environment provides an environment only to run programs.

Java Virtual Machine (JVM): Java Virtual Machine interprets programs line by line.

Package: In Java, a package is used to group related classes.

The basic structure of a program

class Greet {
public static void main (String args[]) {
System.out.print("Assalamoalaikum");
}
}

Naming Convention

  • For classes we use PascalConvention
  • For functions we use camelConvention

Identifiers / Variables

Identifiers are the name that is used for identification purpose. It can be a class name, method name or label name.

Rules for defining java identifiers

  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  • After the first character, identifiers can have any combination of characters.
  • Digit from 0 to 9
  • A keyword cannot be used as an identifier.
  • Most importantly, identifiers are case-sensitive.

💡 Examples of legal identifiers: age, $salary, _value, __1_value.

Examples of illegal identifiers: 123abc, -salary

There’s no length limit in java identifiers

All pre-defined java class names and interface names can be used as variable

Reserved Keywords

Reserved words are words that cannot be used as object or variable names in a Java program because they’re already used by the syntax of the Java programming language.

Reserved Keywords

💡 In the Java program, the return type is mandatory whereas in C is optional and the default return type is int. The usage of goto and const keywords is banned in Java. So use final instead of const

  • Null is the default value of object reference.
  • In java, we have only a new keyword and there’s no delete keyword because the useless object is the responsibility of the garbage collector.
  • Java is a strongly typed programming language. And every assignment is checked by the compiler for type compatibility.
  • Java is not a pure object programming language because several OOP features don’t work such as operator overloading, multiple inheritances etc.

Primitive Data type

Primitive data types

byte

  • A byte is a small unit of digital information.
  • It consists of bits.
  • Min value representation: -128
  • Max value representation: +127
  • Range: -128 to +127

💡 Positive numbers will be represented directly in the memory whereas negative numbers will be represented in 2’s complement of form.

💡 A byte is the first choice if we want to handle data in terms of streams either from the file or from the network (file-supported form and network-supported form is a byte)

short

  • It consists of 2 bytes (16 bits).
  • Range: -2¹⁵ to 2¹⁵-1
  • Min value representation: -32,768
  • Max value representation: 32,767

💡 Short is the best suitable for 16-bit such as 8085 but these processors are completely outdated and hence corresponding data type is also outdated.

int

  • int data type is a 32-bit signed two’s complement integer.
  • Minimum value is — 2,147,483,648 (-2³¹)
  • Maximum value is 2,147,483,647(inclusive) (2³¹ -1)
  • An integer is generally used as the default data type for integral values unless there is a concern about memory.
  • The default value is 0
  • Example: int a = 100000, int b = -200000

long

  • A long data type is a 64-bit signed two’s complement integer
  • It consists of 8 byte
  • Minimum value is -9,223,372,036,854,775,808(-2⁶³)
  • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2⁶³ -1)
  • This type is used when a wider range than int is needed
  • The default value is 0L
  • Example: Speed of light, Distance of another universe

💡 The number of characters present in a big file may exceed int range hence the written type of length method is long.

long l = f.length()

float

  • The float data type is a single-precision 32-bit IEEE 754 floating point
  • It consists of 4 bytes
  • Range: -1.7e38 to 1.7e38
  • Float is mainly used to save memory in large arrays of floating point numbers
  • Default value is 0.0f
  • The float data type is never used for precise values such as currency
  • Example: float f1 = 234.5f

double

  • A double data type is a double-precision 64-bit IEEE 754 floating point
  • It consists of 8 bytes
  • This data type is generally used as the default data type for decimal values, generally the default choice
  • The double data type should never be used for precise values such as currency
  • Default value is 0.0d
  • Example: double d1 = 123.4

💡 If we want 5–6 places of accuracy then we should go for float and if we want beyond it we should go for double.

boolean

  • boolean data type represents one bit of information
  • There are only two possible values: true and false
  • This data type is used for simple flags that track true/false condition default
  • Default value is false
  • Example: boolean x = true

char

  • char data type is a single 16-bit Unicode character
  • It consists of 2 byte
  • Minimum value is ‘\u0000’ (or 0)
  • Maximum value is ‘\uffff’ (or 65,535 inclusive)
  • Char data type is used to store any character
  • Example: char letterA = ‘A’

Arrays

An array is an indexed collection of a fixed number of homogenous data elements. The main advantage of an array is we can represent a huge number of values single variable so that the readability of code will be improved. But the disadvantage of array is fixed in size.

Array declaration

One dimensional

int[] x;  //Recommend
int []x;
int x[];
int[8] x; // Compiler time error: At time of declaration we can't specify the size

Two dimensional

//Ways of valid declarations
int[][] x;
int [][]x;
int x[][];
int[] []x;
int[] x[];
int []x[];

💡 Every array in java is an object hence we can create arrays by using new operator. For every array type corresponding classes are available. And these classes are part of java language and not available for programmer level.

//array is reference variable
int[] array = new int[sizeOfArray];
System.out.println(array.getClass().getName());
// Output: [I

💡 At the time of array creation compulsory we should specify the size. Allowed size should be in a byte, short, int and char otherwise we will get compile time error

💡 A negative index will throw run time exception

int[] array = new int[10];

Array to be continued

Variables

Based on type of value

  1. Primitive variables can hold exactly one value of its declared type at a time. For example, an int variable can store one integer at a time. When another value is assigned to that variable, the new value replaces the previous one — which is lost.
  2. Reference variables are used to store the addresses of objects in the computer’s memory. Such a variable is said to refer to an object in the program.
public class Test {
public static void main (String[] args) {
int digit = 9; // Primitive variable
System.out.print(digit);
}
}
public class Details {
String name; //Instance variable
public static void main (String[] args) {
// Reference variable
// myName stores address of object Details@76ed5528
Details myName = new Details();
System.out.print(myName);
}
}

Based on the type of positional declarations & behaviour

  1. Instance variables

If the value of variable varies from object to object. For every object, a separate copy of instance variable will be created. It should be declared within class directly but outside of any method, block or constructor.

  • Instance variable is created at the time of object created and destroyed at the time of destruction. Hence the scope of instance variable is exactly same as scope of object.
  • Objects & Instance variables are stored in heap memory.
  • We can’t access instance variable directly from static area but we can access by using object reference.
  • It is also known as object level variable

2. Static variables

  • It should be declared using static keyword within class directly but outside of any method, block or constructor.
  • Static variable is created at the time of class loading created and destroyed at the time of class unloading. Hence the scope of instance variable is exactly same as scope of class file.
  • Static variable is known as class level variables or fields
  • Static variable is stored in method area
  • For static variable JVM will provide default values
  • Only one separate copy of static variable is created while multiple copy of instance variable is created for every new object.
public class Test {
static int digit = 9; // Static variable
public static void main (String[] args) {
Test t = new Test();
// System.out.print(t.digit); // Can be accessed but not recommended because of readability
System.out.print(Test.digit); // Should be accessed via class name
}
}

💡 We can access static variables without above way if we are accessing in same class.

3. Local variables

  • The local variable is stored in stack memory and it is temporary data
  • The Local variable will be created while executing the block in which we declared it once block execution completes automatically local variable will be destroyed hence the scope of local variable a is the block in which we declared it.

Class and Object

  • Class is a group of elements having common properties and behaviours. It’s virtual encapsulation of the properties and behaviours.
  • Among the group of elements an individual element has physical properties and physical properties and physical behaviours then that individual element is called an object. It’s physical encapsulation of the properties and behaviours.
  • The Method also known as Function, is used to solve a particular task or specific operation.

💡 Class is virtual and Object is real. Class is a blueprint for the object while an object is an instance of the class.

Operators & Assignments

Increment & Decrement Operators

// Pre-increment
y = ++x
// Post-increment
y = x++
// Pre-decrement
y = --x
//Post-decrement
y = x--
  • We cannot apply increment or decrement on constant value e.g. ++30
  • We are not allowed to perform operations such as ++ (++x)
  • We cannot assign a value or increment or decrement operators to a final variable.
  • Increment / Decrement works with int, and char, double but not boolean.
// Correction of above code
byte b = 10
b = (byte) (b + 1)
System.out.print(b); // 11
byte b = 10
b = b++
System.out.print(b); // 11 because of internal typecasting

💡 In integral arithmetic (byte, short, int, long) there is no way to represent undefined result. hence we will get run time arithmetic exception. But in floating point arithmetic float and double there is a way to represent undefined results. They contain NaN constant.

Flow Control

Flow control describes the order in which the statements will be executed at run-time.

There are 3 types of Flow Control Statements :

  1. Selection Statements In Selection Statements, among several options, only one option will be selected and will be executed.

if-else

  • If() takes boolean type parameter only.
  • else part is optional
  • {} is optional for one line statement which should not be declarative statement

Examples

//Example 1
boolean b = true;
if (b = false) {
System.out.print('hello');
}
else {
System.out.print('hi');
}
// Output > Hi
//Example 2
boolean b = false;
if (b == false) {
System.out.print('hello');
}
else {
System.out.print('hi');
}
// Output > Hello
//Example 3
if (true); // valid syntax
//Example 4
if (true)
if (true)
System.out.print("Hi");
else {
System.out.print("Hello");
}
//else belongs to second if

switch( )

  • If several option is available recommended to use switch()
  • Only byte, short, char, int are allowed as argument in switch()
  • In switch() case and default both are optional, though it’s meaningless but it won’t throw error.
  • Inside switch, every statement should be under case or default.
  • Variable should not be used to in case label e.g case a
  • switch argument and case label both can be expression but expression should be constant
  • Every case label should be in the range of switch argument type
  • Duplicate case is not allowed
  • Fall through inside switch is advantage for program like quarter-month program

2. Iterative Statements In Iterative Statements, a group of statements will be executed iteratively.

while( )

  • If we don’t know the number of iteration in advance then ‘while loop’ is recommended to use.
  • While() condition takes boolean type parameter only.
  • Unreachable statement throws error in java
//Example 1
int a = 10 , b = 20;
//Compiler doesn't consider its value because it's not final.

while (a<b) {
System.out.print("Hello");
}
System.out.print("Hi");
//Example 2
final int a = 10 , b = 20;
//Compiler considers its value because it's final.
while (a<b) {
System.out.print("Hello");
}
System.out.print("Hi");

do-while( )

  • do-while() executes at least once
  • While() condition takes boolean type parameter only.
  • {} is optional for one line statement which should not be declarative statement
//Example 1
do
while(true);
//Loop is not having body

//Example 2
do while(true)
System.out.print("Hello");
while(false);
//Valid code

for( ) loop

  • If we know the number of iteration in advance then ‘for loop’ is recommended to use.
  • In initialization section of for loop we can take any valid java statement.
  • In condition section of for loop we can take any valid expression of boolean type;
  • Condition section is optional complier will place true by default
  • Increment/decrement section we can take any valid java statement.
  • All part of for loop are optional and independent.
  • for-each ( introduced in the 1.5 version ) :Also known as enhanced for-loop especially designed to retrieve Arrays & Collection but it’s not general use

3. Transfer Statements

  • break : With the break statement we can stop the loop even if the while condition is true.
  • continue : With the continue statement we can stop the current iteration, and continue with the next.

Constructors

A constructor in Java looks like a method that is used to initialize objects. The constructor is called when an object of a class is created.

class Student {
int enrolmentNo;
char gender;
int age;

Student (int enrolmentNo, char gender, int age) {
this.enrolmentNo = enrolmentNo;
this.gender = gender;
this.age = age;
}
public static void main (String args[]){
// Constructor
Student student1 = new Student(59,'M',19);
}
}

I am happy to be able to share it with you guys. I’ll be adding more topics on Java programming, Thanks for reading. Hit the clap button and drop your comment.

--

--