Java Overview

Introduction

  • Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. 
  • James Gosling is known as the father of Java. 
  • Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the Oak name to Java.

History of Java

  • James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.
  • Initially designed for small, embedded systems in electronic appliances like set-top boxes.
  • Firstly, it was called “Greentalk” by James Gosling, and the file extension was .gt.
  • After that, it was called Oak and was developed as a part of the Green project.
  • Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany, Romania, etc.
  • In 1995, Oak was renamed as “Java” because it was already a trademark by Oak Technologies.

Features of Java

  • Simple
  • Object-Oriented
  • Portable
  • Platform independent
  • Secured
  • Robust
  • Architecture neutral
  • Interpreted
  • High Performance
  • Multithreaded
  • Distributed
  • Dynamic

Java Terminology

Java Virtual Machine (JVM) – 

  • Compilation of program is done by javac compiler, 
  • javac is the primary java compiler included in java development kit (JDK). 
  • It takes java program as input and generates java bytecode as output

Bytecode 

  • javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. 
  • The bytecode is saved in a .class file by compiler

Java Development Kit(JDK)

  • This is a complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
  • In order to create, compile and run Java program you would need JDK installed on your computer

Java Runtime Environment(JRE)

  • JRE is a part of JDK which means that JDK includes JRE. 
  • When you have JRE installed on your system, you can run a java program however you won’t be able to compile it. 
  • JRE includes JVM, browser plugins and applets support. 
  • When you only need to run a java program on your computer, you would only need JRE.

Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java

  • 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).
  • Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code. 
  • This makes it easier for the compiler as it has to generate byte code for JVM rather than different machine code for each type of machine. 
  • JVM executes the byte code generated by the compiler and produces output. JVM is the one that makes java platform independent
  • Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems

JVM Vs JRE Vs JDK

  • JRE: JRE is the environment within which the java virtual machine runs. 
  • JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger.
  • Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
  • JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.

JRE

  • JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.

JDK

Identifiers

A name in java program is called identifier which can be used for identification purpose. It can be method name or variable name, class name or label name.

Rules for defining java identifiers:-

  • The only allowed characters in java identifiers are a-z, A-Z,0-9,$,_ .If we are using any other character we will get compile time error. 

Eg:- total_number =valid
total#number =invalid

  • Identifiers can’t start with digit eg:- total123 =valid but 123total=invalid

  • Java identifiers are case-sensitive  ofcouse java language is treated as case sensitive programming language

Eg:-

  • There is no length limit for java identifiers but it is not recommended taking too lengthy identifiers.

  • We can’t use reserved words as identifiers eg:- 

Int x=10 =valid
Int if =20 =invalid as if is as reserved word

  • All predefined java class name and interface names we can use as identifiers.

Eg:-

Even though it is valid but it is not good programming practice because it reduces readability and creates confusion.

Reserved words

  • In java some words are reserved  to represent some or functionality such type of words are called reserved words.
  • There are 53 reserved words available in java

  • All 53 reserved words contains only lowercase alphabets
  • In java we have only new keywords and there is no delete keyword because destruction of useless objects is responsibility of garbage collector

Simple Java Program:

public class FirstJavaProgram {
 public static void main(String[] args){
    System.out.println("This is my first program in java");
  }//End of main
}//End of FirstJavaProgram Class
Output: This is my first program in java

public class FirstJavaProgram { – Every java application must have at least one class definition that consists of class keyword followed by class name

public static void main(String[] args)  {

public: This makes the main method public that means that we can call the method from outside the class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args): Used for command line arguments that are passed as strings. We will cover that in a separate post.

Variables in Java

  • A variable is a name which is associated with a value that can be changed. 
  • For example when I write int i=10; here variable name is i which is associated with value 10

How to Declare a variable in Java

To declare a variable follow this syntax:
data_type variable_name = value;

Variables naming convention in java

  • Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it.
  • Variable name can begin with special characters such as $ and _
  • As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter).
  • Variable names are case sensitive in Java.

Types of Variables in Java

There are three types of variables in Java.

1) Local variable 2) Static (or class) variable 3) Instance variable

Local Variable

  • These variables are declared inside the method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.
  • In this example, I have declared the instance variable with the same name as local variable, this is to demonstrate the scope of local variables.

Static (or class) Variable

  • Static variables are also known as class variables because they are associated with the class and common for all the instances of class. 
  • For example, If I create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when you access it through other objects.

Instance variable

  • Each instance(objects) of class has its own copy of instance variable. 
  • Unlike static variable, instance variables have their own separate copy of instance variable.
  • We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. 
  • This shows that they have their own copy of instance variable.

  String myInstanceVar="instance variable";
public static void main(String args[]){
  InstanceVarExample obj = new InstanceVarExample();
  InstanceVarExample obj2 = new InstanceVarExample();
  System.out.println(obj.myInstanceVar);
  System.out.println(obj2.myInstanceVar);
  obj2.myInstanceVar = "Changed Text";
  System.out.println(obj.myInstanceVar); //instance variable

Data Types in Java

  • Data type defines the values that a variable can take, for example if a variable has int data type, it can only take integer values. In java we have two categories of data type: 1) Primitive data types 2) Non-primitive data types
  • Java is a statically typed language. A language is statically typed, if the data type of a variable is known at compile time. 

Java has two categories of data:

  • Primitive Data Type: such as boolean, char, int, short, byte, long, float and double
  • Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Primitive data types

In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double

  • byte, short, int and long data types are used for storing whole numbers.
  • float and double are used for fractional numbers.
  • char is used for storing characters(letters).
  • boolean data type is used for variables that holds either true or false.

Literals in Java

A literal is a fixed value that we assign to a variable in a Program.

int num=10;
Here value 10 is a Integer literal.
char ch = 'A';
Here A is a char literal

Integer Literal

Integer literals are assigned to the variables of data type byte, short, int and long.

byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;

Float Literals

Used for data type float and double.

double num1 = 22.4;
float num2 = 22.4f;

Note: Always suffix float value with the “f” else compiler will consider it as double.

Char and String Literal

Used for char and String type.

char ch = 'Z';
String str = "BeginnersBook";

Operators in Java

An operator is a character that represents an action, for example + is an arithmetic operator that represents addition.

Types of Operator in Java

  •  Basic Arithmetic Operators
  • Assignment Operators
  • Auto-increment and Auto-decrement Operators
  • Logical Operators
  • Comparison (relational) operators
  • Bitwise Operators
  • Ternary Operator

Other operators

Besides these operators, there are other additional operators in Java.

Java instanceof Operator

The instanceof operator checks whether an object is an instanceof a particular class. For example,

class Main {
  public static void main(String[] args) {

    String str = "Programiz";
    boolean result;

    // checks if str is an instance of
    // the String class
    result = str instanceof String;
    System.out.println("Is str an object of String? " + result);
  }
}

Output

Is str an object of String? true

Here, str is an instance of the String class. Hence, the instanceof operator returns true. To learn more, visit Java instanceof.


Java Ternary Operator

The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,

variable = Expression ? expression1 : expression2

Here's how it works.

  • If the Expression is trueexpression1 is assigned to the variable.
  • If the Expression is falseexpression2 is assigned to the variable.

Let’s see an example of a ternary operator.

class Java {
  public static void main(String[] args) {

    int februaryDays = 29;
    String result;

    // ternary operator
    result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
    System.out.println(result);
  }
}

Output

Leap year

Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.

Syntax:

variable num1 = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to the variable num1 else the second value is assigned to the num1.

Example of Ternary Operator

public class TernaryOperatorDemo {
   public static void main(String args[]) {
        int num1, num2;
        num1 = 25;
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}
Output:
num2: 200
num2: 100

Static Block in Java

  • In Java, the static keyword is used for the management of memory mainly. 
  • the static keyword can be used with Variables, Methods, Block and nested class.
  • A static block in a program is a set of statements which are executed by the JVM (Java Virtual Machine) before the main method. 
  • At the time of class loading, if we want to perform any task we can define that task inside the static block, this task will be executed at the time of class loading. 
  • In a class, any number of a static block can be defined, and this static blocks will be executed from top to bottom.

static block Image

Example of a static block

Static block executes before the main method while executing program. Statements written inside the static block will execute first. However both are static.

class StaticDemo1
{
	static
	{
		System.out.println("Welcome to studytonight.com");
		System.out.println("This is static block");
	}
	public static void main(String as[])
	{
		System.out.println("This is main() method");
	}
}

 Initializer Block in Java

  • In Java, the initializer Block is used to initialize instance data members. 
  • The initializer block is executed whenever an object is created. 
  • The Initializer block is copied into Java compiler and then to every constructor. 
  • The initialization block is executed before the code in the constructor.

Example using static and initializer block

We can have both static and initializer blocks in a Java program. But static block will execute first even before initializer block. 

public class one extends two {
    static {
System.out.println("inside satic block");
}
one() {
System.out.println("inside constructor of child");
}
{
System.out.println("inside initialization block");
}
    public static void main(String[] args) {
        new one();
        new one();
System.out.println("inside main");
}
}
class two{
static {
System.out.println("inside parent Static block");
}
{
System.out.println("inside parent initialisation block");
}
two(){
System.out.println("inside parent constructor");
}
}

Type Casting in Java

Casting is a process of changing one type value to another type. In Java, we can cast one type of value to another type. It is known as type casting.

Example :

int x = 10;
byte y = (byte)x;

In Java, type casting is classified into two types,

  • Widening Casting(Implicit)

widening-type-conversion

  • Narrowing Casting(Explicitly done)

narrowing-type-conversion

Example for Conversion of int and double into a byte

Here, we are converting int and double type to byte type by using explicit type casting.

class Demo2
{
    public static void main(String args[])  {
      byte b;  
      int i = 355;  
      double d = 423.150; 
      b = (byte) i; 
      System.out.println("Conversion of int to byte: i = " + i + " b = " + b);  
      System.out.println("*************************************************"); 
      b = (byte) d;   
      System.out.println("Conversion of double to byte: d = " + d + " b= " + b);
}
}     

BASIC Programmes