Oops in Java Unit-1
Oops in Java Unit-1
1. Introduction to Java
History of Java:
o Developed by James Gosling at Sun Microsystems (released in 1995).
o Initially designed for interactive television, but it was too advanced for the
digital cable television industry at the time.
o Gained popularity for its "write once, run anywhere" capability, enabled by
the Java Virtual Machine (JVM).
Features of Java:
o Object-Oriented: Everything is an object.
o Platform-Independent: Compiled code (bytecode) can run on any platform
with a JVM.
o Simple: Easy to learn and use, with a clean syntax.
o Secure: Features like bytecode verification and a security manager.
o Robust: Strong memory management and exception handling.
o Multithreaded: Built-in support for multithreaded programming.
o High Performance: Just-In-Time (JIT) compilers.
Java Editions:
o Java SE (Standard Edition): Core functionalities.
o Java EE (Enterprise Edition): For large-scale enterprise applications.
o Java ME (Micro Edition): For mobile and embedded systems.
Java Development Kit (JDK):
o Components: JRE (Java Runtime Environment), compiler (javac), debugger,
and various tools.
o Installation and setup: Setting up the environment variable (JAVA_HOME).
Java is statically typed and also a strongly typed language because, in Java, each
type of data (such as integer, character, hexadecimal, packed decimal, and so
forth) is predefined as part of the programming language and all constants or
variables defined for a given program must be described with one of the Java
data typData Types in Java
Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all test
cases. Java has two categories in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float,
and double
2. Non-Primitive Data Type or Object Data type: such as String, Array,
etc.
boolea 8
true or false false true, false true, false
n bits
twos-
8
complement 0 (none) -128 to 127
bits
byte integer
Descriptio Defaul Siz Example
Type n t e Literals Range of values
‘a’, ‘\u0041’,
Unicode 16 characters representation
\u0000 ‘\101’, ‘\\’, of ASCII values
character bits
char ‘\’, ‘\n’, ‘β’ 0 to 255
twos-
16
complement 0 (none) -32,768 to 32,767
bits
short integer
twos-
32 -2,147,483,648
complement 0 -2,-1,0,1,2 to
bits
int intger 2,147,483,647
-
twos- 9,223,372,036,854,775,8
64 -2L,- 08
complement 0
bits 1L,0L,1L,2L to
integer
long 9,223,372,036,854,775,8
07
1.23e100f , -
IEEE 754
32 1.23e-
floating 0.0 upto 7 decimal digits
bits 100f , .3f ,3.1
point
float 4F
// Class
class GFG {
short s = 56;
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Non-Primitive Data Type or Reference Data Types
The Reference Data Types will contain a memory address of variable values
because the reference types won’t store the variable value directly in memory.
They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character
array and a string in Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character array is a collection of separate
char-type entities. Unlike C/C++, Java strings are not terminated with a null
character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2. 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. In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access. Refer to access
specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by
convention).
3. 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.
4. 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.
5. Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of :
1. State: It is represented by the attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact with other objects.
4. Interface
Like a class, an interface can have methods and variables, but the methods declared
in an interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of
the class.
An Interface is about capabilities like a Player may be an interface and
any class implementing Player must be able to (or must implement)
move(). So it specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies
for all functions specified in the interface, then the class must be declared
abstract.
A Java library example is Comparator Interface. If a class implements
this interface, then it can be used to sort a collection.
5. Array
An Array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some
important points about Java arrays.
In Java, all arrays are dynamically allocated. (discussed below)
Since arrays are objects in Java, we can find their length using member
length. This is different from C/C++ where we find length using size.
A Java array variable can also be declared like other variables with []
after the data type.
The variables in the array are ordered and each has an index beginning
with 0.
Java array can also be used as a static field, a local variable, or a method
parameter.
The size of an array must be specified by an int value and not long or
short.
The direct superclass of an array type is Object.
Operators
Arithmetic Operators: +, -, *, /, %.
Relational Operators: ==, !=, >, <, >=, <=.
Logical Operators: &&, ||, !.
Bitwise Operators: &, |, ^, ~, <<, >>, >>>.
Assignment Operators: =, +=, -=, *=, /=, %=.
Unary Operators: +, -, ++, --, !.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression and
control the 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.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. 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. In Java, there are four types of if-
statements given below
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) 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.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java
code.
Student.java
Student.java
Output:
x + y is greater than 20
2) 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:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Student.java
Output:
Delhi
4. Nested if-statement
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
Output:
Delhi
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. The switch statement is easier to use instead of
if-else-if statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
Output:
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 switch
permits only int, string, and Enum type variables to be used.
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. The execution of the set of instructions
depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Calculation.java
Output:
Consider the following example to understand the functioning of the for-each loop
in Java.
Calculation.java
Output:
Java
C
C++
Python
JavaScript
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.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
Output:
0
2
4
6
8
10
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop
in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.
ADVERTISEMENT
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the
for loop.
BreakExample.java
Output:
0
1
2
3
4
5
6
Calculation.java
Output:
0
1
2
3
4
5
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.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Java Arrays
Normally, 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.
Unlike C/C++, we can get the length of the array using the length member. In C/C+
+, we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like C/C++, we can also create
single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
Output:
10
20
70
40
50
Output:
33
3
4
5
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any
array.
Let's see the simple example to get the minimum number of an array using a
method.
ADVERTISEMENT
Output:
Output:
10
22
44
66
Output:
10
30
50
90
60
ADVERTISEMENT
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length
of the array in negative, equal to the array size or greater than the array size while
traversing the array.
Output:
Output:
1 2 3
2 4 5
4 4 5