JAVA PROGRAMMING UNIT I
JAVA PROGRAMMING UNIT I
JAVA PROGRAMMING UNIT I
UNIT I:
1. Object
An object can be represented as an entity that has state and behaviour. For example: A car
is an object that has states such as color, model, price and behaviour such as speed, start, gear
change, stop etc.
Let’s understand the difference between state and behaviour. The state of an object is a
data item that can be represented in value such as price of car, color, consider them as variables in
programming. The behaviour is like a method of the class, it is a group of actions that together
can perform a task. For example, gear change is a behaviour as it involves multiple subtasks such
as speed control, clutch, gear handle movement.
Let’s take few more examples of Objects:
Examples of states and behaviours
Example 1:
Class: House
State: address, color, area
Behaviour: Open door, close door
Let’s see how can we write these state and behaviours in a java program. States can be
represented as instance variables and behaviours as methods of the class.
class House {
String address;
String color;
double area;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...}
Example 2:
Class: Car
State: color, brand, weight, model
Behaviour: Break, Accelerate, Slow Down, Gear change.
Note: As we have seen in the above example, the states and behaviours of an object can be
represented by variables and methods in the class.
2. Class
A class can be considered as a blueprint which you can use to create as many objects as
you like. For example, here we have a class Website that has two data members. This is just a
blueprint, it does not represent any website, however using this we can create Website objects that
represents the websites. We have created two objects, while creating objects we provided separate
properties to the objects using constructor.
// constructor
Website(String name, int age){
this.webName = name;
this.webAge = age;
}
public static void main(String args[]){
//Creating objects
Website obj1 = new Website("beginnersbook", 11);
Website obj2 = new Website("google", 28);
Types of Inheritance:
Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the
child class. For example class A extends class B and class B extends class C.
Hierarchical inheritance: refers to a child and parent class relationship where more than one
classes extends the same class. For example, class B extends class A and class C extends class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which
means a child class has two parent classes. Java doesn’t support multiple inheritance, read more
about it here.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
6. Polymorphism
Polymorphism is a object oriented programming feature that allows us to perform a single action
in different ways. For example, let’s say we have a class Animal that has a method animalSound(),
here we cannot give implementation to this method as we do not know which Animal class would
extend Animal class. So, we make this method abstract like this:
public abstract class Animal{
...
public abstract void animalSound();}
Now suppose we have two Animal classes Dog and Lion that extends Animal class. We can
provide the implementation detail there.
public class Lion extends Animal{...
@Override
public void animalSound(){
System.out.println("Roar");
}}
and
public class Dog extends Animal{...
@Override
public void animalSound(){
System.out.println("Woof");
}}
As you can see that although we had the common action for all subclasses animalSound() but
there were different ways to do the same action. This is a perfect example of polymorphism
(feature that allows us to perform a single action in different ways).
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism. Method
overloading can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name in a class
that differs in signature.
class DisplayOverloading{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}}public class ExampleOverloading{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}}
Output:
a
a 10
When I say method signature I am not talking about return type of the method, for
example if two methods have same name, same parameters and have different
return type, then this is not a valid method overloading example. This will throw
compilation error.
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in
which a call to an overridden method is resolved at runtime rather, thats why it is called runtime
polymorphism.
Example
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}}public class Dog extends Animal{
Learn Java in-depth with real-world projects through our Java certification course. Enroll and
become a certified expert to boost your career.
JDK
1 1995 Initial Draft version
Beta
23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996
19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997
8
HotSpot JVM, JNDI, JPDA, JavaSound and support
5 JDK 1.3 May
for Synthetic proxy classes were added.
2000
JDK 1.5 30
Various new features were added to the language like
7 or J2SE Sep
foreach, var-args, generics etc.
5 2004
21
JAVA Module system introduced which can be applied to
11 Sep
SE 9 JVM platform.
2017
17
JAVA Feature added - Text Blocks (Multiline strings),
15 Sep
SE 13 Enhanced Thread-local handshakes.
2019
15
JAVA Feature added - Sealed Classes, Hidden Classes,
17 Sep
SE 15 Foreign Function and Memory API (Incubator).
2020
20
JAVA Feature added - Record pattern, Vector API (Fourth
21 Sep
SE 19 incubator), Structured Concurrency (Incubator) etc.
2022
The inventors of Java wanted to design a language which could offer solutions to some of
the problems encountered in modern programming. They wanted the language to be not only
reliable, portable and distributed but also simple, compact and interactive. The authors of Java
have written an influential White Paper that explains the features of java by all of the following
buzzwords:
Simple
Object Oriented
Platform Independent
Distributed
Robust
Secure
Architecture Neutral
Portable
Interpreted
High Performance
Multithreaded
Dynamic
Simple
Java is an object-oriented programming language with syntax and keywords almost
identical to C++. When developing Java, its creators took all of the good features of the existing
object-oriented programming languages such as C++, Ada, and Smalltalk, and removed most of
their flaws and peculiarities. There are a lot of aspects of the Java language that are consistent and
make sense, thereby making it easier to learn.
If you are familiar with C++ you would know about clumsy features of C++: header files,
pointer arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base
classes, and so on. All these clumsy features are cleaned-up in java making it easier to learn.
Object Oriented
What is object oriented programming (OOP) language?
Any programming language if supports Encapsulation, Abstraction, Inheritance,
Polymorphism then that language is an object oriented programming language. E.g. java, C++
Define OOP concepts?
If you have just started learning java, definitely it is very hard to understand the Object
oriented programming (OOP) concepts. Once you learn java completely then you will understand
these concepts. Many java professional who are using these concepts in their daily life will fail to
define OOP (Object Oriented Programing) concepts. Below are the definitions of OOP concepts
which will surely help you when you are attending the java interviews.
Encapsulation: It is the Process of binding the data and methods together into a single unit.
Example: Binding private variables with setter and getter methods.
Abstraction: Showing Essential properties and methods of an object by hiding internal things is
called as Abstraction. Abstraction is possible if and only if there is encapsulation. Example: Java
is an abstraction layer over binary language. Hibernate is an abstraction layer over JDBC
Inheritance: Inheriting the properties and methods of one class (super class) into another class
(sub class) using IS a relationship. Example: Ferrari class inherits the features of Car class. Puppy
class inherit the features of Dog class, Dog class inherit the features of Animal class
Polymorphism: One form behaving differently in different situations is called polymorphism.
Animal class behaving differently for different objects like Dog, Cat etc...
Platform independent
Java can run in any system line windows, Linux, mac etc. You no need to write separate program
for individual platform/OS. Program written in Windows platform can run in Linux platform.
Output of java compiler (javac.exe in windows) is a bytecode (.calss file), but not native machine
code. This bytecode is interpreted by virtual machine (not by real computer) as real computer
interprets .exe files in C/C++. Such a virtual machine is called as Java Virtual Machine (JVM).
Translating java program into Byte code makes it much easier to run a program in wide variety of
platforms/Environments, because only JVM need to be implemented. Once bytecode is ready, we
can run it in windows, Linux, calculator, mobile, watch etc.., but one thing is all environments
require just JVM. Details of JVM differ from environment to environment. (Platform to Platform)
Distributed
A technology is said to be distributed if it's business objects are geographically dispersed into
different locations and still communicating one another.
Java has a garbage collector which will automatically clean up unused objects and memory.
No need to chase memory corruption.
In java you do not use pointers to access strings, arrays, objects, even files. Nor do you need
to worry about memory allocation for them.
Java has exception handling mechanism which is very useful in handling both compile and
run time errors. Without handling errors and exceptions, entire application would fail. With
exception handling it just stops the current flows even that are when failed, but rest all flows
still runs.
Secure
Java team has said that they will have a “zero tolerance” for security bugs and will
immediately go to work on fixing any bugs found. Java program will be first compiled to byte
code. This byte code will then be interpreted by Java Virtual Machine (JVM). JVM makes java
secure with below factors:
JIT is a part of JVM. A just-in-time compiler translates Java bytecode into native machine
language. It does this while it is executing the program. Just as for a normal interpreter, the input
to a just-in-time compiler is a Java bytecode program, and its task is to execute that program.
It is important to understand that it is not practical to compile an entire Java program into
executable code all at once, because Java performs various run-time checks that can be done only
at run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore,
not all sequences of bytecode are compiled—only those that will benefit from compilation. The
remaining code is simply interpreted. The translated parts of the program can then be executed
much more quickly than they could be interpreted. Since a given part of a program is often
executed many times as the program runs, a just-in-time compiler can significantly speed up the
overall execution time.
Even though dynamic compilation is applied to bytecode, the portability and safety
features still apply, because the JVM is still in charge of the execution environment.
Multithreaded
A thread is defined as a separate path of execution inside any process. It is done to use
CPU idle time. A process consists of the memory space allocated by the operating system that can
contain one or more threads. A thread cannot exist on its own; it must be a part of a process.
Whenever a thread is created within a program it will not occupy any separate space. It will share
the same memory space of the program. It will also not consume more resources.
Thread implementations on the major platforms differ widely, but Java makes no effort to
be platform independent in this regard. Only the code for calling multithreading remains the same
across machines; Java offloads the implementation of multithreading to the underlying operating
system or a thread library.
Dynamic
In a number of ways, Java is a more dynamic language than C or C++. It was designed to
adapt to an evolving environment. Libraries can freely add new methods and instance variables
without any effect on their clients. In Java, finding out run time type information is
straightforward. This is an important feature in those situations where code needs to be added to a
running program.
boolean 8
true or false false true, false true, false
bits
byte twos-
8
complement 0 (none) -128 to 127
bits
integer
short twos-
16
complement 0 (none) -32,768 to 32,767
bits
integer
long
-
twos-
64 -2L,- 9,223,372,036,854,775,808
complement 0
bits 1L,0L,1L,2L to
integer
9,223,372,036,854,775,807
Let us discuss and implement each one of the following data types that are as follows:
1. boolean Data Type
The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by the virtual
machine is implementation-dependent and typically at least one byte (eight bits) in practice.
Values of the boolean type are not implicitly or explicitly converted to any other type using casts.
However, programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
Size: Virtual machine dependent
2. byte Data Type
The byte data type is an 8-bit signed two’s complement integer. The byte data type is
useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size: 1 byte (8 bits)
3. short Data Type
The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a
short to save memory in large arrays, in situations where the memory savings actually matters.
Syntax:
short shortVar;
Size: 2 bytes (16 bits)
4. int Data Type
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
Size: 4 bytes ( 32 bits )
Remember: In Java SE 8 and later, we can use the int data type to represent an
unsigned 32-bit integer, which has a value in the range [0, 2 32 -1]. Use the
Integer class to use the int data type as an unsigned integer.
5. long Data Type
The range of a long is quite large. The long data type is a 64-bit two’s complement integer
and is useful for those occasions where an int type is not large enough to hold the desired value.
The size of the Long Datatype is 8 bytes (64 bits).
Syntax:
long longVar;
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point numbers. The size
of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal
values, this data type is generally the default choice. The size of the double data type is 8 bytes or
64 bits.
Syntax:
double doubleVar;
It is recommended to go through rounding off errors in java.
8. char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
EXAMPLE PROGRAM:
class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';
From the image, it can be easily perceived that while declaring a variable, we need to take care of
two things that are:
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two
ways:
Variable Initialization
Assigning value by taking input
How to Initialize Java Variables?
It can be perceived with the help of 3 components explained
Example:
// Declaring float variable
float simpleInterest;
Let us discuss the traits of every type of variable listed here in detail.
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
The Local variable is created at the time of declaration and destroyed after exiting from
the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
Example 1:
// Java Program to show the use of local variables
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method,
constructor, or block.
As instance variables are declared in a class, these 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.
We initialize instance variables using constructors while creating an object. We can also
use instance blocks to initialize the instance variables.
Example:
// Java Program to show the use of
// Instance Variables
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "+ name.i);
class GFG {
// Declared static variable
public static String geek = "Shubham Jain";
// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Output
Geek Name is : Shubham Jain
General convention for a variable’s scope is, it is accessible only within the block in which it is
declared. A block begins with a left curly brace { and ends with a right curly brace }.
As we know there are three types of variables: 1) instance variables, 2) class variables and 3) local
variables, we will look at the scope and lifetime of each of them now.
Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance
variable.
General scope of an instance variable is throughout the class except in static methods. Lifetime
of an instance variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is known as
a class variable.
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.
Local Variables
All other variables which are not instance and class variables are treated as local variables
including the parameters in a method.
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.
Nested Scope
In Java, we can create nested blocks – a block inside another block. In case of nested blocks what
is the scope of local variables?
All the local variables in the outer block are accessible within the inner block but vice versa is not
true i.e., local variables within the inner block are not accessible in the outer block. Consider the
following example:
class Sample
{
public static void main(String[] args)
{
int x;
//Begining of inner block
{
int y = 100;
x = 200;
System.out.println("x = "+x);
}
//End of inner block
System.out.println("x = "+x);
y = 200; //Error as y is not accessible in the outer block
}
}
Java Arrays
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.
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.
In contrast to C/C++, the length member allows us to obtain the array's length. We must utilise the
sizeof operator in C/C++.
An object of a dynamically formed class is called an array in Java. Java arrays implement the
Serializable and Cloneable interfaces and derive from the Object class. In Java, an array can hold
objects or primitive values. Java allows us to create single- or multi-dimensional arrays, just like
C/C++ does.
Additionally, C/C++ does not support the anonymous array functionality that Java does.
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: Arrays have a fixed size and do not grow dynamically at runtime.
. 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.
10
20
70
40
50
33
3
4
5
. for(data_type variable:array){
. //body of the loop
. }
Let's see the example of printing the elements of the Java array using the for-each loop.
Testarray1.java
33
3
4
5
Explanation
This Java program demonstrates the concept of passing an array to a method. The min method
takes an integer array arr as a parameter and finds the minimum element in the array using a
simple iterative loop. In the main method, an integer array a is declared and initialized with values
{33, 3, 4, 5}, and then the min method is called with this array as an argument. The min method
iterates through the array to find the minimum element and prints it to the console.
10
22
44
66
Explanation
In this example, the printArray method takes an integer array as a parameter and prints each
element of the array. In the main method, an anonymous array {10, 20, 30} is directly passed as
an argument to the printArray method. This concise syntax demonstrates the usage of anonymous
arrays in Java, allowing for more streamlined code without the need for intermediate variable
declarations.
Returning Array from the Method
In Java, methods are not limited to returning simple data types or objects; they can also return
arrays. This feature allows for more flexibility in method design and enables developers to
encapsulate complex logic for generating arrays within methods.
TestReturnArray.java
10
30
50
90
60
Explanation
The example demonstrates how to return an array from a method in Java and subsequently use the
returned array in the calling code. By encapsulating array creation and initialization logic within
the get method, the code becomes more modular and reusable.
ArrayIndexOutOfBoundsException
In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the Java Virtual
Machine (JVM) when attempting to access an invalid index of an array. This exception occurs if
the index is negative, equal to the size of the array, or greater than the size of the array while
traversing the array.
TestArrayException.java
. 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;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
TestMultiArray.java
. class TestMultiArray {
. public static void main(String args[]) {
. int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
. // Printing the 2D array
. for (int i = 0; i < 3; i++) {
. for (int j = 0; j < 3; j++) {
. System.out.print(arr[i][j] + " ");
. }
. System.out.println();
. }
. }
. }
Output:
123
456
789
Explanation
This Java program initializes and prints a 2D array, representing a 3x3 matrix. Initially, a
2D array named arr is declared and initialized with values using array initializer syntax. The array
consists of three rows, each containing three columns. The program then iterates through each
row and column of the array using nested loops. Within the loops, it prints the value of each
element, separated by a space. After printing all the elements of a row, a newline character is
printed to move to the next line. This process continues until all elements of the array are printed.
As a result, the program outputs the 3x3 matrix with each element displayed in its respective row
and column.
These examples demonstrate the declaration, instantiation, initialization, and traversal of
both single-dimensional and multidimensional arrays in Java.
Jagged Arrays in Java
In Java, a jagged array is an array of arrays where each row of the array can have a
different number of columns. This contrasts with a regular two-dimensional array, where each
row has the same number of columns.
Declaring and Initializing a Jagged Array
To declare a jagged array in Java, you first declare the array of arrays, and then you
initialize each row separately with its own array of columns.
012
3456
78
Explanation
This Java program demonstrates the concept of a jagged array, where an array of arrays is created,
with each inner array having a different number of columns. Initially, a 2D array named arr is
declared with 3 rows, but with each row having a different number of columns: the first row has 3
columns, the second row has 4 columns, and the third row has 2 columns. The program then
initializes the jagged array by filling it with sequential values starting from 0. Finally, it iterates
through the array and prints out each element, row by row, separated by a space, with a newline
character indicating the end of each row.
What is the class name of a Java array?
In Java, an array is an object. However, arrays have a special feature in Java where the JVM
generates a proxy class for each array object. This proxy class represents the runtime type of the
array. To obtain the class name of a Java array, you can use the getClass().getName() method,
which is available on all Java objects. This method returns a String representing the fully qualified
name of the class of the object, including any package information.
Testarray.java
Explanation
An integer array called arr is initialised with the numbers {33, 3, 4, 5} in this Java programme,
and its elements are printed. Then, it uses the clone() method to duplicate arr, assigns the result to
carr, and prints the items of the duplicated array. The last line of the programme compares arr and
carr using the == operator; the result evaluates to false, meaning that arr and carr are distinct array
objects. The elements in both arrays, though, are the same.
Addition of Two Matrices in Java
A fundamental operation in linear algebra and computer science, matrix addition is frequently
utilised in a variety of applications, including scientific computing, computer graphics, and image
processing. To create a new matrix with the same dimensions as the original, matching elements
from each matrix must be added when adding two matrices in Java. This Java program shows how
to add matrices effectively by using stacked loops to do a basic example of the process.
Let's see a simple example that adds two matrices.
ArrayAddition.java
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
MatrixMultiplicationExample.java
Explanation
This Java program computes the multiplication of two 3x3 matrices, 'a' and 'b', storing the result
in matrix 'c'. It initializes matrices 'a' and 'b' with predefined values and creates matrix 'c' to store
the result. Using nested loops, it iterates through each element of the resulting matrix 'c',
calculating the dot product of corresponding row and column elements from matrices 'a' and 'b'.
The computed result for each element is accumulated in the corresponding position of 'c'.
Operators in Java
Last Updated : 04 Oct, 2024
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. In this article, we will learn about Java
Operators and learn all their types.
What are the Java Operators?
Operators in Java are the symbols used for performing specific operations in Java. Operators
make tasks like addition, multiplication, etc which look easy although the implementation of these
tasks is quite complex.
Operators are the building blocks of Java expressions, allowing you to perform calculations,
comparisons, and more. For a deeper exploration of all types of operators and how to use them
effectively, the Java Programming Course covers everything from basic arithmetic to advanced
bitwise operations.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. 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
Example:
// Java Program to implement
// Arithmetic Operators
import java.io.*;
// Drive Class
class GFG {
// Main Function
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.
+ : Unary plus indicates the positive value (numbers are positive without this, however).
It performs an automatic conversion to int when the type of its operand is the byte, char, or
short. This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are two varieties
of increment operators.
o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is computed.
– – : Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operators.
o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result is computed.
! : Logical not operator, used for inverting a boolean value.
Example:
// Java Program to implement
// Unary Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than. They
return boolean results after the comparison and are extensively used in looping statements as
well as conditional if-else statements. The general format is,
variable relation_operator value
Some of the relational operators are-
==, Equal to returns true if the left-hand side is equal to the right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand side.
<=, less than or equal to returns true if the left-hand side is less than or equal to the
right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater than or equal to
the right-hand side.
Example:
// Java Program to implement
// Relational Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These 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. General format-
number shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as multiplying the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of the initial number. Similar
effect to dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.
// Java Program to implement
// shift operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
class operators {
public static void main(String[] args)
{
class Person {
}
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
Precedence and Associativity of Java Operators
Precedence and associative rules are used when dealing with hybrid equations involving more
than one type of operator. In such cases, these rules determine which part of the equation to
consider first, as there can be many different valuations for the same equation. The below table
depicts the precedence of operators in decreasing order as magnitude, with the top representing
the highest precedence and the bottom showing the lowest precedence.
Interesting Questions about Java Operators
1. Precedence and Associativity:
There is often confusion when it comes to hybrid equations which are equations having multiple
operators. The problem is which part to solve first. There is a golden rule to follow in these
situations. If the operators have different precedence, solve the higher precedence first. If they
have the same precedence, solve according to associativity, that is, either from right to left or from
left to right. The explanation of the below program is well written in comments within the
program itself.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
2. Be a Compiler:
The compiler in our systems uses a lex tool to match the greatest match when generating tokens.
This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too
many of the readers might seem to create a compiler error. But this statement is absolutely
correct as the token created by lex is a, =, b, ++, +, c. Therefore, this statement has a similar
effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c; would
generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an error as
there is no operand after the second unary operand.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0;
// a=b+++c is compiled as
// b++ +c
// a=b+c then b=b+1
a = b++ + c;
System.out.println("Value of a(b+c), "
+ " b(b+1), c = " + a + ", " + b
+ ", " + c);
// a=b+++++c is compiled as
// b++ ++ +c
// which gives error.
// a=b+++++c;
// System.out.println(b+++++c);
}
}
Output
Value of a(b+c), b(b+1), c = 10, 11, 0
// concatenates x and y as
// first x is added to "concatenation (x+y) = "
// producing "concatenation (x+y) = 5"
// and then 8 is further concatenated.
System.out.println("Concatenation (x+y)= " + x + y);
// addition of x and y
System.out.println("Addition (x+y) = " + (x + y));
}
}
Output
Concatenation (x+y)= 58
Addition (x+y) = 13
. if(condition) {
. statement 1; //executes when condition is true
. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
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:
. if(condition) {
. statement 1; //executes when condition is true
. }
. else{
. statement 2; //executes when condition is false
. }
Consider the following example.
Student.java
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.
. if(condition 1) {
. statement 1; //executes when condition 1 is true
. }
. else if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else {
. statement 2; //executes when all the conditions are false
. }
Consider the following example.
Student.java
. public class Student {
. public static void main(String[] args) {
. String city = "Delhi";
. if(city == "Meerut") {
. System.out.println("city is meerut");
. }else if (city == "Noida") {
. System.out.println("city is noida");
. }else if(city == "Agra") {
. System.out.println("city is agra");
. }else {
. System.out.println(city);
. }
. }
. }
Output:
Delhi
4. 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 of Nested if-statement is given below.
. if(condition 1) {
. statement 1; //executes when condition 1 is true
. if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else{
. statement 2; //executes when condition 2 is false
. }
. }
Consider the following example.
Student.java
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.
Points to be noted about switch statement:
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.
The syntax to use the switch statement is given below.
. switch (expression){
. case value1:
. statement1;
. break;
. .
. .
. .
. case valueN:
. statementN;
. break;
. default:
. default statement;
. }
Consider the following example to understand the flow of the switch statement.
Student.java
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
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. 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.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Java
C
C++
Python
JavaScript
. while(condition){
. //looping statements
. }
The flow chart for the while loop is given in the following image.
0
2
4
6
8
10
. do
. {
. //statements
. } 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
. public class Calculation {
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int i = 0;
. System.out.println("Printing the list of first 10 even numbers \n");
. do {
. System.out.println(i);
. i = i + 2;
. }while(i<=10);
. }
. }
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.
Java 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.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
0
1
2
3
4
5
6
Type Casting
Convert a value from one data type to another data type is known as type casting.
Rules of Typecasting
Widening Conversion (Implicit)
o No explicit notation is required.
o Conversion from a smaller data type to a larger data type is allowed.
o No risk of data loss.
Narrowing Conversion (Explicit)
o Requires explicit notation using parentheses and casting.
o Conversion from a larger data type to a smaller data type is allowed.
o Risk of data loss due to truncation.
Use Cases
Typecasting is commonly used in various scenarios, such as:
o Converting between primitive data types.
o Handling data in expressions and calculations.
o Interacting with different methods and APIs that expect specific data types.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
. byte -> short -> char -> int -> long -> float -> double
Why Widening Type Casting?
Widening conversion needs to be implemented in order to enable Java to work smoothly with
different data types. It creates unbroken workflows when an element of a smaller type is used in a
context that needs a larger type. The reason for generalizing the narrower type is in order not to
lose any data by converting the smaller type to the larger one, and preserving the whole
information.
Types of Widening Type Casting
The common procedure of the Widening type casting is about conversion from primitive to
primitive data types in Java.
o From byte to short, int, long, float, or double.
o From data to type int, long, float, or double.
o Char to int, long, float, or double can be converted.
o Various other types like int, long, float, or double can also be used.
Key Points to Note
o Widening typecasting is performed automatically by the Java compiler when converting
from a smaller data type to a larger data type.
o No explicit notation, such as casting, is required for widening typecasting.
o Widening conversions are always safe and do not result in any loss of data.
o Widening typecasting is commonly used in assignments, expressions, and method
invocations where data of different types interact.
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.
WideningTypeCastingExample.java
In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting, then the compiler reports a compile-time error.
. double -> float -> long -> int -> char -> short -> byte
Why Narrowing Type casting?
Narrowing typecasting becomes necessary when we need to convert data from a larger data type
to a smaller one. It often occurs when we are working with data of different sizes and need to fit
larger values into smaller containers.
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java
. class Simple{
. public static void main(String args[]){
. System.out.println("Hello Java");
. }
. }
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o 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 does not
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it does not return any value.
o The main() method represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in
coming section.
o System.out.println() is used to print statement on the console. Here, System is a class, out
is an object of the PrintStream class, println() is a method of the PrintStream class. We
will discuss the internal working of System.out.println() statement in the coming section.
To write the simple program, we need to open notepad by Start Menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shownbelow:
As we can see in the above notepad window, we have written a simple Java program and saved it
as Simple.java.
In order to compile and run the above program, open the Command Prompt window by using the
following steps:
Click on start menu -> All Programs -> Accessories -> command prompt. When we have
done with all the steps properly, following window appears on the screen:
To compile and run the above program, go to your current directory first; my current directory
is c:\new. Write the following commands:
To compile: javac Simple.java
To execute: java Simple
. class A{
. static public void main(String... args){
. System.out.println("hello java4");
. }
. }; //optional
Valid Java main() method signature
Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our
programs. A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.
// Driver Class
class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}
// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java
compiler creates a default constructor (constructor with no arguments) if your
class doesn’t have any.
// Driver class
class GFG {
// Default Constructor
GFG() { System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null,
etc. depending on the type.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
Example:
// Java Program for Parameterized Constructor
import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
}
}
Output
GeekName :Avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor
returns the current class instance. We can write ‘return’ inside a constructor.
Now the most important topic that comes into play is the strong incorporation of OOPS with
constructors known as constructor overloading. Just like methods, we can overload constructors
for creating objects in different ways. The compiler differentiates constructors on the basis of
the number of parameters, types of parameters, and order of the parameters.
Example:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class Geek {
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one "
+ "argument - String : " + name);
}
System.out.println(
"Constructor with two arguments : "
+ " String and Integer : " + name + " " + age);
}
class GFG {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments
class Geek {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
System.out.println();
Java Methods
The method in Java or Methods of Java is a collection of statements that perform some specific
tasks and return the result to the caller. A Java method can perform some specific tasks without
returning anything. Java Methods allows us to reuse the code without retyping the code. In Java,
every method must be part of some class that is different from languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Syntax of Method:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method:
Code Reusability
Code Optimization
Note: Methods are time savers and help us to reuse the code without retyping the
code.
To deepen your understanding of Java methods and learn how to effectively implement them in
your programs, you might consider exploring structured learning resources or comprehensive
Java Programming Online courses designed to enhance your coding skills and knowledge.
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its subclasses.
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any modifier. It is accessible within the same
class and package within which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the method or void if does not return a
value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the convention is
a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw; you can specify these
exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to perform
your intended operations. It is Optional in syntax.
2. Static Method: Access the static data using class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
}
Method Signature:
It consists of the method name and a parameter list (number of parameters, type of the parameters,
and order of the parameters). The return type and exceptions are not considered as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of parameter is int.
Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a
multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first
word, the first letter of each word should be capitalized.
Method Calling
The method needs to be called for use its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
It completes all the statements in the method.
It reaches a return statement.
Throws an exception.
Example:
// Java Program to Illustrate Methods
// Class 1
// Helper class
class Addition {
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Static block
static {
num = 10;
System.out.println("Static block executed. num = " + num);
}
Static Data
Static data (or static variables) are variables declared with the static keyword.
They belong to the class rather than any specific instance.
All objects of the class share the same copy of the static variable.
class StaticDataExample {
static int counter = 0;
StaticDataExample() {
counter++;
}
Static Method
A static method is a method that is associated with the class rather than any object of the
class.
It can be called without creating an object of the class.
Static methods can only access other static members (variables or methods).
Example:
class StaticMethodExample {
static int add(int a, int b) {
return a + b;
}
String Class
The String class is used to create and manipulate immutable strings in Java.
Strings created using the String class cannot be modified (immutable).
class StringExample {
public static void main(String[] args) {
String str = "Hello, Java!";
System.out.println("String length: " + str.length());
System.out.println("Character at index 4: " + str.charAt(4));
System.out.println("Substring: " + str.substring(7));
System.out.println("Uppercase: " + str.toUpperCase());
}
}
Output:
String length: 12
Character at index 4: o
Substring: Java!
Uppercase: HELLO, JAVA!
StringBuffer Class
The StringBuffer class is used to create and manipulate mutable strings.
It is thread-safe because its methods are synchronized.
class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(", Java!"); // Append to the string
System.out.println("After append: " + sb);