JAVA Unit - 1
JAVA Unit - 1
in 1995.
It is used to develop desktop and mobile applications, big data processing, embedded systems.
Java was originally designed for interactive television, but it was too advanced technology for the
digital cable television industry at the time.
Java team members, initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Initially it was 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 Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
Java is an object oriented language which gives a clear structure to programs and allows code to
be reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
Features
The primary objective of Java programming language creation was to make it portable, simple and
1. Simple 7. Secured
3. Portable 9. Robust
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
Object-oriented:
Java is platform independent because it is different from other languages. Java is a write once,
run anywhere language.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms.
Runtime Environment
This bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
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 a virtual machine sandbox-A separate environment that allows users
to execute their applications without affecting the underlying system.
It has a bytecode verifier that checks the code fragments for any illegal code that violates the
access right.
Robust:
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make
Java robust.
Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for example,
the 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.
However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any 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.
Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes.
It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java.
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.
The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
Java supports dynamic compilation and automatic memory management (garbage collection).
Java OOPs Concepts
Object-oriented programming is a method used for designing a program using classes and objects.
Object-oriented programming is also called the core of java.
In this type of approach, programmers define the data type of a data structure and the operations
that are applied to the data structure.
For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviours
like wagging the tail, barking, eating, etc.
Class:
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
It represents the set of properties or methods that are common to all objects of one type.
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
Inheritance is an important pillar of OOP. It is the mechanism in java by which one class is
allow to inherit the features(fields and methods) of another class.
Super Class: The class whose features are inherited is known as superclass(or a base class or a parent
class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the fields and methods of the existing
class.
Polymorphism:
For example: to convince the customer differently, to draw something, for example, shape,
Abstraction:
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can
be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-
hiding.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
Java Development Kit
The Java Development Kit (JDK) is a cross-platformed software development environment that
offers a collection of tools and libraries necessary for developing Java-based software applications
and applets
It includes the JVM, compiler, debugger and other tools for developing Java applets and
applications.
The first is javac , which is the java compiler .It converts our source code into byte code
The second is java, Sometimes referred to as the application launcher, this is the program we will
use to run a Java program.
It operates on the byte code, using the JVM to execute your program.
Hello World Example
class Simple
System.out.println("Hello World");
To compile:
javac Simple.java
To execute:
java Simple
Parameters used
public keyword is an access modifier that represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to invoke the
static method.
The main() method is executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
Here, System is a class, out is an object of the PrintStream class, println() is a method of the
PrintStream class.
Create blocks of code
Program code in a Java program is contained in a block.
A block in Java is a group of one or more statements enclosed in braces. A block begins with an
open curly brace ({) symbol and ends with a close curly brace (}) symbol.
Between the opening and closing braces, you can code one or more statements.
Even though a block can be treated as a single statement, you should not end a block with a
semicolon.
The statements within the block may require semicolons, but the block itself does not.
Java keywords
Java keywords are also known as reserved words.
Keywords are particular words that act as a key to a code.
These are predefined words by Java so they cannot be used as a variable or object name or
class name.
Identifiers
An identifier is nothing but a name assigned to an element in a program.
They can be a class name, variable name, method name, package name, constant name, and more.
However, In Java, There are some reserved words that can not be used as an identifier.
From the example, we have the following Java
identifiers:
println (method)
Rules for Identifiers in Java
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar
sign ($). for example, @abc is not a valid identifier because it contains a special character which is @.
There should not be any space in an identifier. For example, java class is an invalid identifier.
An identifier should not contain a number at the starting. For example, 123javaclass is an invalid
identifier.
An identifier should be of length 4-15 letters only. However, there is no limit on its length. But, it is
good to follow the standard conventions.
We can't use the Java reserved keywords as an identifier such as int, float, double, char, etc. For
example, int double is an invalid identifier in Java.
An identifier should not be any query language keywords such as SELECT, FROM, COUNT,
DELETE, etc.
java class libraries
java programming, main two features are supported that is class and object. Basically we know
that class is collection of objects and object is an instance of class.
And also there are some classes available with java system that provide some important support to
the java programmer for developing their programming logic as well as their programming
architecture with very smooth way.
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.
Primitive Data Types:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
literals are the constant values that appear directly in the program. It can be assigned directly to a
variable. Java has various types of literals.
Types of Literals:
Integer Literal
Character Literal
Boolean Literal
String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a
positive (+) or negative (-). For example, 5678, +657, -89, etc.
Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For example,
045, 026,
A character literal is expressed as a character or an escape sequence, enclosed in a single quote ('')
mark. It is always a type of char.
String Literals:
String literal is a sequence of characters that is enclosed between double quotes ("") marks.
Boolean Literals:
Boolean literals are the value that is either true or false. It may also have values 0 and 1.
A variable is a name given to a memory location. It is the basic unit of storage in a program.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
There are three types of variables in java: local, instance and static.
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.
Scope of a local variable is within the block in which it is declared and the lifetime of a local variable
is until the control leaves the block in which it is declared.
Instance Variable:
A variable declared inside the class but outside the body of the method, is called an instance variable.
It is not declared as static.
these variables are created when an object of the class is created and destroyed when the object is
destroyed. The general scope of an instance variable is throughout the class except in static methods
Static variable:
It cannot be local. You can create a single copy of the static variable and share it among all the
instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the memory.
The general scope of a class variable is throughout the class and the lifetime of a class variable is
until the end of the program or as long as the class is loaded in memory.
public class A
void method()
}//end of class
Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Assignment Operator.
Unary Operator
unary operators require only one operand. Unary operators are used to perform various operations
i.e. Operator Meaning
++ Increment operator:
increments value by 1
-- Decrement operator:
decrements value by 1
Logical complement
! operator: inverts the
value of a boolean
Example
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
Arithmetic Operators
Arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
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 Operators
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.
Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.
Example:
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10>>2);//10/2^2=10/4=2
}}
Relational Operators
Relational operators are used to check the relationship between two operands
int a = 10;
int b = 20;
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}}
Bitwise operators
Bitwise operator works on bits and performs the bit-by-bit operation.
They can be used with any of the integral types (char, short, int, etc).
a = 0011 1100
b = 0000 1101
~a = 1100 0011
public class operators {
int a = 5;
int b = 7;
} }
Assignment Operators
Assignment operators are used in Java to assign values to variables:
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
class Main {
int a = 4;
int var;
var = a;
var += a;
var *= a;
} }
Logical Operators
Logical operators are used to check whether an expression is true or false. They are used in decision
making.
true if either
|| (Logical OR) expression1 || expression1 or
expression2
expression2 is true
}
Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.
Example:
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
} }
Type Casting/type conversion
When you assign a value of one data type to another, the two types might not be compatible with
each other.
Converting one primitive datatype into another is known as type casting (type conversion).
Converting a lower data type into a higher one is called widening type casting.
byte -> short -> char -> int -> long -> float -> double
public class Main1 {
int m = 9;
double n = m;
System.out.println(m);
System.out.println(n);
}
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting.
double -> float -> long -> int -> char -> short -> byte
public class Main1 {
double m = 9.0;
int n = (int) m;
System.out.println(m);
System.out.println(n);
}
Operators Precedence and Associativity
When more than one operator has to be evaluated in an expression Java interpreter has to decide
which operator should be evaluated first.
Java makes this decision on the basis of the precedence and the associativity of the operators.
There are certain rules defined in Java to specify the order in which the operators in an expression
are evaluated.
In Java, parentheses() and Array subscript[] have the highest precedence in Java.
Java operators have two properties those are precedence, and associativity.
Precedence is the priority order of an operator, if there are two or more operators in an expression
then the operator of highest priority will be executed first then higher, and then high.
Associativity is a concept related to the operators applied when two operators with the same
precedence come in an expression.
Suppose we have an expression a + b - c (+ and - operators have the same priority), and this
expression will be treated as ((a + b) - c) because these operators are left to right-associative.
Operators Precedence Associativity
= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=
Example:
Expression: x = 4 / 2 + 8 * 4 - ( 5+ 2 ) % 3
In the above expression, the highest precedence operator is (). So, the parenthesis goes first and
calculates first.
x=4/2+8*4-7%3
Now, /, * and % operators have the same precedence and highest from the + and - Here, we use
the associativity concept to solve them.
The associative of these operators are from left to right. So, / operator goes first and
then * and % simultaneously.
x=2+8*4-7%3
x = 2 + 32 - 7 % 3
x = 2 + 32 - 1
Now, + and - operators both also have the same precedence, and the associativity of these
operators lest to the right.
x = 34 - 1
x = 33
Control Statements
The statements in the java code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements.
Java provides three types of control flow statements.
Decision Making statements:
if statements
switch statement
Loop statements:
do while loop
while loop
for loop
for-each loop
Jump statements:
break statement
continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. It evaluate
program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and switch statement.
If Statement:
The control of the program is diverted depending upon the specific condition.
The condition of the If statement gives a Boolean value, either true or false.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Simple if statement:
It is the most basic statement among all control flow statements in Java.
It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates
to true.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false }
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements.
Syntax:
if(condition 1) {
else if(condition 2) {
else {
}
Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.
Syntax:
if(condition 1) {
if(condition 2) {
else{
} }
Switch Statement
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched.
Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
Break statement terminates the switch block when the condition is satisfied. It is optional, if not
used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true.
However, loop statements are used to execute the set of instructions in a repeated order.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
for loop
while loop
do-while loop
for loop
It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code.
We use the for loop only when we exactly know the number of times, we want to execute the
block of code.
Syntax:
//block of statements
}
public class Cal {
int sum = 0;
sum = sum + j;
}
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection.
In the for-each loop, we don't need to update the loop variable.
Syntax:
for(data_type var : array_name/collection_name){
//statements
}
Example:
public class Cal {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
} } }
while loop:
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement
in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.
Syntax:
while(condition){
//looping statements
}:
public class Calculation {
int i = 0;
while(i<=10) {
System.out.println(i);
i = i + 2;
}
do-while loop:
The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can
use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.
Syntax:
do
//statements
} while (condition);
public class Cal {
int i = 0;
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
There are two types of jump statements in Java, i.e., break and continue.
break statement:
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
public class BreakExample {
System.out.println(i);
if(i==6) {
break;
}
continue statement:
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Example:
if(j == 4) {
continue;
} System.out.println(j);
} } } }