Java Programming


 

Java is a plat form independent , object oriented language

invented by scientist "James Gosling" in sun microsystem

initiated in June 1991

java was originally designed for developing software for network consumer electronic devices

language was initially called OAK.

OAK is a tree which is located outside of James gosling office


name "java" specifically doesn't have any meaning rather it refer to the hot aromatic drink coffee

as name java is derived from coffee cup java programming language icon is coffee cup


java features

1)simple

2)secure

3)Robust

4)Portable

5. Architecture neutral

6. object oriented

7. multi-threaded

8. high performance

9. Distributed

10. Dynamic

11. Byte coded

12. Interpreted

13. Garbage collected

14. open source







platform independent : program that is compiled on windows can run on Linux and vice versa

Object Oriented : Way of organizing programs as collection of objects each of which represents as instance of a class








Platform Independent: program that is compiled on windows can run on Linux and vice-versa

Object Oriented:  way of organizing programs as collection of objects, each of which represents an instance of a class

                          Abstraction, Encapsulation, Inheritance, Polymorphism -> 4 main concepts of OOP

Robust:  puts a lot of emphasis on early checking for possible errors

             main features of java that makes it robust are garbage collection, Exception Handling and memory allocation

Secure: We don’t have pointers and we cannot access out of bound arrays

            several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.

Distributed:  java programs can be distributed on more than one systems that are connected to each other using internet connection.

                  Objects on one JVM (java virtual machine) can execute procedures on a remote JVM

Multithreading: allows concurrent execution of two or more parts of a program for maximum utilization              of CPU.

Portable: byte code can be carried to any platform for execution that makes java code portable.

 

  • JVM - Java Virtual Machine
  • Provides  Runtime Environment in which Java bytecode can be executed
  • Tasks of JVM
    • Loads Code
    • Verifies Code
    • Executes Code
    • Provides Runtime Environment
  • JVM is platform dependent  i.e.  for each platform we have different JVM Configuration
  • JVM does not exists Physically. It is abstract in nature.
  • The primary function of JVM is to execute the byte code produced by compiler
  • Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. Which means that the byte code generated on Windows can be run on Mac OS and vice versa.
  • The JVM doesn’t understand Java source code, that’s why we need to have javac compiler that compiles *.java files to obtain *.class files that contain the byte codes understood by the JVM
  • JVM makes java portable (write once, run anywhere). Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems.
  • Java is a high level programming language. A program written in high level language cannot be run on any machine directly. First, it needs to be translated into that particular machine language
  • The javac compiler does this thing, it takes java program (.java file containing source code) and translates it into machine code (referred as byte code or .class file).

 

JRE

 

  • JRE- Java Runtime Environment
  • JRE = JVM + set of Libraries
  • JRE contains set of libraries that JVM uses at runtime
  • JRE Physically exists
  • JRE is Platform Dependent

 

  • JRE is the environment within which the java virtual machine runs
  • You can run the code in JRE but you can’t develop and compile the code in JRE.
  • JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger.
  • Actually, JRE is the implementation of JVM, as JVM runs the program by using class libraries and other files provided in JRE
  • If you only want to run any Java program, you should have JRE installed in the system, but we don’t need JDK to run any Java program.

 

 

JDK

 

  • JDK – Java Development Kit
  • JDK= JRE+ Development Tools
  • It is a fully featured Software Development Kit
  • Development Tools:  javac, java, javadoc etc

 

  • JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.
  • It is a kit that is the combination of developing tools to develop Java programs and JRE (Java Runtime Environment) to run the programs.

 

 

 

Java Installation

 

 

IDE Installation

 

 

Java Terms

 

  • Compiler (Javac)
  • Byte-Code
  • ClassPath
  • Just In Time Compiler (JTI)
  • Garbage Collector

 

 

  • Java is a high level programming language. A program written in high level language cannot be run on any machine directly. First, it needs to be translated into that particular machine language. The javac compiler does this thing, it takes java program (.java file containing source code) and translates it into machine code (referred as byte code or .class file).
  • Javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM
  • The classpath is the file path where the java runtime and Java compiler look for .class files to load. By default, JDK provides many libraries. If you want to include external libraries they should be added to the classpath.
  • The Just-In-Time (JIT) compiler is a an essential part of the JRE, that is responsible for performance optimization of java based applications at run time. Interpreting the bytecode affects the speed of execution. The JIT compiler aids in improving the performance of Java programs by compiling bytecode into native machine code at run time. A just-in-time (JIT) compiler is a program that turns bytecode into instructions that can be sent directly to a computer's CPU. JIT compiler runs after a program starts and compiles code. A common way to say this is that a JIT compiler compiles code on the fly, or in other words, just in time. JIT compilers contrast different compiler types such as a traditional compiler, which will compile all code to a machine language before a program starts to run. bytecode must be compiled and translated to a language a CPU can properly understand. However, how that bytecode is translated into a native language may have a large impact on the speed and performance of an application. To improve performance, JIT compilers will, at runtime, compile suitable bytecode sequences into machine code. When the same block of bytecode is needed again, the previously created object code will be used. https://www.theserverside.com/definition/just-in-time-compiler-JIT
  • Java applications obtain objects in memory as needed. It is the task of garbage collection (GC) in the Java virtual machine (JVM) to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses. Because memory is automatically reclaimed in the JVM, Java application developers are not burdened with having to explicitly free memory objects that are not being used. https://www.eginnovations.com/blog/what-is-garbage-collection-java/

 

 


 

JVM Architecture

 

Working of JVM

 

  • Behaves as a run-time engine to run Java applications
  • JVM performs the following tasks:
    • Loads the code
    • Verifies code
    • Executes the code
    • Provides a run-time environment for various applications
    • JVM provides a Memory area
    • Provides a Register set
    • JVM provides the garbage collection heap

 

 

 

Subsystems of JVM

 

 

There are three main subsystems in JVM Architecture

    • Class Loader
    • Memory Area
    • Execution Engine

 

 

JVM Classloader

 

Three important functions of ClassLoader are Initialization, Loading, Linking

 

 

Loading

 

  • The Classloader reads the .class file, generates the corresponding binary data, and saves it in the method area.
  • After loading the .class file, JVM creates an object of type Class to represent this file in the heap memory.
  • To get this object reference we can use the getClass() method of Object class.

Three built-in classloaders in Java are:

  • Bootstrap ClassLoader

              This is the classloader which is the super class of Extension classloader. It loads the rt.jar file.

  • Extension ClassLoader

              It is the ClassLoader which loads the jar files present in the ext directory. This is the child Bootstrap classLoader and parent of System classloader.

  • System/Application ClassLoader

              It is the classLoader which loads the class files from the application classpath. This is the child of the Extension classloader.

 

 

Linking

 

    • This operation combines different files in the main program together
    • Performs verification, preparation, and (optionally) resolution

 

 

  • Verification: The Verification phase checks the correctness of the .class file. It means that it checks that the file formation and generation is by a valid compiler or not. If the verification fails then we get a java.lang.Verify Exception.
  • Preparation: JVM allocates memory for class variables and initializes the memory to default values.
  • Resolution: Resolution is the process of replacing symbolic references with direct references. It uses searching into the method area to locate the referenced entity.

 

 

Initialization

 

    • Involves the assignment of all static variables with their specific values

 

JVM Memory area

  • 1. Method Area– It stores the structure of each class like method data, field data, runtime pool, metadata.
  • 2. Heap– Heap is the runtime area where object allocation takes place.
  • 3. Stacks– Stacks store the partial results and local variables of a program. Whenever a thread is created, there is a simultaneous creation of JVM stack. When we invoke a method, a new frame creates and destroys at the same time when the invocation process completes.
  • 4. PC Registers – It stores the address of the currently executing JVM instruction.
  • 5. Native Method Stacks – It includes all the native methods required in any application. It is not written in java.

 

JVM execution engine

 

It is the component of JVM that reads data from memory locations and executes the instructions. It has three major components namely a virtual processor, an interpreter, and a JIT compiler.

  • Virtual Processor
  • Interpreter: Read the bytecode stream then execute the instructions.
  • Just-In-Time(JIT) compiler: It improves performance. JIT compiles parts of the byte code with similar functionality at the same time and reduces the amount of time needed for compilation.

 

 

What is JAR

 

    • Java Archive
    • Compressed  format of compiled Java Project
    • Contains .class files + metadata + other resources
    • Used to distribute java code to be used by other projects/direct execution of java programs.
  • It is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform
  • In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image files, or directories


First of all we must install JDK and put in one any location you want

open edit environment variable

in path just add location upto bin folder where you have kept jdk folder



console application



My first Java Program

// basic java program to print "hello world"


import java.io.*;


class MyFirstJavaProgramme 

{

public MyFirstProgramme 

{

public static void main(String[] args)

{

// prints hello world

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

}

}



 

Comments

             

  • Comments are used for explaining code.
  • Compilers ignore the comment entries and do not execute them

Single Line Comments

              Syntax: // Single Line Comment

Multi Line Comment

              Syntax:  /* Multi line comments*/

 

 

Explanation

 

Package

             

  • Mechanism to encapsulate a group of classes, sub packages and interfaces
  • Packages are named in reverse order of domain names
  • Packages that are inside another package are the subpackages
  • Built In Packages:
    • Java.lang
    • Java.io
    • Java.util etc

 

  • Preventing naming conflicts
  • Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
  • Providing controlled access
  • Packages can be considered as data encapsulation
  • 1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
    2)  java.ioContains classed for supporting input / output operations.
    3)  java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.
    4)  java.applet: Contains classes for creating Applets.
    5)  java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
    6)  java.netContain classes for supporting networking operations.
  • // All the classes and interfaces of this package will be accessible but not subpackages.

              import package.*;

 

  •  import java.io.*: This means all the classes of io package can be imported. Java io package provides a set of input and output streams for reading and writing data to files or other input or output sources.
  • class : class keyword is used to declare classes in Java. The class contains the data and methods to be used in the program.
  • public : It is an access specifier. Public means this function is visible to all.
  • static : static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. The main() method here is called by JVM, without creating any object for class.
  • void : It is the return type, meaning this function will not return anything.
  • main : main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.
  • String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.
  • System.out.println : This is used to print anything on the console like printf in C language.

 

Compile and Run

 

  • Save your program with .java extension
  • Compile program with: javac MyFirstJavaProgram.java
  • Run program with: java MyFirstJavaProgram

 

Naming Convention

Classes are started with capital letter ( Integer, String)

Method are started with lower case letter and uppercasing all other first letter (Camel case)

https://www.geeksforgeeks.org/java-naming-conventions/



comments


Constants are named with all upper case letters and underscores


IDE

Integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development

Consists of source code editor , build automation tools debugger, compiler
.

Using IDE is very useful and handy

To make documentation

/** and press enter

go to tool in Intellij or project in eclipse and click on generate docs

Tips and best practices

please always remember
if a specific chunk of code is commented just to hid code - you don't need it in you project

comments require maintenance and they can be misleading

in the future -- your unit test will perform role of documentation

To increase code readability - do not rely only on documentation. write code according to java code conventions and choose meaningful names for methods and variables



Data type exist in java

Data type

primitive type(Stores actual value)
Integer
Floating point numbers
Booleans
Characters

Reference types(Stores address)
Classes
Annotations
Interfaces
Enumerations
Arrays

Primitive types


Variables
Java s strongly typed language
every variable has a type
every expression has a type
Each type is strictly defined

variable is a piece of memory that can contain a data value

Java is strongly typed language each variable has a type

A variable is defined by the combination of identifier and a type

You can declare variable with 'var' keyword -- in this case type of the variable will be defined by the compiler

All variable have a scope which defines their visibility

You can't give name to variable of java keyword

Number system

binary number system
radix 2
0,1

Array 
Array s an object which contains  elements of similar data types and support access to them by index
index o the first element in array is 0
No dynamic size

int[] arr;
int arr[]'
arr= new int[10];
int[] arr={1,2,3};

int[][] matrix = {
    {1,2,3},
    {4,5,6}

}  

System.out.print(Arrays.toString(arr));
Arrays.sort(arrr)
System.outprint(Arrays.toSring(arr));


Operator

sign or symbol which perform certain operations
if there is one operand it is called unary operator
int i=+10;
int i2=-10;
int i3= ++i;
int i4= i++;
int i5 = --i;
int i6= i--;



if there is two operand it is called binary operator

+
_
/
%
*


if there is three operand it is called ternary operator



types of operator

1. Arithmetic operator

2. Assignment Operator
=
+=
-=
*=
/=
%=

right hand operand is assign to left hand operand




3. Relational Operator
==
!=
>
<
>=
<=

result produce by relational operator is also Boolean value i.e. either true or false



4. Logical Operator
result obtained from logical operator is also Boolean value only i.e. either true or false
&
&&
|
||
!
^(x-or)



5. Bitwise Operator
&
|
^
~(binary 1's complement)
>> ( binary right shift operator)
>>>
<< (binary left shift operator)



5. Ternary Operator

(condition) ? true expression : false expression

System.out.print(2>1:"2 is greater than 1": "2 is not less than 1");


Operator precedence
from highest to lowest






OOP 
OOP is a programming paradigm based on the concept of object

OOP is a computer programming model that organizes software design around the objects rather than function

Object oriented programming is a software design approach in which concept of object occupies the first place

every this is object in OOP
array is object, unexpected situation during the program execution is object and connection to database is also an object

Car
has properties like door body. trunk, steering wheel, headlight, wheels, engine, color

and has behavior methods like tun on headlight, stop engine, turn left, break, start engine, turn right, accelerate, open trunk

object is a virtual entity with specific list of properties which can distinguish it from other objects and behavior which allow to manipulate with these properties


in simple words object = data + behavior

object is an instance of class


Class is a template for object


Functional programming vs OOP

functional programming
our main concept is function
functional programming approach works best where you don't care about order of function execution

OOP
our main concept is object
OOP approach allow you to organize you code and program execution in structure way



OOP advantage
Modularity: you know which module to look
scalability: we can scale software easily. so adding more features is easy
lower cost of development
Security and reliability

Programming is always just a question of trade-offs between maintainability, scalability, speed of development, code quality and reliability


Basic OOP principle

Inheritance
allow you to create new class based on another one
new class can extend existing one and share properties and behaviors
new class is called child class and basic class is called parent class
Inheritance allow you to reuse code and to create new classes without reinventing the wheel



Encapsulation
This key principle tells us to keep data and code that can manipulate this data together. It is also about keeping data and the code safe from external interference.

access modifiers in java
private
default
protected
public





access modifiers  exist to facilities encapsulation

private restricted one

default can be access out of package


protected can be access within the class and out of package


public can be access from anywhere



Polymorphism

one interface --- multiple implementations


Abstraction


if you create good abstraction for your specific case it would allow you to not duplicate code, to support good scalability of your units and lots more


class and object


class consists of
constructors
fields
methods
initialization block
nested classes



fields are properties
with the help of fields we can express state of specific object fields can have different modifiers





static block will be executed only once when class will be uploaded into JVM


constructor is special method which should be called to instantiate object


function can exist without object independently

where as method is behavior of an object




Different types of classes

concrete classes
nested classes
final classes
POJO classes
Abstract Keyword
Anonymous classes
Abstract keyword


concrete class have no implementation of all of its methods

creating object of one class with help of other class

// init statc nested class

for eg Tax tax = new Cart.Tax:(some tax type",0);


// init inner class
Discount discount = new Cart().new Discount("firstClientDiscount",0);





just add final before class keyword to make a final class



Abstract

we cannot create instance of abstract class

abstract method of abstract class must be implement in child class body else there will be error





Anonymous class

ClassName1 cn1 = new Class0( ) {

@override
public datatype method( ) 
{
return datatyevalue;
};

}



What is SOLID principles?

S- single responsibility principle

    A class should have only one reason to change

O- Open/Close principle

    
L-Liskov substitution principle
I- Interface segregation principle
D- Dependency inversion principle




Comments