Object-Oriented Programming Overview
Object-Oriented Programming Overview
ON
OBJECT ORIENTED PROGRAMMING
PREPARED BY-
DIBYASHA DAS
ASSISTANT PROFESSOR
CSE
MODULE 1
A programming language is a set of instructions and syntax used to create software programs. A programming
language is a formal language that specifies a set of instructions for a computer to perform specific tasks. It's
used to write software programs and applications, and to control and manipulate computer systems. Some of the
key features of programming languages include:
1. Syntax: The specific rules and structure used to write code in a programming language.
2. Data Types: The type of values that can be stored in a program, such as numbers, strings, and booleans.
3. Variables: Named memory locations that can store values.
4. Operators: Symbols used to perform operations on values, such as addition, subtraction, and
comparison.
5. Control Structures: Statements used to control the flow of a program, such as if-else statements, loops,
and function calls.
6. Libraries and Frameworks: Collections of pre-written code that can be used to perform common tasks
and speed up development.
Different types of programming language
5 major types of programming languages are-
1. Procedural programming languages
A procedural language follows a sequence of statements or commands to achieve a desired output. Each series
of steps is called a procedure, and a program written in one of these languages will have one or more
procedures within it. Common examples of procedural languages include:
• C and C++
• Java
• Pascal
• BASIC
4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web content, or support
processes in larger applications. Some common scripting languages include:
• PHP
• Ruby
• Python
• bash
• Perl
• [Link]
Need of source Compiler doesn't require the It requires the source code for execution
code source code for execution later. later.
Procedural Programming focuses on the sequential Object-Oriented Programming focuses on the data
steps required to achieve a result. that is used for programming.
Functions and variables are the primary Classes and objects are the primary programming
programming tools. tools.
It cannot model the real world effectively. It can model the real world effectively.
It is not suitable for large and complex apps. It is suitable for large and complex apps.
C, Basic, Fortran, Pascal, etc., are examples of C++, Java, Python, JavaScript, etc., are examples of
procedural languages. object-oriented languages.
➢ Object
➢ Class
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation
Object:
• Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc.
• An object contains an address and takes up some space in memory. 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 behaviors like
wagging the tail, barking, eating, etc.
Class:
• Collection of objects is called class.
• Classes are user-defined datatypes.
• A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
• A class is a group of objects which have common properties.
• A class is a collection of Data member and member functions.
• Variables declared in a class are called data member and functions declared in class are called member
functions or methods.
• Once a class has been defined, we can create any number of objects belonging to that class.
• If Fruit is a class, then apple, orange, banana etc. are the objects of the class Fruit.
Inheritance
• When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance.
• It is an important part of OOPs (Object Oriented programming system).
• It provides code reusability.
• Inheritance is also known as a parent-child relationship.
• The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
• Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Abstraction
• Hiding internal or background details and showing the essential features is known as
abstraction. The unnecessary details are not displayed to the user.
• It allows to focus on what an object does rather than how it does it.
• For example, phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit typically a class are
known as encapsulation.
• Technically, in encapsulation, the variables or the data in a class is hidden from any
other class and can be accessed only through any member function of the class in
which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which is similar to
what data-hiding does. So, the terms "encapsulation" and "data-hiding" are used
interchangeably.
• For example, a capsule, it is wrapped with different medicines.
What is Java?
• Java is a programming language and a platform.
• Platform: Any hardware or software environment in which a program runs, is known
as a platform. Since Java has a runtime environment (JRE) and Application
Programming Interface (API), it is called a platform.
• 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 Oak name to Java.
• Java is mostly used for building –
Thread Support Does not support thread Has built-in thread support via
the “thread” class
Features of Java
• Simple
• Object-Oriented
• Open Source
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
1. Simple
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented
• Java is an 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 behavior.
3. Open Source
• The source code of java development is not limited to sun microsystem or oracle
corporation, it is freely available to any end user, according to requirement anyone
can customize it which is known as open source.
4. Platform Independent
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines
• Java is a write once, run anywhere.
5. Secured
• No explicit pointer means Java does not allow direct manipulation of memory through
pointers. This eliminates a class of vulnerabilities like buffer overflows and pointer
arithmetic errors, which are common sources of security exploits.
• Automatic memory management(Garbage Collection). Java's automatic garbage
collection handles memory allocation and deallocation, reducing the risk of memory
leaks and other memory-related errors that can lead to security vulnerabilities.
• Java Programs run inside a virtual machine sandbox i.e isolating the application from
direct access to the underlying operating system and hardware
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
6. Robust(Strong)
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java 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.
7. Architecture-neutral
• The memory allocation and memory deallocation is totally same for all
environment(Windows,Linux), 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.
• It occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
8. Portable
• Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
9. High-performance
• Java is faster than other traditional interpreted programming languages.
• 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.
10. 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.
11. 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 common memory area.
• Threads are important for multi-media,Web applications, etc.
12. 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).
class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
save this file as [Link]
To compile: javac [Link]
To execute: java Simple
class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
• class keyword is used to declare a class in java.
• public keyword is an access modifier which 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 to create 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.
• String[] args is used for command line argument.
• [Link]() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class.
• The subscript notation in Java array can be used after type, before the variable or after
the variable.
public static void main(String[] args)
• You can provide [] args support to the main method by passing 3 ellipses (dots)
public static void main(String... args)
JVM
• JVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is
the one that calls the main method present in a Java code.
• It is a specification that provides a runtime environment in which Java bytecode can
be executed.
• JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from each
other.
• However, Java is platform independent.
The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
Architecture of JVM
3. Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
• Interpreter: It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.
• Just-In-Time Compiler(JIT): It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
• Garbage Collector: It destroys un-referenced objects.
4. Java Native Interface (JNI)
• Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C,
C++, Assembly etc.
• Java uses JNI framework to send output to the Console or interact with
OS libraries.
5. Native Method Libraries
• These are collections of native libraries required for executing native methods. They
include libraries written in languages like C and C++.
JRE
• JRE is an acronym for Java Runtime Environment.
• The Java Runtime Environment is a set of software tools which are used for
developing Java applications.
• It is used to provide the runtime environment.
• It is the implementation of JVM.
JDK
• JDK is an acronym for Java Development Kit.
• The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets.
• The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables
Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
[Link] Variables
• Instance variables are known as non-static variables and are declared in a class but
outside of any method, constructor, or block.
• Instance variables are created when an object of the class is created and destroyed
when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default value is dependent
on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0,
for Wrapper classes like Integer it is null, etc.
• Instance variables can be accessed only by creating objects.
class Geeks {
// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();
// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);
3. Static Variables
• Static variables are also known as class variables.
• These variables are declared similarly to instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor, or block.
• Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
• Static variables are created at the start of program execution and destroyed
automatically when execution ends.
• Initialization of a static variable is not mandatory. Its default value is dependent on the
data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper
classes like Integer it is null, etc.
• If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won't halt the program. The compiler
will replace the object name with the class name automatically.
• If we access a static variable without the class name, the compiler will automatically
append the class name. But for accessing the static variable of a different class, we
must mention the class name as 2 different classes might have a static variable with
the same name.
• Static variables cannot be declared locally inside an instance method.
• Static blocks can be used to initialize static variables.
// Java Program to show the use of Static variables
import [Link].*;
class Geeks {
// static int c = 0;
// above line, when uncommented,will throw an error as static variables cannot be
declared locally.
}
}
Output
Geek Name is: Sweta Dash
Syntax:
boolean booleanVar;
Output
Is Java fun? true
Is fish tasty? False
Syntax:
byte byteVar;
Syntax:
short shortVar;
Syntax:
int intVar;
Syntax:
long longVar;
Syntax:
float floatVar;
Syntax:
double doubleVar;
Syntax:
char charVar;
Output
Grade: A
Symbol: $
Example
Type Description Default Size Literals Range of values
JVM-
dependent
true or false false true, false true, false
(typically
boolean 1 byte)
8-bit signed
0 1 byte (none) -128 to 127
byte integer
'a',
Unicode
'\u0041',
character(16 \u0000 2 bytes 0 to 65,535 (unsigned)
'\101', '\\',
bit)
char '\', '\n', 'β'
16-bit
signed 0 2 bytes (none) -32,768 to 32,767
short integer
32-bit -2,147,483,648
signed 0 4 bytes -2,0,1 to
int integer 2,147,483,647
-
64-bit
9,223,372,036,854,775,808
signed 0L 8 bytes -2L,0L,1L
to
integer
long 9,223,372,036,854,775,807
32-bit IEEE
754 3.14f, - ~6-7 significant decimal
0.0f 4 bytes
floating- 1.23e-10f digits
float point
floating-
point
2. Non-Primitive Data Types (Object Types): It will contain a memory address of variable
values because the reference types won’t store the variable value directly in memory.
Examples of Non-primitive data types are
• String
• Array
• Class
• Interface
• Object
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.
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.
void display() {
[Link](model + " " + year);
}
}
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.
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.
5. Array
An Array is a group of like-typed variables that are referred to by a common name. 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.
// Demonstrating how to create an array
public class Geeks {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
String[] arr = {"Geek1", "Geek2", "Geek3"};
Output
First Number: 1
Second Fruit: Geek2
Java Tokens
In Java, Tokens are the smallest elements of a program that is meaningful to the compiler.
They are also known as the fundamental building blocks of the program. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators
1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program. Since keywords are referred names for a
compiler, they can’t be used as variable names because by doing so, we are trying to assign a
new meaning to the keyword which is not allowed. Java language supports the following
keywords:
2. Identifiers
Identifiers are used as the general terminology for naming of variables, functions and arrays.
These are user-defined names consisting of an arbitrarily long sequence of letters and digits
with either a letter or the underscore (_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later program statements
to refer to the associated value.
Syntax:
final data_type variable_name;
import [Link].*;
class GFG {
public static void main (String[] args) {
// Example usage of PI
[Link]("The value of PI is: " + PI);
}
}
[Link]
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator
• Precedence and Associativity
5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used separator
in java is semicolon (;).
int variable; //here the semicolon (;) ends the declaration of the variable
import [Link].*;
class GFG {
public static void main (String[] args) {
Java Operators
Java operators are special symbols that perform operations on variables or values. These
operators are essential in programming as they allow you to manipulate data efficiently.
Some of the types are-
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non primitive data
types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
class Geeks
{
public static void main (String[] args)
{
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
a1 + b1 = 40
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement or negate a
value.
– : Unary minus, used for negating the values.
++ : Increment operator, used for incrementing the value by 1.
-- : Decrement operator, used for decrementing the value by 1.
There are two varieties of increment operator.
• Post-Increment : Value is first used for computing the result and then incremented.
• Pre-Increment : Value is incremented first and then result is computed.
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
3. Assignment Operator
“ =” Assignment operator is used to assign a value to any variable.
It has a right to left associativity, i.e value given on right hand side of operator is assigned to
the variable on the left and therefore right hand side value must be declared before using it or
should be a constant.
Syntax :
variable = value;
In many cases assignment operator can be combined with other operators to build a shorter
version of statement called Compound Statement.
For example, instead of a = a+5, we can write a += 5.
+=, for adding left operand with right operand and then assigning it to variable on the left.
-=, for subtracting left operand with right operand and then assigning it to variable on the left.
*=, for multiplying left operand with right operand and then assigning it to variable on the
left.
/=, for dividing left operand with right operand and then assigning it to variable on the left.
%=, for assigning modulo of left operand with right operand and then assigning it to variable
on the left.
// Java Program to show the use of Assignment Operators
import [Link].*;
// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
4. Relational Operators
These operators are used to check for relations like equality, greater than, less than.
They return boolean result after the comparison and are extensively used in looping
statements as well as conditional if else statements.
Syntax : variable relation_operator value
==, Equal to : returns true if left hand side is equal to right hand side.
!=, Not Equal to : returns true if left hand side is not equal to right hand side.
<, less than : returns true if left hand side is less than right hand side.
<=, less than or equal to : returns true if left hand side is less than or equal to right hand
side.
>, Greater than : returns true if left hand side is greater than right hand side.
>=, Greater than or equal to: returns true if left hand side is greater than or equal to right
hand side.
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the
function similar to AND gate and OR gate in digital electronics.
The second condition is not evaluated if the first one is false.
Conditional operators are-
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
// Java Program to show the use of Logical operators
import [Link].*;
class Geeks {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
[Link]("x && y: " + (x && y));
[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is,
The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.
• & (Bitwise AND): returns bit-by-bit AND of input values.
• | (Bitwise OR): returns bit-by-bit OR of input values.
• ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
• ~ (Bitwise Complement): inverts all bits (one's complement).
// Java Program to show the use of bitwise operators
import [Link].*;
class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying or
dividing the number by two, respectively. They can be used when we have to multiply or
divide a number by two. The general format ,
• << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
• >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
• >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit always 0.
class Geeks
{
public static void main(String[] args)
{
int a = 10;
9. instanceof Operator
The instanceof operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format,
Example: This example demonstrates the use of the instanceof operator to check if an
object is an instance of a specific class or interface
// Since obj2 is of type boy, whose parent class is person and it implements the interface
Myinterface it is instance of all of these classes
[Link]("obj2 instanceof Person: "
+ (obj2 instanceof Person));
[Link]("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
[Link]("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
interface MyInterface {
}
Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
Typecasting in Java
In Java, typecasting is the process of converting one data type to another data type.
• A lower data type is transformed into a higher one by a process known as widening
type casting. Implicit type casting and casting down are some names for it.
• It occurs naturally. Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:
• The target type must be larger than the source type.
• Both data types must be compatible with each other.
Example-
// Java program to demonstrate Widening TypeCasting
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int i = 10;
• The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting. Casting up or explicit type casting are other names for it.
• It doesn't just happen by itself. If we don't explicitly do that, a compile-time error will
occur. Narrowing type casting is unsafe because data loss might happen due to the
lower data type's smaller range of permitted values.
• A cast operator assists in the process of explicit casting.
Example-
// Java Program to demonstrate Narrow type casting
import [Link].*;
class Geeks {
public static void main(String[] args)
{
double i = 100.245;
1. Java if Statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is
true then a block of statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if condition is true
}
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
Syntax:
if(condition){
// Executes this block if condition is true
}else{
// Executes this block if condition is false
}
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output
i is smaller than 15
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
if( x == 30 )
{
if( y == 10 )
{
[Link]("X = 30 and Y = 10");
}
}
}
}
Output
X = 30 and Y = 10
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
class Geeks {
public static void main(String args[])
{
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
Output
i is 20
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
}
}
Output
It is 20
6. jump Statements
Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.
• Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement.
o To exit a loop.
o Used as a "civilized" form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the code
in its body for this particular iteration. This is, in effect, a goto just past the body of
the loop, to the loop's end. The continue statement performs such an action.
Return Statement
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
if (t)
return;
Java Loops
Loops in programming allow a set of instructions to run multiple times based on a condition.
In Java, there are three types of Loops, which are explained below:
1. for loop
The for loop is used when we know the number of iterations (we know how many times we
want to repeat a task). The for statement includes the initialization, condition, and
increment/decrement in one line.
Syntax:
for (initialization; condition; increment/decrement)
{
// code to be executed
}
• Initialization condition: Here, we initialize the variable in use. It marks the start of a
for loop. An already declared variable can be used or a variable can be declared, local
to loop only.
• Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
• Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
• Increment/ Decrement: It is used for updating the variable for next iteration.
• Loop termination: When the condition becomes false, the loop terminates marking
the end of its life cycle.
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++) {
[Link](i + " ");
}
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
[Link] Loop
A while loop is used when we want to check the condition before executing the loop body.
Syntax:
while (condition) {
// code to be executed
}
• While loop starts with the checking of Boolean condition. If it evaluated to true, then
the loop body statements are executed otherwise first statement following the loop is
executed. For this reason it is also called Entry control loop
• Normally the statements contain an update value for the variable being processed for
the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life
cycle.
class Geeks {
public static void main(String[] args)
{
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++;
}
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
3. do-while Loop
The do-while loop ensures that the code block executes at least once before checking the
condition.
Syntax:
do {
// code to be executed
} while (condition);
• do while loop starts with the execution of the statement. There is no checking of any
condition for the first time.
• After the execution of the statements, and update of the variable value, the condition
is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
• When the condition becomes false, the loop terminates which marks the end of its life
cycle.
• It is important to note that the do-while loop will execute its statements atleast once
before any condition is checked, and therefore is an example of exit control loop.
class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
[Link](i + " ");
i++;
} while (i <= 10);
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
Arrays in Java
In Java, an array is an important linear data structure that allows us to store multiple values of
the same type.
• Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from
the [Link] class. This allows you to invoke methods defined in Object (such
as toString(), equals() and hashCode()).
• Arrays have a built-in length property, which provides the number of elements in the
array
// initializing array
int[] arr = { 40,55,63,17,22,68,89,97,89};
// size of array
int n = [Link];
// traversing array
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
}
Output
40 55 63 17 22 68 89 97 89
1. Declaring an Array
The general form of array declaration is
// Method 1:
int arr[];
// Method 2:
int[] arr;
4. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int n = [Link];
Example: Here we are taking a student class and creating an array of Student with five
Student objects stored in the array. The Student objects have to be instantiated using the
constructor of the Student class and their references should be assigned to the array elements.
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name){
this.roll_no = roll_no;
[Link] = name;
}
}
Output
Element at 0 : { 1 aman }
Element at 1 : { 2 vaibhav }
Element at 2 : { 3 shikar }
Element at 3 : { 4 dharmesh }
Element at 4 : { 5 mohit }
Output
sum of array values : 15
Explanation
• This Java program demonstrates how to pass an array to a method.
• An integer array arr is declared and initialized in the main method.
• The sum() method is called with arr as an argument.
• Inside the sum() method, all array elements are added using a for loop.
• The final sum is then printed to the console.
Types of Arrays
where,
• data_type: is a type of data of each array block.
• array_name: is the name of the array using which we can refer to it.
• array_size: is the number of blocks of memory array going to have.
For Example
int nums[5];
[Link] Multi-Dimensional Arrays
Multidimensional arrays are used to store the data in rows and columns, where each row can
represent another individual array are multidimensional array.
Output
arr[0][0] = 3
arr[0][1] = 5
arr[0][2] = 7
Parameters:
• data_type: Type of data to be stored in the array. For example: int, char, etc.
• dimension: The dimension of the array created. For example: 1D, 2D, etc.
• array_name: Name of the array
• size1, size2, ..., sizeN: Sizes of the dimensions respectively.
Examples:
// Two dimensional array:
int[][] arr2d = new int[3][5];
// Three dimensional array:
int[][][] arr3d = new int[3][5][7];
Size of Multidimensional Arrays: The size of the multidimensional array can be calculated
by multiplying the size of all dimensions of array foe example arrd have the dimensions 3*5
= 15
For example: array int[][][] x = new int[3][5][7] can store a total of (3*5*7) = 105
elements.
Java User Input
The most common way to take user input in Java is using the Scanner class. It is a part
of [Link] package. The scanner class can handle input from different places, like as we are
typing at the console, reading from a file, or working with data streams. This class was
introduced in Java 5. Before that, we used the BufferedReader class (introduced in Java
1.1).
Example 1: Taking input from the user using the Scanner class and displaying the output.
// Java program to demonstrate the use of Scanner class to take input from user
import [Link];
class Geeks
{
public static void main(String[] args) {
}
Output:
Explanation: In the above code example, we use the nextLine() of Scanner class to read the
line value which is entered by the user and print it in the console.
Step 1: First, import the [Link] package in top of the program file Without
importing this package, we cannot use the Scanner class. either we can import
the [Link].* by importing this package we can use all the classes present in the util
package.
import [Link]
public class Geeks{
public static void main(String [] args){
}
}
Step 3: Create a variable and using scanner class object call the corresponding method to
take the input value.
int age = [Link]();
Method Description
Example 2: Taking different inputs using Scanner class method such as nextInt(),
nextDouble and nextLine(), etc.
// Java program to read data of various types using Scanner class
import [Link];
// Driver Class
public class Geeks
{
// main function
public static void main(String[] args) {
// Declare the object and initialize with predefined standard input object
Scanner sc = new Scanner([Link]);
// String input
String name = [Link]();
// Character input
char gender = [Link]().charAt(0);
Explanation: In the above code example, we use the Scanner class to take different types of
input values from user and print it in the console.
Sometimes, we have to check if the next value we read is of a certain type or if the input has
ended (EOF marker encountered). Then, we check if the scanner's input is of the type we
want with the help of hasNextDataType() functions where DataType is the type we are
interested in. The function returns true if the scanner has a token of that type, otherwise false.
For example, in the below code, we have used hasNextInt(). To check for a string, we use
hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
• hasNextInt(): This method is used to check if the token is an integer.
• hasNextLine(): This method is used to check if there is an input in next line.
Example 3: Using the hasNext() and hasNextInt() method to take input from user without
specifying the limit of input values.
// Java program to read some values using Scanne class and print their mean.
import [Link];
}
}
Output:
Explanation: In the above code example, we use the hasNext() and hasNextInt() method to
take the input values from user and then user give the input value they can specify that the
input value is ended and they can type "done" to find the mean value of given input.
Important Points:
• To create an object of Scanner class, we usually pass the predefined object [Link],
which represents the standard input stream. We may pass an object of class File if we
want to read input from a file.
• To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) function returns the first character in
that string.
• Always close the Scanner object after use to avoid resource leaks.
• The Scanner class reads an entire line and divides the line into tokens. Tokens are
small elements that have some meaning to the Java compiler.
• For example, Suppose there is an input string: "How are you"
In this case, the scanner object will read the entire line and divides the string into
tokens: "How", "are" and "you". The object then iterates over each token and reads
each token using its different methods.
The BufferedReader class of Java is used to read the stream of characters from the specified
source (character-input stream). The constructor of this class accepts an InputStream object as
a parameter.
This class provides a method named read() and readLine() which reads and returns the
character and next line from the source (respectively) and returns them.
• Instantiate an InputStreamReader class bypassing your InputStream object as a
parameter.
• Then, create a BufferedReader, bypassing the above obtained InputStreamReader
object as a parameter.
• Now, read data from the current reader as String using the readLine() or read()
method.
Example
The following Java program demonstrates how to read integer data from the user using
the BufferedReader class.
import [Link];
import [Link];
import [Link];
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
[Link] = name;
[Link] = age;
[Link] = id;
}
public void displayDetails(){
[Link]("Name: "+[Link]);
[Link]("Age: "+[Link]);
[Link]("Id: "+[Link]);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]([Link]());
[Link]("Enter your Id: ");
int id = [Link]([Link]());
Employee std = new Employee(name, age, id);
[Link]();
}
}
Output
Enter your name:
Krishna
Enter your age:
25
Enter your Id:
1233
Name: Krishna
Age: 25
Id: 1233
Java command-line argument is an argument, i.e., passed at the time of running the Java
program. Command-line arguments passed from the console can be received by the Java
program and used as input.
Example:
java Geeks Hello World
Note: Here, the words Hello and World are the command-line arguments. JVM will collect
these words and will pass these arguments to the main method as an array of strings called
args. The JVM passes these arguments to the program inside args[0] and args[1].
Example: In this example, we are going to print a simple argument in the command line.
Output:
Explanation:
• Running java GFG GeeksForGeeks prints GeeksForGeeks because the argument is
passed to main(String[] args).
• If no arguments are given (e.g., java GFG), it throws
ArrayIndexOutOfBoundsException since args is empty.
class Geeks {
// Print statements
[Link]("The command line"
+ " arguments are:");
[Link](val);
}
else