Introduction to Java programming
Java terminology
Before we start learning Java, lets get familiar with common java terms.
Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets 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 bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase.
So, now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.
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 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.
Main Features of JAVA
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 bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, 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 bytecode is same across all operating systems. That is why we call java as platform independent language.
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.
4 main concepts of Object Oriented programming are:
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.
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.
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.
Java is distributed
Using java programming language we can create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for 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.
Multithreading
Java supports Multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU.
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.
Working strategy:
Source Code --> complier --> Byte code --> JVM <-->Interpreter for Windows/Mac/Linux
.java file -->javac-->.class file
javac compiler 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
JVM executes the byte code generated by compiler and produce 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
So to summarize everything: The Java Virtual machine (JVM) is the virtual machine that runs on actual machine (your computer) and executes Java byte code. 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.
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.
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.
Keypoints:
JRE = JVM + Jar files(Lib and complied class files)
JDK = JRE + Complier, debugger and other development tools
First Java Program
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.
Variables
·
A variable is a container which holds the value
while the Java program is executed.
·
A variable is assigned with a data type.
·
Variable is a name of memory location.
·
There are three types of variables in java:
local, instance and static.
·
There are two types of data types in Java:
primitive and non-primitive.
·
Variable is name of reserved area allocated in
memory. In other words, it is a name of memory location. It is a combination of
"vary + able" that means its value can be changed.
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.
Eg:
char ch = 'A';
int number = 100;
Variables naming convention in java
1) Variables naming cannot contain white spaces, for
example: int num ber = 100; is invalid because the variable name has space in
it.
2) Variable name can begin with special characters such as $
and _
3) 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;
4) Variable names are case sensitive in Java.
5) Reserved words (like Java keywords, such as int or
boolean) cannot be used as names
Types:
1) Local Variable
A variable declared inside the body of the method is called
local variable. You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static"
keyword.
2) Instance Variable
A variable declared inside the class but outside the body of
the method, is called instance variable. It is not declared as static.
It is called instance variable because its value is instance
specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static
variable. It cannot be local. You can create a single copy of static variable
and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.
Eg:
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Data Types in Java
Data types specify the different sizes and values that can
be stored in the variable. There are two types of data types in Java:
Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Data Type &
size |
Default Value
|
Description |
byte 1 byte |
0 |
Stores whole
numbers from -128 to 127 |
short 2 bytes |
0 |
Stores whole
numbers from -32,768 to 32,767 |
int 4 bytes |
0 |
Stores whole
numbers from -2,147,483,648 to 2,147,483,647 |
long 8 bytes |
0 |
Stores whole
numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float 4 bytes |
0.0f |
Stores
fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double 8 bytes |
0.0d |
Stores
fractional numbers. Sufficient for storing 15 decimal digits |
Boolean 1 bit |
False |
Stores true
or false values |
char 2 bytes |
'\u0000’ |
Stores a
single character/letter or ASCII values |
Point to note:
why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code
system. The \u0000 is the lowest range of Unicode system.
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative
(such as 123 or -456), without decimals. Valid types are byte, short, int and
long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional
part, containing one or more decimals. There are two types: float and double.
Non-Primitive Data Types
Non-primitive data types are called reference types because
they refer to objects.
The main difference between primitive and non-primitive data
types are:
Primitive types are predefined (already defined) in Java.
Non-primitive types are created by the programmer and is not defined by Java
(except for String).
Non-primitive types can be used to call methods to perform
certain operations, while primitive types cannot.
A primitive type has always a value, while non-primitive
types can be null.
A primitive type starts with a lowercase letter, while
non-primitive types starts with an uppercase letter.
The size of a primitive type depends on the data type, while
non-primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes,
Interface, etc
Type Casting
Type casting is when you assign a value of one primitive
data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type
to a larger type size
byte -> short -> char -> int -> long -> float
-> double
Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char ->
short -> byte
public class Main {
public static void
main(String[] args) {
int myInt = 9;
double myDouble =
myInt; // Automatic casting: int to double
System.out.println(myInt); //
Outputs 9
System.out.println(myDouble); //
Outputs 9.0
}
}
public class Main {
public static void
main(String[] args) {
double myDouble =
9.78;
int myInt = (int)
myDouble; // Manual casting: double to int
System.out.println(myDouble); //
Outputs 9.78
System.out.println(myInt); //
Outputs 9
}
}
Operators
Operator Type |
Category |
Precedence |
Unary |
postfix |
expr++ expr-- |
prefix |
++expr --expr +expr -expr ~
! |
|
Arithmetic |
multiplicative |
* / % |
additive |
+ - |
|
Shift |
shift |
<< >> >>> |
Relational |
comparison |
< > <= >= instanceof |
equality |
== != |
|
Bitwise |
bitwise AND |
& |
bitwise exclusive OR |
^ |
|
bitwise inclusive OR |
| |
|
Logical |
logical AND |
&& |
logical OR |
|| |
|
Ternary |
ternary |
? : |
Assignment |
assignment |
= += -= *= /= %= &= ^= |= <<= >>= >>>= |
class Unary OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value
which starts from 0)
System.out.println(~b);//9 (positive of total minus,
positive starts from 0)
System.out.println(!c);//false (opposite of boolean
value)
System.out.println(!d);//true
Arithmetic
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
Shift Operator
The Java left shift operator << is used to shift all
of the bits in a value to the left side of a specified number of times.
class LeftShiftOperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
The Java right shift operator >> is used to move left
operands value to right by the number of bits specified by the right operand.
class RightShiftOperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
//For positive number, >> and >>> works
same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative
number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
5
5
-5
1073741819
Logical && vs Bitwise &
The logical && operator doesn't check second
condition if first condition is false. It checks second condition only if first
one is true.
The bitwise & operator always checks both conditions
whether first condition is true or false.
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false
&& true = false
System.out.println(a);//10 because second condition is not
checked
System.out.println(a<b&a++<c);//false &&
true = false
System.out.println(a);//11 because second condition is
checked
Logical || and Bitwise |
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true =
true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true =
true
System.out.println(a);//10 because second condition is not
checked
System.out.println(a>b|a++<c);//true | true =
true
System.out.println(a);//11 because second condition is
checked
Java Ternary Operator
Java Ternary operator is used as one liner replacement for
if-then-else statement and used a lot in Java programming. it is the only
conditional operator which takes three operands.
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
Java Assignment Operator
Java assignment operator is one of the most common operator.
It is used to assign the value on its right to the operand on its left.
Example
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
13
9
18
9
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
so,
a=(short)(a+b);//20 which is int now converted to short