Introduction to Java

 Introduction to Java


JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James Gosling and Patrick Naught on. It is a simple programming language. Writing, compiling and debugging a program is easy in java. It helps to create modular programs and reusable code.

Java terminology

Before we start learning Java, let’s get familiar with common java terms.

Java Virtual Machine (JVM)

This is generally referred as JVM. Before, we discuss about JVM let’s see the phases of program execution. Phases are as follows: we write the program,  then we compile the program and at last we run the program. 
1) Writing of the program is of course done by java programmer like you  and me. 
2) 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 byte code as output. 
3) In third phase, JVM executes the byte code generated by compiler. This  is called program run phase.

bytecode

As discussed above, 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)

While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name suggests this is 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 Development Kit(JDK)

While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name suggests this is 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 plugging and applets support. When you only need to run a java program on your computer, you would only need JRE.

Importance and Features of Java–

    Main Features of JAVA

1. Java is a platform independent language-


  •  Compiler (javac) converts source code (.java file) to the byte code (.class file). As mentioned above, JVM executes the byte code produced by compiler. This byte code can run on any platform such as Windows, Linux,and Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-versa?
  •  Each operating system has different JVM; however the output they produce after execution of byte code is same across all operating systems. That is why we call java as platform independent language.

2. Java is an Object Oriented language.

  •  Object oriented programming is a way of organizing programs as collection of objects, each of which represents an instance of a class.
  • Object-oriented means we organize our software as a combination of
  • different types of objects that incorporates both data and behavior.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object- An entity that has state and behavior is known as an object e.g. chairs, bike, marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.


Class- A class is a group of objects which have common properties. It is a 
template or blueprint from which objects are created. It is a logical entity. It can't  be physical.

A class in Java can contain:

  •   Fields
  •   Methods
  •   Constructors
  •   Blocks
  •   Nested class and interface

Inheritance- Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

Polymorphism- Polymorphism in Java is a concept by which we can perform  a single action in different ways. Polymorphism is derived from 2 Greek words:  poly and morphs. The word "poly" means many and "morphs" means forms. So  polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.


Abstraction- Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.

Encapsulation- Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.

      3. Simple

  •  Java is considered as one of simple language because it does not have complex features like Operator overloading, multiple inheritance, pointers and Explicit memory allocation.
       
      4. Robust Language

  • Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.
 
      5. Secure
 
  • We don’t have pointers and we cannot access out of bound arrays (you get ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
        
       6. Java is distributed 

  • Using java programming language we can create distributed applications. RMI (Remote Method Invocation) and EJB (Enterprise Java Beans) are usedfor creating distributed applications in java. In simple words: The 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.
      
        7. Multithreading

  • Java supports multithreading. Multithreading is a Java feature that allows  concurrent execution of two or more parts of a program for maximum  utilization of CPU.
       
        8. Portable

  • As discussed above, java code that is written on one machine can run on another machine. The platform independent byte code can be carried to any platform for execution that makes java code portable.


Keywords–

Keywords are words that have already been defined for Java compiler. They have special meaning for the compiler. Java Keywords must be in your information because you cannot use them as a variable, class or a method name.

Some Examples of keywords:


abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve abstraction. For more, refer abstract keyword in java.

 enum : It is used to define enum in Java

 instanceof: It is used to know whether the object is an instance of the
specified type (class or subclass or interface).

private: It is an access modifier. Anything declared private cannot be seen outside of its class.

protected : If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.

public: Anything declared public can be accessed from anywhere.

Constants–


Constants in Java. A constant is a variable which cannot have its value 
changed after declaration. It uses the 'final' keyword.
Syntax-
modifier final dataType variableName = value; //global constant
modifier static final dataType variableName = value; //constant within a class

Variables and Data type–

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, int is a data type that represents that this variable can hold integer values. We will cover the data types in the next tutorial. In this tutorial, we will discuss about variables.

How to Declare a variable in Java
To declare a variable follow this syntax:

data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then later assign the value to it.

For example: Here num is a variable and int is a data type. We will discuss the data type in next tutorial so do not worry too much about it, just understand that int data type allows this num variable to hold integer values. You can read data types here but I would recommend you to finish reading this guide before proceeding to the next one.

int num;
Similarly we can assign the values to the variables while declaring them, like this:

char ch = 'A';
int number = 100;
or we can do it like this:

char ch;
int number;
...
ch = 'A';
number = 100;

Types of Variables in Java 

There are three types of variables in Java. 1) Local variable 2) Static (or class) variable 3) Instance variable.

Static (or class) Variable 

Static variables are also known as class variable 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.

Local Variable

These variables are declared inside 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.

Data types

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 – Arrays and Strings are 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. This means that you must specify the type of the variable (Declare the variable) before you can use it.

1) Primitive data types

In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double. Java developers included these data types to maintain the portability of java as the size of these primitive data types do not change from one operating system to another.

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.

2) No primitive data types 
Non-primitive, or reference data types, are the more sophisticated members of  the data type family. They don't store the value, but store a reference to that value. Instead of partNumber 4030023, Java keeps the reference, also called  address, to that value, not the value itself.

Operators and expressions–

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

Types of Operator in Java

1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators 

Basic arithmetic operators are: +, -, *, /, % 
+ is for addition. 

is for subtraction. 

* is for multiplication. 

/ is for division. 

% is for modulo. 

Note: Modulo operator returns remainder, for example 10 % 5 would return 0

Example of Arithmetic Operators


public class ArithmeticOperatorDemo {
 public static void main(String args[]) {
 int num1 = 100;
 int num2 = 20;
 System.out.println("num1 + num2: " + (num1 + num2) );
 System.out.println("num1 - num2: " + (num1 - num2) );
 System.out.println("num1 * num2: " + (num1 * num2) );
 System.out.println("num1 / num2: " + (num1 / num2) );
 System.out.println("num1 % num2: " + (num1 % num2) );
 }
}
Output:

num1 + num2: 120
num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0

2) Assignment Operators 

Assignments operators in java are: =, +=, -=, *=, /=, %= 
num2 = num1 would assign value of variable num1 to the variable. 

num2+=num1 is equal to num2 = num2+num1 

num2-=num1 is equal to num2 = num2-num1 

num2*=num1 is equal to num2 = num2*num1 

num2/=num1 is equal to num2 = num2/num1 

num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators

 public class AssignmentOperatorDemo {
 public static void main(String args[]) {
 int num1 = 10;
 int num2 = 20;
 num2 = num1;
 System.out.println("= Output: "+num2);
 num2 += num1;
 System.out.println("+= Output: "+num2);

 num2 -= num1;
 System.out.println("-= Output: "+num2);

 num2 *= num1;
 System.out.println("*= Output: "+num2);
 num2 /= num1;
 System.out.println("/= Output: "+num2);
 num2 %= num1;
 System.out.println("%= Output: "+num2);
 }
}

Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

3) Auto-increment and Auto-decrement Operators
++ and —
num++ is equivalent to num=num+1;
num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

public class AutoOperatorDemo {
public static void main(String args[]){
 int num1=100;
 int num2=200;
 num1++;
 num2--;
 System.out.println("num1++ is: "+num1);
 System.out.println("num2-- is: "+num2);
 }
}

Output:
num1++ is: 101
num2-- is: 199

4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional statements and loops for evaluating a condition.

Logical operators in java are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false and it would return false if b1 is true.

Example of Logical Operators

public class LogicalOperatorDemo {
 public static void main(String args[]) {
 boolean b1 = true;
 boolean b2 = false;
System.out.println("b1 && b2: " + (b1&&b2));
 System.out.println("b1 || b2: " + (b1||b2));
 System.out.println("!(b1 && b2): " + !(b1&&b2));
 }
}

Output:

b1 && b2: false
b1 || b2: true
!(b1 && b2): true

5) Comparison(Relational) operators

We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

Example of Relational operators

public class RelationalOperatorDemo {
 public static void main(String args[]) {
 int num1 = 10;
 int num2 = 50;
 if (num1==num2) {
 System.out.println("num1 and num2 are equal");
 }
 else{
System.out.println("num1 and num2 are not equal");
 }
 if( num1 != num2 ){
 System.out.println("num1 and num2 are not equal");
 }
 else{
 System.out.println("num1 and num2 are equal");
 }
 if( num1 > num2 ){
 System.out.println("num1 is greater than num2");
 }
 else{
 System.out.println("num1 is not greater than num2");
 }
 if( num1 >= num2 ){
 System.out.println("num1 is greater than or equal to num2");
 }
 else{
 System.out.println("num1 is less than num2");
 }
 if( num1 < num2 ){
 System.out.println("num1 is less than num2");
 }
 else{
 System.out.println("num1 is not less than num2");
 }
 if( num1 <= num2){
 System.out.println("num1 is less than or equal to num2");
 }
 else{
 System.out.println("num1 is greater than num2");
 }
}
}

Output:
num1 and num2 are not equal
num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2


6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/ 
num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.
num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the binary form of num1 and num2 only second last bits are  matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if  either bit is 1, else it returns 0. In our case it would return 31 which is 00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if  they are not equal, else it returns 0. In our example it would return  29 which is  equivalent to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0.  In our example it would return -12 which is signed 8 bit equivalent to 11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far left  bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is  equivalent to 00101100

num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010

Example of Bitwise Operators


public class BitwiseOperatorDemo { 
 public static void main(String args[]) { 
 int num1 = 11; /* 11 = 00001011 */
 int num2 = 22; /* 22 = 00010110 */
 int result = 0; 
 result = num1 & num2; 
 System.out.println("num1 & num2: "+result); 
 result = num1 | num2; 
 System.out.println("num1 | num2: "+result); 
 
 result = num1 ^ num2; 
 System.out.println("num1 ^ num2: "+result); 
 
 result = ~num1; 
 System.out.println("~num1: "+result); 
 
 result = num1 << 2; 
 System.out.println("num1 << 2: "+result); result = num1 >> 2; 
 System.out.println("num1 >> 2: "+result); 
 } 
}

Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

7) 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; 
 /* num1 is not equal to 10 that's why 
 * the second value after colon is assigned 
 * to the variable num2 
 */
 num2 = (num1 == 10) ? 100: 200; 
System.out.println( "num2: "+num2); 
/* num1 is equal to 25 that's why 
 * the first value is assigned 
 * to the variable num2 
 */
 num2 = (num1 == 25) ? 100: 200; 
System.out.println( "num2: "+num2); 
 } 
}

Output:

num2: 200
num2: 100

Operator Precedence in Java

This determines which operator needs to be evaluated first if an expression has more than one operator. Operator with higher precedence at the top and lower precedence at the bottom. Unary Operators.
++ – – ! ~

Multiplicative 
* / %

Additive 
+ –

Shift 
<< >> >>>

Relational 
> >= < <=

Equality 
== !=

Bitwise AND 
&

Bitwise XOR 
^

Bitwise OR 
|

Logical AND 
&&

Logical OR 
||

Ternary
?:

Assignment
= += -= *= /= %= > >= < <= &= ^= |=


Expressions

 1- Expressions are essential building blocks of any Java program, usually
created to produce a new value, although sometimes an expression simply assigns a value to a variable. Expressions are built using values, variables, operators and method calls.

2- An expression is a statement that can convey a value. Some of the most common expressions are mathematical, such as in the following source code example:

int x = 3; 

int y = x; 

int z = x * y;

All three of these statements can be considered expressions—they convey values  that can be assigned to variables. The first assigns the literal 3 to the variable x. 
The second assigns the value of the variable x to the variable y. The multiplication  operator * is used to multiply the x and y integers, and the expression produces the result of the multiplication. This result is stored in the z integer.

Decision making–

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming languages −

Java programming language provides following types of decision making
statements. Click the following links to check their detail.


?: Operator

We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. To determine the value of the whole expression, initially exp1 is evaluated.
  • If the value of exp1 is true, then the value of Exp2 will be the value of thewhole expression.
  • If the value of exp1 is false, then Exp3 is evaluated and its value becomesthe value of the entire expression.
Loops-

Programming languages provide various control structures that allow for more 
complicated execution paths. 

A loop statement allows us to execute a statement or group of statements 
multiple times and following is the general form of a loop statement in most of the programming languages −

Java programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

Loop Control Statements 

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. 

Java supports the following control statements. Click the following links to check their detail.

Labeled loop-

According to nested loop, if we put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. What if we need to jump out from the outer loop using break statement given inside inner loop? The answer is, we should define lable along with colon(:) sign before loop.

Syntax of Labelled loop

               Introducing Classes

Object and methods:

Defining a class-

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −

  • Polymorphism
  •  Inheritance
  •  Encapsulation
  •  Abstraction
  •  Classes
  •  Objects
  •  Instance
  •  Method
  • Message Parsing
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.

Adding variables and methods-

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.

Creating Method

Considering the following example to explain the syntax of a method −
Syntax

public static int methodName(int a, int b) {
// body
}

Here,
  • public static − modifier 
  • int − return type 
  • methodName − name of the method 
  • a, b − formal parameters 
  • int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown in the following syntax −

Syntax
modifier returnType nameOfMethod (Parameter List) {
 // method body
}
The syntax shown above includes −

1- modifier − It defines the access type of the method and it is opÆŸonal to
use.

2-  returnType − Method may return a value.

3- nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

4- Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
5- method body − The method body defines what the method does with the statements.

Creating objects-

In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java


1. //Java Program to demonstrate having the main method in 

2. //another class 

3. //Creating Student class. 

4. class Student{ 

5. int id; 

6. String name; 

7. } 

8. //Creating another class TestStudent1 which contains the main method 

9. class TestStudent1{ 

10. public static void main(String args[]){ 

11. Student s1=new Student(); 

12. System.out.println(s1.id); 

13. System.out.println(s1.name); 

14. } 

15.} 

Output: 


null

Constructors-

Constructor is a block of code that initializes the newly created object. A
constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.


Constructor has same name as the class and looks like this in a java code.

public class MyClass{ 
 //This is the constructor
 MyClass(){ 
 } 
 .. 
}

A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the  instance variable nameof the object. As you can see that the output 
is BeginnersBook.com which is what we have passed to the name during 
initialization in constructor. This shows that when we created the object obj the constructor got invoked. In this example we have used this keyword, which refers to the current object, object obj in this example. We will cover this keyword in  detail in the next tutorial.

public class Hello { 
 String name; 
 //Constructor
 Hello(){ 
 this.name = "BeginnersBook.com"; 
 } 
 public static void main(String[] args) { 
 Hello obj = new Hello(); 
 System.out.println(obj.name); 
 } 
}
Output:
   
BeginnersBook.com

Class Inheritance-

A class that is derived from another class is called subclass and inherits all fields and methods of its superclass. In Java, only single inheritance is allowed and thus, every class can have at most one direct superclass. A class can be derived from another classthat is derived from another class and so on.

Post a Comment

Previous Post Next Post