Java Unit 1
Java Unit 1
Foundations of Java
• Java is a Programming Language and a Platform Independent. Java is a high level, robust,
object oriented and secure programming language.
• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak
to Java.
• Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
• Java Standard Edition (JSE): It is used to create programs for a desk top computer.
• Java Enterprise Edition (JEE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
• Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.
Types of Java Applications
There are four types of Java applications that can be created using Java programming:
• Standalone Applications: Java standalone applications use GUI components such as AWT,
Swing, and Java FX. These components contain buttons, list, menu, scroll panel, etc. It is
also known as desktop alienations.
• Enterprise Applications: An application which is distributed in nature is called enterprise
applications.
• Web Applications: An application that run on the server is called web applications. We
use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.
• Mobile Applications: Java ME is a cross-platform to develop mobile applications which
run across smart phones. Java is a platform for App Development in Android.
Features of Java:
• Object Oriented – Java implements basic concepts of Object-oriented programming System
(OOPS) i.e. Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation. In Java,
everything is an Object. Java can be easily extended since it is based on the Object model.
• Platform Independent − Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
• Simple – Java fallows the basic Syntax of C, C++. If you understand the basic concept of OOPS
then it is easy to master in java.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
• Portable − Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
• Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
• Multithreaded − With Java's multithreaded feature In java we can write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
• Interpreted − Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
• High Performance − With the use of Just-In-Time compilers, Java enables high performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.
OOP Concepts
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
1. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. Using classes, you
can create multiple objects with the same behavior instead of writing their code multiple times.
In general, class declarations can include these components in order:
• Modifiers: A class can be public or have default access
• Class name: The class name should begin with the initial letter capitalized by convention.
• Body: The class body is surrounded by braces, {}.
2. Object
An Object is a basic unit of Object-Oriented Programming that represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
The objects are what perform your code, they are the part of your code visible to the
viewer/user.
3. Abstraction
Abstraction in Java is the process of hiding implementation details and showing only the
essential features of an object. It helps users focus on what an object does rather than how it
does it.
4. Encapsulation
Encapsulation is the process of wrapping data and methods into a single unit, usually a class,
and restricting direct access to the data. It acts as a protective shield that prevents data from
being accessed directly from outside the class.
5. Inheritance
Inheritance is a core OOP concept in Java that allows one class to acquire the fields and
methods of another class using the extends keyword. It represents an “is-a” relationship
between classes.
• The class being inherited is called the superclass, and the inheriting class is the subclass.
• A subclass can use existing features of the superclass and also add its own.
• Inheritance promotes code reusability and reduces redundancy.
6. Polymorphism
Polymorphism means “many forms”, where a single entity can behave differently in different
situations. In Java, it allows the same method or object to show different behavior based on
context.
• Same method, different behavior depending on the object
• Achieved through method overloading and method overriding
7. Dynamic Binding
Dynamic Binding (also known as Late Binding or Run-time Binding) occurs when the Java Virtual
Machine (JVM) determines which specific method implementation to execute at runtime rather
than at compile time.
8. Message Passing
Message Passing is the process by which objects communicate with one another. In Java, this is
simply the act of one object calling a method of another object to request an action or
information.
JVM
The Java Virtual Machine (JVM) is a core component of the Java Runtime Environment (JRE)
that allows Java programs to run on any platform without modification. JVM acts as an
interpreter between Java bytecode and the underlying hardware, providing Java’s famous Write
Once, Run Anywhere (WORA) capability.
• Java source (.java) -> compiled by javac -> bytecode (.class)
• JVM loads the bytecode, verifies it, links it, and then executes it
• Execution may involve interpreting bytecode or using Just-In-Time (JIT) compilation to
convert “hot” code into native machine code for performance
• Garbage collection runs in the background to reclaim memory from unused objects
Simple Java Program
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Code Explanation
A Java program follows a specific structure where every piece of code must reside inside a
class
• public class HelloWorld:
o public is an access modifier that makes the class accessible from anywhere.
o class is a keyword used to define a new class.
o HelloWorld is the name of the class, which must exactly match the filename (e.g.,
[Link]).
• public static void main(String[] args):
o This is the entry point of the program where the Java Virtual Machine (JVM) starts
execution.
o static means the method belongs to the class and can be called without creating an
object of the class.
o void indicates that this method does not return any value.
o String[] args is a parameter that allows the program to accept command-line
arguments as an array of strings
• [Link]("Hello, World!");:
o This statement prints the text inside the quotation marks to the screen.
o The semicolon (;) at the end is mandatory for every statement in Java to signal the
end of a command.
If executed with:
java CommandLineExample Hello World 123
Output
Command-line arguments are:
Hello
World
123
JAVA – DATA TYPES
Data type is used to allocate sufficient memory space for the data. Data types
specify the different sizes and values that can be stored in the variable.
➢ Java is a strongly Typed Language.
➢ Definition: strongly Typed Language:
Java is a strongly typed programming language because every variable must be declared
with a data type. A variable cannot start off life without knowing the range of values it can
hold, and once it is declared, the data type of the variable cannot change.
1. Primitive Types:
Primitive data types are those whose variables allow us to store only one value and
never allow storing multiple values of same type. This is a data type whose variable
can hold maximum one value at a time.
There are eight primitive types in Java:
Integer Types:
1. int
2. short
3. long
4. byte
Floating-point Types:
5. float
6. double
Others:
7. char
8. Boolean
➢ Integer Types:
The integer types are form numbers without fractional parts. Negative values are
[Link] provides the four integer types shown below:
Storage Default
Type Range Example
Requirement Value
-2,147,483,648(-2^31)
int a = 100000,
int 4 bytes to 0
int b = -200000
2,147,483,647 (2^31-1)
short s = 10000,
short 2 bytes -32,768 (-2^15) to 32,767 (2^15-1) 0
short r = -20000
-9,223,372,036,854,775,808 (-2^63)
long a = 100000L,
long 8 bytes to 0L
int b = -200000L
9,223,372,036,854,775,808 (2^63-1)
byte a = 100 ,
byte 1 byte -128 (-2^7) to 127 (2^7-1) byte b = -50 0
➢ Floating-point Types:
The floating-point types denote numbers with fractional parts. The
two floating-pointtypes are shown below:
Storage Default
Type Requirement Range Example Value
Approximately ±3.40282347E+38F
float 4 bytes (6-7 significant decimal digits) float f1 =234.5f 0.0f
Approximately
double d1 =
double 8 bytes ±1.79769313486231570E+308 123.4 0.0d
(15 significant decimal digits)
➢ char:
• char data type is a single 16-bit Unicode character.
• Minimum value is '\u0000' (or 0).
• Maximum value is '\uffff' (or 65,535 inclusive).
• Char data type is used to store any character.
• Example: char letterA ='A'
➢ boolean:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true
JAVA – VARIABLES
➢ A Variable is a named piece of memory that is used for storing data in java
Program.
➢ A variable is an identifier used for storing a data value.
➢ A Variable may take different values at different times during the execution
if the program, unlike the constants.
➢ The variable's type determines what values it can hold and what
operations can beperformed on it.
➢ Syntax to declare variables:
datatype identifier [=value][,identifier [ =value] …];
➢ Initializing Variables:
✓ After the declaration of a variable, it must be initialized by means of assignment
statement.
✓ It is not possible to use the values of uninitialized variables.
✓ Two ways to initialize a variable:
1. Initialize after declaration:
Syntax: variablename=value;
int months;
months=1;
int months=12;
➢ Dynamic Initialization of a Variable:
Java allows variables to be initialized dynamically using any valid expression at thetime
the variable is declared.
class FindRemainer
{
public static void main(String arg[]) {int num=5,den=2;
int rem=num%den; [Link](“Remainder is “ rem);
}
}
Output:
Remainder is 1
In the above program there are three variables num, den and rem. num and den are
initialized by constants whereas rem is initialized dynamically by the modulo division
operation on num and den.
Access modifiers cannot be Access modifiers can be used Access modifiers can be
used for local variables. forinstance variables. used for class variables.
class area
{
int length=20;
int breadth=30;
static int classvar=2500;
void calc()
{
int areas=length*breadth;
[Link](“The area is “+areas+” [Link]”);
}
Program Explanation:
Class name: area
Method names: calc() and main()
Local variables: areas (accessed only in the particular method)
Instance variables: length and breadth (accessed only through the object‘s method)
Static variable: accessed anywhere in the program, without object reference
ARRAYS
Definition:
An array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantage of Array:
• Code Optimization: It makes the code optimized; we can retrieve or sort the data
easily.
• Random access: We can get any data located at any index position.
Disadvantage of Array:
• Size Limit: We can store only fixed size of elements in the array. It doesn't growits
size at runtime.
Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
1. One-Dimensional Array:
➢ Creating an array:
Three steps to create an array:
1. Declaration of the array
2. Instantiation of the array
3. Initialization of arrays
Example:
int[] floppy; (or) int []floppy (or) int floppy[];
Definition:
Allocating memory spaces for the declared array in memory (RAM) is called as
Instantiation of an array.
Syntax:
arrayRefVar=new datatype[size];
3. Initialization of arrays:Definition:
Storing the values in the array element is called as Initialization of arrays.
Example:
floppy[0]=20;
Example 1:
int regno[]={101,102,103,104,105,106};
int reg[]=regno;
ARRAY LENGTH:
The variable length can identify the length of array in Java. To find the number of
elements of an array, use [Link].
Example1:
int regno[10]; len1=[Link];
Example 2:
for(int i=0;i<[Link];i++)
[Link](regno[i]);
Following picture represents array myList. Here, myList holds ten double values and
the indicesare from 0 to 9.
class Array
{
public static void main(String[] args)
{
int month_days[];
month_days=new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;
max = myList[0];
for (int i = 1; i < [Link]; i++)
{
if (myList[i] > max)
max = myList[i];
}
[Link]("Max is " + max);
}
}
Output:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
2. Multidimensional Arrays:
Definition:
Multidimensional arrays are arrays of arrays. It is an array which uses more than
one index to access array elements. In multidimensional arrays, data is stored in
row and column based index (also known as matrix form).
int[][] arr=new int[3][3]; //3 row and 3 column - internally this matrix is implemented as arrays of arrays of int.
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class twoDarray
{
public static void main(String args[])
{
int array1[][]=new int[4][5];// declares an 2D array.
int array2[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D arrayint i,j,k=0;
// printing 2D array2
[Link]("-------Array 2--------");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](array2[i][j]+
}
[Link]();
}
}
}
Output:
-------------Array1------------
01234
56789
10 11 12 13 14
15 16 17 18 19
-------------Array2------------
123
245
445
It means that, when we allocate memory for a multidimensional array, we need to only
specify the memory for the first (leftmost) dimension. We can allocate the remaining
dimensions separately with different sizes.
class twoDarray
{
public static void main(String args[])
{
int array1[][]=new int[4][]; // declares an 2D array.
array1[0]=new int[1];
array1[1]=new int[2];
array1[2]=new int[3];
array1[3]=new int[4];
int i,j,k=0;
Output:
0
12
345
6789
OPERATORS
Operators are used to manipulate primitive data types.
Java operators can be classified as unary,binary, or ternary—meaning taking one, two,
or three arguments, respectively.
1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x=10;
6. [Link](x++); //10 (11)
7. [Link](++x); //12
8. [Link](x--); //12 (11)
9. [Link](--x); //108.
10.}
11.}
Output:
10
12
12
10
1. class OperatorExample
2. {
3. public static void main(String args[])
4. {
5. int a=10;
6. int b=10;
7. [Link](a++ + ++a); //10+12=22
8. [Link](b++ + b++); //10+11=21 7.
9. }
10. }
Output:
22
21
Output:
-11
9
False
true
A binary or ternary operator appears between its arguments.
1. Assignment
2. Arithmetic
3. Relational
4. Logical
5. Bitwise
6. Compound assignment
7. Conditional
8. Type
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Relational Operators > < >= <= == !=
Logical Operators && || & | ! ^
Bit wise Operator & | ^ >> >>>
Compound Assignment += -= *= /= %=
Operators <<= >>= >>>=
Conditional Operator ?:
If the value already exists in the variable it is overwritten by the assignment operator
(=).
14
16
Output:
21
3. Relational Operators
Relational operators in Java are used to compare 2 or more objects. Java provides six
relational operators: Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
Checks if the values of two operands are equal or not, if yes (A == B) is not
== then condition becomes true. true.
Checks if the value of left operand is greater than the value of (A > B) is not
> right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value ofright
< operand, if yes then condition becomes true. (A < B) is true.
Checks if the value of left operand is greater than or equal tothe (A >= B) is not
>= value of right operand, if yes then condition becomes true. true.
public RelationalOperatorsDemo( )
{
int x = 10, y = 5;
[Link]("x > y : "+(x > y));
[Link]("x < y : "+(x < y));
[Link]("x >= y : "+(x >= y));
[Link]("x <= y : "+(x <= y));
[Link]("x == y : "+(x == y));
[Link]("x != y : "+(x != y));
Output:
$java RelationalOperatorsDemo
x > y : true
x < y : false
x >= y : true
x <= y : false
x == y : false
x != y : true
4. Logical Operators
Logical operators return a true or false value based on the state of the Variables. Given
that x and y represent boolean expressions, the boolean logical operators are defined
in the Table below.
x&y x|y
X Y !x x && y x || y x^y
True True Fals true true False
e
True False Fals false true True
e
False True True false true True
False False True false false false
Example:
public class LogicalOperatorsDemo
{
public LogicalOperatorsDemo()
{
boolean x = true;
boolean y = false;
[Link]("x & y : " + (x & y));
[Link]("x && y : " + (x && y));
[Link]("x | y : " + (x | y));
[Link]("x || y: " + (x || y));
[Link]("x ^ y : " + (x ^ y));
[Link]("!x : " + (!x));
}
public static void main(String args[])
{
new LogicalOperatorsDemo();
}
}
Output:
$java LogicalOperatorsDemo
x & y : false
x && y : false
x | y : true
x || y: true
x ^ y : true
!x : false
5. Bitwise Operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level.
The result of applying bitwise operators between two corresponding bits in the
operandsis shown in the Table below.
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
[Link]("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
[Link]("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
[Link]("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
[Link]("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
[Link]("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
[Link]("a >>> 2 = " + c );
}
}
Output:
$java Test
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
13. [Link](a);12.
14. }
15. }
Output:
13
9
18
9
7. Conditional Operators
The Conditional operator is the only ternary (operator takes three arguments)
operator in Java. The operator evaluates the first argument and, if true, evaluates the
second argument.
If the first argument evaluates to false, then the third argument is evaluated. The
conditional operator is the expression equivalent of the if-else statement.
The conditional expression can be nested and the conditional operator associates from
right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
Example:
public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
[Link]("z : " + z);
Output:
$java TernaryOperatorsDemo
z : 12
8. instanceof Operator:
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type). instanceof operator is
written as:
Example:
public class Test
{
public static void main(String args[])
{
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
[Link]( result );
}
}
OPERATOR PRECEDENCE:
The order in which operators are applied is known as precedence. Operators with a higher
precedence are applied before operators with a lower precedence.
The operator precedence order of Java is shown below. Operators at the top of the table
are applied before operators lower down in the table.
If two operators have the same precedence, they are applied in the order they appear in a
statement. That is, from left to right. You can use parentheses to override the default
precedence.
Example:
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19.
Note that ‗*‘ takes higher precedence than ‗+‘ according to chart shown above. This kindof
precedence of one operator over another applies to all the operators.