1 - Basics of Java
History of JAVA.
Java was initially developed in 1991 named as “oak” but was renamed “Java” in 1995.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
The primary motivation was the need for a platform-independent language that could be used
to create software to be embedded in various consumer electronic devices.
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
platform (Java 1.0 [J2SE]).
It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
Java 2, new versions had multiple configurations built for different types of platforms. J2EE
included technologies and APIs for enterprise applications typically run in server
environments, while J2ME featured APIs optimized for mobile applications.
The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed new
J2 versions as Java EE, Java ME, and Java SE, respectively.
On 13 November 2006, Sun released much of Java as free and open-source software (FOSS),
under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
What is Java?
Java is a programming language that:
Is exclusively object oriented
Has full GUI support
Has full network support
Is platform independent
Executes stand-alone or “on-demand” in web browser as applets
1
JDK, JRE, Byte code & JVM.
Compiler
([Link]) Java
JVM
Java Packages
Application
(math,
Launcher
([Link]), Runtime
AppletViewer, Libraries
etc..)
Development tools JRE
JDK
Java Development Kit (JDK)
o JDK contains tools needed ,
To develop the Java programs and
JRE to run the programs.
o The tools include compiler ([Link]), Java application launcher ([Link]),
Appletviewer, etc…
o Java application launcher ([Link]),
Opens a JRE, loads the class, and invokes its main method.
Java Runtime Environment (JRE)
o The Java Runtime Environment (JRE) is required to run java applications.
o It combines the Java Virtual Machine (JVM), platform core classes and supporting
libraries.
o JRE is part of the Java Development Kit (JDK), but can be downloaded separately.
o It does not contain any development tools such as compiler, debugger, etc.
Byte code
o Byte code is intermediate representation of java source code.
o It produce by java compiler by compiling java source code.
o Extension for java class file or byte code is ‘.class’.
o It is platform independent.
2
JVM (Java Virtual Machine)
o JVM is virtual because It provides a machine interface that does not depend on the
operating system and machine hardware architecture.
o JVM interprets the byte code into the machine code.
o JVM itself is platform dependent, but Java is Not.
Java Code (.java)
JAVAC Compiler
Byte Code (.class)
Windows Linux Mac
JVM JVM JVM
Explain features of JAVA.
Features of java are discussed below:
• The Features of Java programming are as below
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-natural
8. Interpreted
9. High performance
10. Distributed
11. Dynamic
3
1 - Basics of Java
Simple
o It’s simple because it contains many features of other languages like C and C++
o It also removed complexities like pointers, Storage classes, goto statement and multiple
Inheritance.
Secure
o Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
1. No explicit pointer
2. Java Programs run inside virtual machine sandbox
3. Bytecode Verifier
Portable
o Java is portable because it facilitates you to carry the java bytecode to any platform.
Object oriented
o Java is Object-oriented programming language. Everything in Java is an object.
Robust
o Robust simply means strong. Java is robust because:
1. It uses strong memory management.
2. There are lack of pointers that avoids security problem.
3. There is automatic garbage collection in java.
4. There is exception handling and type checking mechanism in java. All these points makes
java robust
Multithreaded
o A thread is like a separate program, executing concurrently.
o We can write Java programs that deal with many tasks at once by defining multiple threads.
o The main advantage of multi-threading is that it doesn't occupy memory for each thread.
o It shares a common memory area. Threads are important for multi-media, Web applications
etc…
Architecture-neutral
o Java is architecture neutral because there is no implementation dependent features e.g. size
of primitive types is fixed.
o Example : in c int occupy 2 byte for 32 bit OS and 4 bytes for 64 bit OS whereas in JAVA it
occupy 4 byte for int both in 32 bit and 64 bit OS.
Interpreted
o Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode.
o This code can be executed on any system that implements the Java Virtual Machine.
High-Performance
o Most previous attempts at cross-platform solutions have done so at the expense of
performance.
o As explained earlier, the Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a just-in-time
compiler.
Dynamic
o Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time.
o This makes it possible to dynamically link code in a safe and expedient manner.
4
1 - Basics of Java
Distributed
o Java is distributed because it facilitates us to create distributed applications in java.
o RMI and EJB are used for creating distributed applications.
o We may access files by calling the methods from any machine on the internet.
Platform Independent
o Java is a platform independent programming language, because when you install JDK in the
system then JVM is also installed automatically on the system.
o For every operating system separate JVM is available which is capable to read the .class file
or byte code.
o When we compile Java code then .class file is generated by java compiler (javac) these codes
are readable by the JVM and every operating system have its own JVM so JVM is platform
dependent but due to JVM java is platform independent.
Explain Operators in JAVA
Sr. Operator Examples
1 Arithmetic Operators +, -, *, /, %
2 Relational Operators <, <=, >, >=, ==, !=
3 Logical Operators &&, ||, !
4 Assignment Operators =, +=, -=, *=, /=
5 Increment and Decrement Operators ++, --
6 Conditional Operator ?:
7 Bitwise Operators &, |, ^, <<, >>
Arithmetic Operator
An arithmetic operator performs basic mathematical calculations such as addition,
subtraction, multiplication, division etc. on numerical values (constants and variables).
Increment / Decrement Operators
o Increment and decrement operators are unary operators that add or subtract one,
to or from their operand.
o the increment operator ++ increases the value of a variable by 1, e.g. a++ means
a=a+1
o the decrement operator -- decreases the value of a variable by 1. e.g. a–– means
a=a–1
o If ++ operator is used as a prefix (++a) then the value of a is incremented by 1 first
then it returns the value.
o If ++ operator is used as a postfix (a++) then the value of a is returned first then it
increments value of a by 1.
5
1 - Basics of Java
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give
30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give
-10
* Multiplication - Multiplies values on either side of the operator A * B will give
200
/ Division - Divides left hand operand by right hand operand B / A will give
2
% Modulus - Divides left hand operand by right hand operand and returns B % A will
remainder give 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
Arithmetic Operators in JAVA, consider A as 10 & B as 20
Expression Evaluation (Let’s say a=10, c=15)
b = a++ Value of b would be 10 and value of a would be 11.
b = ++a Value of b & a would be 11.
b = a-- Value of b would be 10 and value of a would be 9.
b = --a Value of b & a would be 9.
Increment / Decrement Operators
Relational Operators
A relational operators are used to compare two values.
They check the relationship between two operands, if the relation is true, it returns 1; if the
relation is false, it returns value 0.
Relational expressions are used in decision statements such as if, for, while, etc
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then (A == B) is not
condition becomes true. true.
!= Checks if the values of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true. true.
Relational Operators in JAVA, consider A as 10 & B as 20
6
1 - Basics of Java
Bitwise Operators
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is 0000
exists in both operands. 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is 0011
operand. 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
operand but not both. 0001
~ Binary Ones Complement Operator is unary and (~A ) will give -61 which is 1100
has the effect of 'flipping' bits. 0011 in 2's complement form
due to a signed binary number.
<< Binary Left Shift Operator. The left operands value A << 2 will give 240 which is 1111
is moved left by the number of bits specified by the 0000
right operand.
>> Binary Right Shift Operator. The left operands value A >> 2 will give 15 which is 1111
is moved right by the number of bits specified by
the right operand.
>>> Shift right zero fill operator. The left operands value A >>>2 will give 15 which is 0000
is moved right by the number of bits specified by 1111
the right operand and shifted values are filled up
with zeros.
Bitwise Operators in JAVA, consider A as 60 & B as 13
Logical Operators
Logical operators are decision making operators.
They are used to combine two expressions and make decisions.
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results false or true.
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then (A && B) is
the condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands are non-zero, (A || B) is
then the condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B) is
operand. If a condition is true then Logical NOT operator will make false. true.
Logical Operators in JAVA, consider A as true & B as false
7
1 - Basics of Java
Assignment Operators
Assignment operators are used to assign a new value to the variable.
The left side operand of the assignment operator is a variable and right side operand of the
assignment operator is a value or a result of an expression.
Meaning of = in Maths and Programming is different.
o Value of LHS & RHS is always same in Math.
o In programming, value of RHS is assigned to the LHS
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C
left operand and assign the result to left operand =C+A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C
operand from the left operand and assign the result to left =C-A
operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C
operand with the left operand and assign the result to left =C*A
operand
/= Divide AND assignment operator, It divides left operand with C /= A is equivalent to C
the right operand and assign the result to left operand =C/A
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to
two operands and assign the result to left operand C=C%A
<<= Left shift AND assignment operator C <<= 2 is same as C = C
<< 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C
>> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C
&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^
2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C |
2
Assignment Operators in JAVA
8
1 - Basics of Java
Operator Precedence & Associativity
How does java evaluate 1 + 10 * 9 ?
(1 + 10 ) * 9 = 99 OR 1 + (10 * 9) = 91
To get the correct answer for the given problem Java came up with Operator precedence. (
multiplication have higher precedence than addition so correct answer will be 91 in this case)
For Operator, associativity means that when the same operator appears in a row, then to
which direction the expression will be evaluated.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions in absence of brackets.
Operator precedence determines which operation is performed first in an expression with
more than one operators with different precedence.
a=10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30 so answer is 610.
Operators Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right (L to R) or Right to Left (R to L).
E.g. a=100 / 10 * 10
If Left to Right means (100 / 10) * 10 then answer is 100
If Right to Left means 100 / (10 * 10) then answer is 1
Division (/) & Multiplication (*) are Left to Right associative so the answer is 100.
9
1 - Basics of Java
Explain short circuit operators.
Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as
shortcircuit logical operators.
The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator
results in false when A is false, no matter what B is. If you use the || and && forms, rather than
the | and & forms of these operators, Java will not bother to evaluate the right-hand operand
when the outcome of the expression can be determined by the left operand alone.
This is very useful when the right-hand operand depends on the value of the left one in order to
function properly. For example, the following code fragment shows how you can take advantage
of short-circuit logical evaluation to be sure that a division operation will be valid before
evaluating it:
if (denom != 0 && num / denom > 10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception
when denom is zero. If this line of code were written using the single & version of AND, both sides
would be evaluated, causing a run-time exception when denom is zero. It is standard practice to
use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-
character versions exclusively for bitwise operations. However, there are exceptions to this rule.
For example, consider the following statement:
if(c==1 & e++ < 100) d = 100)
Here, using a single & ensures that the increment operation will be applied to e whether c is equal
to 1 or not.
Explain primitive Data types of JAVA.
Java defines 8 primitive types:
Data Type Size Range Example
byte 1 Byte -128 to 127 byte a = 10;
short 2 Bytes -32,768 to 32,767 short a = 200;
int 4 Bytes -2,147,483,648 to 2,147,483,647 int a = 50000;
long 8 Bytes -9,223,372,036,854,775,80 to 9,223,372,036,854,775,807 long a = 20;
float 4 Bytes 1.4e-045 to 3.4e+038 float a = 10.2f;
double 8 Bytes 4.9e-324 to 1.8e+308 double a = 10.2;
char 2 Bytes 0 to 65536 (Stores ASCII of character) char a = ‘a’;
boolean Not true or false boolean a = true;
defined
10
1 - Basics of Java
byte
o Smallest integer type
o It is a signed 8-bit type (1 Byte)
o Range is -128 to 127
o Especially useful when working with stream of data from a network or file
o Example: byte b = 10;
short
o short is signed 16-bit (2 Byte) type
o Range : -32768 to 32767
o It is probably least used Java type
o Example: short vId = 1234;
int
o The most commonly used type
o It is signed 32-bit (4 Byte) type
o Range: -2,147,483,648 to 2,147,483,647
o Example: int a = 1234;
long
o long is signed 64-bit (8 Byte) type
o It is useful when int type is not large enough to hold the desired value
o Example: long soconds = 1234124231;
char
o It is 16-bit (2 Byte) type
o Range: 0 to 65,536
o Example: char first = ‘A’; char second = 65;
float
o It is 32-bit (4-Byte) type
o It specifies a single-precision value
o Example: float price = 1234.45213f
double
o It uses 64-bit (8-Byte)
o All math functions such as sin(),cos(),sqrt() etc… returns double value
o Example: double pi = 3.14141414141414;
boolean
o The boolean data type has only two possible values: true and false.
o This data type represents one bit of information, but its "size" isn't something that's precisely
defined.
11
1 - Basics of Java
Explain Variable in Java
The variable is the basic unit of storage in a java program.
A variable is defined by the combination of identifiers, a type and an optional initialize.
All variables have a scope, which defines their visibility and a life time.
Naming Rules for a variable: -
It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
Avoid using one-character variables such as x, y, z.
Declaring a Variable: -
All variables must be declared before they can be used. The basic form of a variable
declaration is shown here.
Type identifier [= value] [, identifier [=value]...];
Int a,b,c; // declare 3 integers
Byte z = 22; // initialize z
Char x = ‘X’; // the variable x has the value ‘X’
Escape Sequences
Escape sequences in general are used to signal an alternative interpretation of a series of
characters.
For example, if you want to put quotes within quotes you must use the escape sequence, \",
on the interior quotes.
[Link]("Good Morning \"World\" ");
Escape Sequence Description
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New Line
\t Tab
12
1 - Basics of Java
Program Structure, Compilation and Run Process
Simple Java Program Structure
public class Example
{
public static void main(String args[])
{
[Link](“First Example”);
}
}
class Example
Here name of the class is Example.
public static void main(String args[])
public: The public keyword is an access specifier, which means that the content of
the following block accessible from all other classes.
static: The keyword static allows main() to be called without having to instantiate
a particular instance of a class.
void: The keyword void tells the compiler that main() does not return a value. The
methods can return value.
main(): main is a method called when a java application begins,
String args []
Declares a parameter named args, which is an array of instance of the class string.
Args[] receives any command-line argument present when the program is executed.
[Link]()
System is predefined class that provides access to the system.
Out is the output stream that is connected to the console.
Output is accomplished by the built-in println() method. Println() displays the string
which is passed to it.
Compilation of Java Program
Source Code bytecode compiler bytecode file Interpreter (VM)
Example Example
javac java
.java .class
Figure 1.4. Java Program Compilation Process
13
1 - Basics of Java
Command 1: Javac [Link]
This command will compile the source file and if the compilation is successful, it will
generate a file named [Link] containing bytecode. Java compilers translate
java program to bytecode form.
Command 2: Java Example
The command called ‘java’ takes the bytecode and runs the bytecode on JVM
Output
First Example
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
In Java, type casting is classified into two types,
Widening/Automatic Type Casting (Implicit)
Widening/Automatic Type Casting (Implicit)
Narrowing Type Casting (Explicitly done)
Automatic Type Casting
When one type of data is assigned to other type of variable , an automatic type conversion
will take place if the following two conditions are satisfied:
The two types are compatible
The destination type is larger than the source type
Such type of casting is called “widening conversion”.
Example:
int can always hold values of byte and short
public static void main(String[] args) {
byte b = 5;
// √ this is correct
int a = b;
}
14
1 - Basics of Java
Casting Incompatible Types
To create a conversion between two incompatible types, you must use a cast
A cast is an explicit type conversion.
Such type is called “narrowing conversion”.
Syntax:(target-type) value
Example:
public static void main(String[] args) {
int a = 5;
// × this is not correct
byte b = a;
// √ this is correct
byte b = (byte)a ;
}
15