OOP Java Unit 1
OOP Java Unit 1
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some
excellent features which play an important role in the popularity of this language. The
features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
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 incorporate both data and behavior.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
Step 2: Now you will see a download prompt just accept the term and
conditions and click on the download button
Step 3: If you have an oracle account then sign in or if don’t then create
one and sign in
Step 5: After downloading, run the jdk-8u Application(.exe file) and follow
the instructions to install Java on your machine. Once you install Java on
your device, you have to set up the environment variable.
Step 6: Go to Control Panel -> System and Security -> System. Under
the Advanced System Setting option click on Environment Variables as
highlighted below.
Step 7: Now, you have to alter the “Path” variable under System variables
so that it also contains the path to the Java environment. Select the “Path”
variable and click on the Edit button as highlighted below.
Step 8: You will see a list of different paths, click on the New button, and
then add the path where java is installed. By default, java is installed in
“C:\Program Files\Java\jdk\bin” folder OR “C:\Program
Files(x86)\Java\jdk\bin”. In case, you have installed java at any other
location, then add that path.
Step 9: Click on OK, Save the settings, and you are done !! Now to check
whether the installation is done correctly, open the command prompt and
type javac -version. You will see that java is running on your machine.
Note: To make sure whether the compiler is set up, type javac in the
command prompt. You will see a list related to javac.
B. Linux Operating System
In Linux, there are several ways to install java. But we will refer to the
simplest and easy way to install java using a terminal. For Linux, we will
install OpenJDK. OpenJDK is a free and open-source implementation of
the Java programming language. Steps for setting the environment in the
Linux operating system are as follows:
Step 1: Go to Application -> Accessories -> Terminal.
Step 2: Type the command as below as follows:
sudo apt-get install openjdk-8-jdk
Step 3: For the “JAVA_HOME” (Environment Variable) type the command
as shown below, in “Terminal” using your installation path…(Note: the
default path is as shown, but if you have to install OpenJDK at another
location then set that path.)
export JAVA_HOME = /usr/lib/jvm/java-8-openjdk
Step 4: For “PATH” (Environment Value) type command as shown below,
in “Terminal” using your installation path…Note: the default path is as
shown, but if you have to install OpenJDK at another location then set that
path.)
export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin
Note: We are done setting up the environment in Java for Linux OS.
Note: Now to check whether the installation is done correctly, type java -
version in the Terminal. You will see that java is running on your machine.
Notepad/gedit : They are simple text-editors for writing java
programs. Notepad is available on Windows and gedit is available on
Linux.
Eclipse IDE : It is the most widely used IDE(Integrated Development
Environment) for developing software in java. You can download
Eclipse.
C. MacOS Operating System
Step 1: Open the terminal from the application folder or simply press the
“command” and “shift” key together and write initials of the terminal and
press enter.
It will be good to have package manager such as homebrew installed in
your machine as we can operate to install any software from here itself
simply by using terminal commands.
Step 2: Now in order to configure first write the command ‘java –version ‘
where the message below it will pop that there is no
java --version
javac --version
Note: If it was set up then you would have been getting the version
displayed on the screen as it is shown below where in that machine it was
already set up. So remember to cross-check in your machine once you
have successfully set it up in yours.
Step 2: Once we are done with installing JDK now let us move on setting
up the java_home environment variable for that you will have to look into
something called s ‘bash_profie’ using the below command
ls -al
You will notice that in your terminal there will be no bash_profile set but it
is shown below so here in this machine it is already set up. In order to set
it up if not there we have to create it which lets us prior seek into java
home variables whether it is set up or not.
Step 3: Setting up the home java variable. Use the below command to
check or setup if not installed as follows on the terminal:
echo $JAVA_HOME
If it is showing blank then the java home variable is not set up as
perceived from the above image.
Step 4: Installing bash_profile
Make sure to go to the root folder in the terminal and write the command
‘touch ./bash_profile ‘
Now you will see that bash-profile s created which is as shown in the
step2 in your machine which hone can verify by writing command as
follows:
ls -al
Step 5: Edit the .bash_profile created for java, you just have to write the
command marked in below media and provided below as follows:
export JAVA_HOME=$(/usr/libexec/java_home)
// No need to remember this command
OOP's concept
1. Class
class-object
2. Object
Abstraction
Encapsulation
5. Inheritance
Inheritance is a core OOP concept in Java that allows one class to acquire
the fields and methods of another class using the extends keyword. It
represents an “is-a” relationship between classes.
The class being inherited is called the superclass, and the inheriting
class is the subclass.
A subclass can use existing features of the superclass and also add its
own.
Inheritance promotes code reusability and reduces redundancy.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance
Polymorphism in Java
Types of Polymorphism
Let's see which elements are included in the structure of a Java program. A typical
structure of a Java program contains the following elements:
o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes
the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the program.
Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the
documentation section, we use comments. The comments may be single-line, multi-
line, and documentation comments.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
Package Declaration
The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed. Note that
there can be only one package statement in a Java program. It must be defined
before any class and interface declaration. It is necessary because a Java class can be
placed in different packages and directories based on the module they are used. For
all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:
Import Statements
The package contains the many predefined classes and interfaces. If we want to use
any class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to
import the class. It is written before the class declaration and after the package
statement. We use the import statement in two ways, either import a specific class or
import all classes of a particular package. In a Java program, we can use multiple import
statements. For example:
Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from
the class. It contains only constants and method declarations. Another difference is
that it cannot be instantiated. We can use interface in classes by using
the implements keyword. An interface can also be used with other interfaces by using
the extends keyword. For example:
1. interface car
2. {
3. void start();
4. void stop();
5. }
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class,
we cannot create any Java program. A Java program may conation more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a
Java program. It contains information about user-defined methods, variables, and
constants. Every Java program has at least one class that contains the main() method.
For example:
For example:
You can read more about the Java main() method here.
Methods and behavior
In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions execute
at runtime and perform the specified task. For example:
When we follow and use the above elements in a Java program, the program looks
like the following.
[Link]
Output:
1 byte or 8
byte 0 -128 to 127
bits
2 bytes or
short 0 -32,768 to 32,767
16 bits
4 bytes or
int 0 2,147,483,648 to 2,147,483,647
32 bits
8 bytes or 9,223,372,036,854,775,808 to
long 0
64 bits 9,223,372,036,854,775,807
4 bytes or
float 0.0f 1.4e-045 to 3.4e+038
32 bits
8 bytes or
double 0.0d 4.9e-324 to 1.8e+308
64 bits
2 bytes or
char ‘\u0000’ 0 to 65536
16 bits
1 byte or 2
boolean FALSE 0 or 1
bytes
// Class
class GFG {
short s = 56;
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Non-Primitive Data Type or Reference Data Types
The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value directly
in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is
a collection of separate char-type entities. Unlike C/C++, Java strings are
not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2. Array
An Array is a group of like-typed variables that are referred to by a
common name. Arrays in Java work differently than they do in C/C++. The
following are some important points about Java arrays.
In Java, all arrays are dynamically allocated. (discussed below)
Since arrays are objects in Java, we can find their length using
member length. This is different from C/C++ where we find length using
size.
A Java array variable can also be declared like other variables with []
after the data type.
The variables in the array are ordered and each has an index
beginning with 0.
Java array can also be used as a static field, a local variable, or a
method parameter.
The size of an array must be specified by an int value and not long or
short.
The direct superclass of an array type is Object.
Every array type implements the
interfaces Cloneable and [Link] .
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name
of the memory location. It is a combination of "vary + able" which means its value can be
changed.
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Example to understand the types of variables in java
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Java Variable Example: Add Two Numbers
1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. [Link](c);
7. }
8. }
Output:
20
10
10.0
10.5
10
130
-126
20
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as
objects.
The table below shows the primitive type and the equivalent wrapper class:
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working with Collection
objects, such as ArrayList, where primitive types cannot be used (the list can only
store objects):
Example
public class Main {
Integer myInt = 5;
[Link](myInt);
[Link](myDouble);
[Link](myChar);
}
Operators in Java
Last Updated : 10 Sep, 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.
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
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
// Java Program to implement
// Arithmetic Operators
import [Link].*;
// 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
// Java Program to implement
// Unary Operators
import [Link].*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-
left associativity, i.e. value given on the right-hand side of the 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.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to
build a shorter version of the statement called a Compound Statement. For
example, instead of a = a+5, we can write a += 5.
+=, for adding the left operand with the right operand and then assigning it to
the variable on the left.
-=, for subtracting the right operand from the left operand and then assigning it
to the variable on the left.
*=, for multiplying the left operand with the right operand and then assigning it
to the variable on the left.
/=, for dividing the left operand by the right operand and then assigning it to the
variable on the left.
%=, for assigning the modulo of the left operand by the right operand and then
assigning it to the variable on the left.
Example:
Java
// Java Program to implement
// Assignment Operators
import [Link].*;
// Driver Class
class GFG {
// 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));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
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
// Java Program to implement
// Relational Operators
import [Link].*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
[Link]("a > b: " + (a > b));
[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics. One thing to
keep in mind is the second condition is not evaluated if the first one is false, i.e., it
has a short-circuiting effect. Used extensively to test for several conditions for
making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa
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
Example:
Java
// Java Program to implemenet
// Logical operators
import [Link].*;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
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:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
Example:
Java
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
Output
Max of three numbers = 30
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the
one’s complement representation of the input value, i.e., with all bits inverted.
Java
// Java Program to implement
// bitwise operators
import [Link].*;
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
[Link]("d & e: " + (d & e));
[Link]("d | e: " + (d | e));
[Link]("d ^ e: " + (d ^ e));
[Link]("~d: " + (~d));
[Link]("d << 2: " + (d << 2));
[Link]("e >> 1: " + (e >> 1));
[Link]("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
o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators
Bitwise Compliment ~ ~ op
number of
Unsigned Right Shift Operator >>> op >>>
places to shift
[Link]
x&y=8
[Link]
x^y=1
[Link]
x|y=9
[Link]
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
// Java Program to implement
// shift operators
import [Link].*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Output
a<<1 : 20
a>>1 : 5
Bit Shift Operators
Shift operator is used in shifting the bits either right or left. We can use shift operators if
we divide or multiply any number by 2. The general format to shift the bit is as follows:
Note: Java does not support the unsigned left shift operator (<<<).
In general, if we write a>>n, it means to shift the bits of a number toward the right with a
specified position (n). In the terms of mathematics, we can represent the signed right shift
operator as follows:
Note: When we apply right shift operator on a positive number, we get the positive
number in the result also. Similarly, when we apply right shift operator on a negative
number, we get the negative number in the result also.
Example: Apply the signed right shift operator with specified positions 4 if x = 256
and x = -256.
If x = 256
256 >> 4
256/24 = 16
If x = -256
-256 >> 4
-256/24 = -16
In the above example, we have observed that after shifting the operator 256 converted
into 16 and -256 converted into -16.
Let's create a Java program and implement the left shift operator.
[Link]
x>>2 = 12
In general, if we write a<<n, it means to shift the bits of a number toward the left with
specified position (n). In the terms of mathematics, we can represent the signed right shift
operator as follows:
Example 1: What will be the result after shifting a<<3. The value of a is 20.
a << 3 = 160
20 << 3
20*23 = 20*8 = 160
Example 2: What will be the result after shifting a<<2. The value of a is -10.
-10 << 3
Let's create a Java program and implement the signed left shift operator.
[Link]
x<<1 = 24
The left operand value is moved right by the number of bits specified by the right operand
and the shifted bits are filled up with zeros. Excess bits shifted off to the right are
discarded.
Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits
the decimal value of a is 60.
Let's create a Java program and use the unsigned right shift operator.
[Link]
1. public class UnsignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. [Link]("x>>>2 = " + (x >>>2));
7. }
8. }
Output
x>>>2 = 5
[Link] in Java
Last Updated : 12 Jan, 2024
Java [Link]() is used to print an argument that is passed to it.
Parts of [Link]()
The statement can be broken into 3 parts which can be understood separately:
1. System: It is a final class defined in the [Link] package.
2. out: This is an instance of PrintStream type, which is a public and static
member field of the System class.
3. println(): As all instances of the PrintStream class have a public method
println(), we can invoke the same on out as well. This is an upgraded version of
print(). It prints any argument passed to it and adds a new line to the output. We
can assume that [Link] represents the Standard Output Stream.
Syntax:
[Link](parameter)
Parameters: The parameter might be anything that the user wishes to print on the
output screen.
Example of Java [Link]()
Example 1:
Below is the implementation of [Link] :
Java
// [Link]();
import [Link].*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
[Link]("Welcome");
[Link]("To");
[Link]("GeeksforGeeks");
Output
Welcome
To
GeeksforGeeks
Example 2:
Below is the implementation of [Link] :
Java
// [Link]();
import [Link].*;
// Driver Class
class GFG {
// main function
// Declaring variable
[Link](
[Link](num1 + num2);
Output
The addition of 10 and 20 is: 30
import [Link].*;
class GFG {
// print String
[Link]("Entered String str1 : " + str1);
// print string
[Link]("Entered String str2 : " + str2);
// input is an Integer
// read by nextInt() function
int x = [Link]();
// print integer
[Link]("Entered Integer : " + x);
// input is a floatingValue
// read by nextFloat() function
float f = [Link]();
Output:
Entered String str1 : Geeks
Entered String str2 : Geeks For Geeks
Entered Integer : 123
Entered FloatValue : 123.090
Example 2:
Java
// Java Program to implement
// Scanner Class to take input
import [Link].*;
import [Link];
// Driver Class
class Easy {
// main function
public static void main(String[] args)
{
// creating the instance of class Scanner
Scanner obj = new Scanner([Link]);
String name;
int rollno;
float marks;
Output:
Enter your name
Geeks
Enter your rollno
5
Enter your marks
84.60
Name=Geeks
Rollno=5
Marks=84.60
String s = [Link]();
[Link](s);
}
}
Input:
Geek
Output:
class Geeks {
public static void main(String args[]) {
String s1 = [Link]();
[Link]("You entered string " + s1);
int a = [Link]();
[Link]("You entered integer " + a);
float b = [Link]();
[Link]("You entered float " + b);
[Link]();
}
}
Input:
GeeksforGeeks
12
3.4
Output:
if ([Link] > 0) {
[Link]("The command line arguments
are:");
for (String val : args)
[Link](val);
} else {
[Link]("No command line arguments
found.");
}
}
}
Command Line Arguments:
javac [Link]
java Main Hello World
Output:
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types of
decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given
below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is evaluated
as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
[Link]
x + y is greater than 20
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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
[Link]
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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Consider the following example.
[Link]
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else-
if statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
[Link]
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
[Link]
[Link]
Java
C
C++
Python
JavaScript
It is also known as the entry-controlled loop since the condition is checked at the start of
the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
0
2
4
6
8
10
It is also known as the exit-controlled loop since the condition is not checked in advance.
The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
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.
The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for
loop.
[Link]
0
1
2
3
4
5
6
[Link]
0
1
2
3
4
5
Consider the following example to understand the functioning of the continue statement
in Java.
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. [Link](j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)
Types of Arrays in Java
Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in
a linear order.
int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional
array
2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)
You can also access java arrays using for each loops.
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in
the following way.
Student[] arr = new Student[5]; //Student is a user-defined class
Syntax:
-- data type[] arrName;
-- datatype arrName[];
-- datatype [] arrName;
Example of Arrays of Objects
Example 1:
Below is the implementation of the above mentioned topic:
Java
import [Link].*;
class GFG {
public static void main (String[] args) {
Output
Array Size:4
The Student Array contains five memory spaces each of the size of
Student class in which the address of five Student objects can be
stored.
The Student objects have to be instantiated using the constructor of
the Student class, and their references should be assigned to the array
elements in the following way.
Example 2:
Below is the implementation of the above mentioned topic:
Java
// Java program to illustrate creating
// an array of objects
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
[Link] = name;
}
}
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].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
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
Example 3:
An array of objects is also created like :
Java
// Java program to illustrate creating
// an array of objects
class Student
{
Output
Dharma
sanvi
Rupa
Ajay
Declaration:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Java Multidimensional Arrays Examples
Example 1:
Java
// Java Program to demonstrate
// Java Multidimensional Array
import [Link].*;
// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column
// Number of Rows
[Link]("Number of Rows:"+
[Link]);
// Number of Columns
[Link]("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
Example 2:
Java
// Java Program to Multidimensional Array
// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Output
2 7 9
3 6 1
7 4 2