JavaUnit 1
JavaUnit 1
Java is a widely used object-oriented programming language and software platform that runs
on billions of devices, including notebook computers, mobile devices, gaming consoles,
medical devices and many others. The rules and syntax of Java are based on the C and C++
languages.
One major advantage of developing software with Java is its portability. Once you have written
code for a Java program on a notebook computer, it is very easy to move the code to a mobile
device. When the language was invented in 1991 by James Gosling of Sun Microsystems
(later acquired by Oracle), the primary goal was to be able to "write once, run anywhere."
Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Platform Independent
Java is platform independent because it is different from other languages like C, C++ etc. which
are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
Java provides software-based platform. The Java platform differs from most other platforms in
the sense that it is a software-based platform that runs on the top of other hardware-based
platforms.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
✓ No explicit pointer
✓ Java Programs run inside virtual machine sandbox
Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE) which is
used to dynamically load Java classes into the Java Virtual Machine. It adds security by
separating the package for the classes of the local file system from those that are imported from
network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access right
to objects.
Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Robust
Robust simply means strong. Java is robust because:
✓ It uses strong memory management.
✓ There is lack of pointers that avoids security problems.
✓ There is automatic garbage collection in java which runs on the Java Virtual Machine
to get free of objects which are not being used by a Java application anymore.
✓ There is exception handling and type checking mechanism in java. All these points
make java robust
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and
64 bit architectures.
Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g. C++). Java
is an interpreted language that is why it is slower than compiled languages e.g. C, C++ etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI
(Remote Method Invocation) and EJB (Enterprise Java Beans) are used for creating distributed
applications. This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages i.e. C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java
program.
When you run the Java program, Java compiler first compiles your Java code to bytecode.
Then, the JVM translates bytecode into native machine code (set of instructions that a
computer's CPU executes directly).
Java is a platform-independent language. It's because when you write Java code, it's ultimately
written for JVM but not your physical machine (computer). Since JVM executes the Java
bytecode which is platform-independent, Java is platform-independent.
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have
in OS because JVM is platform dependent.
JVM is the main component of Java architecture, and it is the part of the JRE (Java Runtime
Environment).
A program of JVM is written in C Programming Language, and JVM is Operating System
dependent.
JVM is responsible for allocating the necessary memory needed by the Java program.
JVM is responsible for deallocating memory space.
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java
Virtual Machine (JVM), and other components that are required to run Java applications.
JRE is the superset of JVM.
If you want to run Java programs, but not develop them, JRE is what you need.
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in
Java. When you download JDK, JRE is also downloaded with it.
In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc,
Java Debugger, etc).
If you want to develop Java applications, you have to download JDK.
boolean type
boolean data type represents only one bit of information either true or false which is intended
to represent the two truth values of logic and Boolean algebra.
Default value: false.
class Main
{
public static void main(String[] args)
{
boolean flag = true;
System.out.println(flag); // prints true
}
}
byte type
✓ The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
✓ If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
short type
✓ The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
✓ If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
int type
✓ The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
✓ If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have
a minimum value of 0 and a maximum value of 232-1.
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
int range = -4250000;
System.out.println(range); // print -4250000
}
}
long type
✓ The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
✓ If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
✓ Default value: 0
class LongExample
{
public static void main(String[] args)
{
long range = -42332200000L;
System.out.println(range); // prints -42332200000
}
}
Notice, the use of L at the end of -42332200000. This represents that it's an integer of the long
type.
double type
✓ The double data type is a double-precision 64-bit floating-point.
✓ It should never be used for precise values such as currency.
✓ Default value: 0.0 (0.0d)
class Main
{
public static void main(String[] args)
{
double number = -42.3;
System.out.println(number); // prints -42.3
}
}
float type
✓ The float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
✓ It should never be used for precise values such as currency.
✓ Default value: 0.0 (0.0f)
class Main
{
public static void main(String[] args)
{
float number = -42.3f;
System.out.println(number); // prints -42.3
}
}
Notice that we have used -42.3f instead of -42.3in the above program. It's because -42.3 is a
double literal.
char type
✓ It's a 16-bit Unicode character.
✓ The minimum value of the char data type is '\u0000' (0) and the maximum value of the
is '\uffff'.
✓ Default value: '\u0000'
class Main
{
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
}
}
Java Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, 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] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the
name of the variable. You can initialize the variable by specifying an equal sign and a value.
Here are several examples of variable declarations of various types. Note that some
include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store two values:
true and false. For example,
Integer Literals
An integer literal is a numeric value(associated with numbers) without any fractional or
exponential part. There are 4 types of integer literals in Java:
1. binary (base 2)
2. decimal (base 10)
3. octal (base 8)
4. hexadecimal (base 16)
e.g.
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.
Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponential
form. For example,
// 3.445*10^2
double myDoubleScientific = 3.445e2;
The floating-point literals are used to initialize float and double type variables.
Character Literals
Character literals are unicode character enclosed inside single quotes. For example,
char letter = 'a';
String literals
A string literal is a sequence of characters enclosed inside double-quotes. For example,
String str1 = "Java Programming";
Java Identifiers
Java Identifiers can be a class name, method name, variable name, or label.
✓ There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
Java Operators
Operators are symbols that perform operations on variables and values.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
class DemoArithmatic
{
public static void main(String[] args)
{
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
/ Division Operator
If we use the division operator with two integers, then the resulting quotient will also be an
integer. And, if one of the operands is a floating-point number, we will get the result will also
be in floating-point.
(5 / 2) is 2
(5.0 / 2) is 2.5
% Modulo Operator
The modulo operator % computes the remainder. When a = 7 is divided by b = 4, the remainder
is 3.
int a;
a = 7;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 7 is assigned to the variable a.
class DemoAssigmentOp
{
public static void main(String[] args)
{
// create variables
int a = 4;
int var;
class DemoRelationalOp
{
public static void main(String[] args)
{
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
class DemoLogicalOp
{
public static void main(String[] args)
{
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that
increases the value of a variable by 1. That is, ++5 will return 6.
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
! Logical complement operator: inverts the value of a boolean
Increment and decrement operator can be use as pre or post form, for example
//pre increment
++a;
//post increment
a++;
class DemoUnary
{
public static void main(String[] args)
{
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
It is important to note that the bitwise complement of any integer N is equal to - (N + 1).
Java Shift Operators
There are three types of shift operators in Java:
1. Signed Left Shift (<<)
2. Signed Right Shift (>>)
3. Unsigned Right Shift (>>>)
As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left
shift operation on it, each individual bit is shifted to the left by 1 bit.
As a result, the left-most bit (most-significant) is discarded and the right-most position(least-
significant) remains vacant. This vacancy is filled with 0s.
When we shift any number to the right, the least significant bits (rightmost) are discarded and
the most significant position (leftmost) is filled with the sign bit. For example
// right shift of 8
8 = 1000 (In Binary)
// right shift of -8
8 = 1000 (In Binary)
2's complement:
0111
+1
_______
1000
Signed bit = 1
Here, we have used the signed bit 1 to fill the leftmost bits.
class DemoRightShift
{
public static void main(String[] args)
{
int number1 = 8;
int number2 = -8;
Syntax
variable = Expression ? expression1 : expression2;
class DemoTernary
{
public static void main(String[] args)
{
int num = 7;
String result;
// ternary operator
result = (num % 2 == 0) ? "even-number" : "odd-number";
System.out.println( num + “ “ + result);
}
}
For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other. There are no automatic conversions from the numeric types to
char or boolean. char and boolean are not compatible with each other.
Here, target-type specifies the desired type to convert the specified value to. For example, the
following fragment casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
Java if Statement
Syntax
if (condition)
{
// statements
}
Working of if Statement
Java if...else (if-then-else) Statement
The if statement executes a certain section of code if the test expression is evaluated to true.
However, if the test expression is evaluated to false, it does nothing.
In this case, we can use an optional else block. Statements inside the body of else block are
executed if the test expression is evaluated to false. This is known as the if-...else statement in
Java.
Syntax
if (condition)
{
// codes in if block
}
else
{
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition is true and another
task (codes inside else block) if the condition is false.
The switch statement also includes an optional default case. It is executed when the expression
doesn't match any of the cases.