Unit 3
Unit 3
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
example :
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Arithmetic Operator
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Relational Operator
Java has 6 relational operators.
== is the equality operator. This returns true if both the operands are referring to
the same object, otherwise false.
!= is for non-equality operator. It returns true if both the operands are referring to
the different objects, otherwise false.
< is less than operator.
> is greater than operator.
<= is less than or equal to operator.
>= is greater than or equal to operator.
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number.
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
~ 0101
________
1010 = 10 (In decimal)
Home Work
Write a Java program with using the all bit wise operator.
Logical Operator
Logical operators are used to performing logical “AND”, “OR” and “NOT” operations
AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true execute else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
!(condition)
Ternary Operator
Java ternary operator is the only conditional operator that takes three operands. It’s a
one-liner replacement for the if-then-else statement and is used a lot in Java
programming. We can use the ternary operator in place of if-else conditions or even
switch conditions using nested ternary operators. Although it follows the same
algorithm as of if-else statement, the conditional operator takes less space and helps
to write the if-else statements in the shortest way possible.
Ternary Operator : Expression
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Assignment Operator
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable, and the right side operand of the assignment
operator is a value.
A = 2;
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1: Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2: Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Data Types: classification
Primitive data types
The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)
(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when
you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
Example:
char letterA = 'A'
Non-primitive data types
Unlike primitive data types, these are not predefined. These are user-defined data
types created by programmers. These data types are used to store multiple values.
For example, consider an array that stores a group of values. Class is also a primitive
type that stores different methods and variables. Therefore, these are also called as
advanced data types in Java.
1)Class
2)Object
3)String
4)Array
5)Interface
1. Class and objects:
A class in Java is a user defined data type i.e. it is created by the user. It acts a
template to the data which consists of member variables and methods.
An object is the variable of the class, which can access the elements of class i.e.
methods and variables.
Example: Class and Object
// main method
public static void main (String[] args) {
// creating the object of class
ClassExample obj = new ClassExample();
An interface is similar to a class however the only difference is that its methods are
abstract by default i.e. they do not have body. An interface has only the final variables
and method declarations. It is also called a fully abstract class.
interface CalcInterface {
void multiply();
void divide();
}
public class InterfaceExample implements CalcInterface {
Example:
String str = "You're the best";
An array is a data type which can store multiple homogenous variables i.e., variables
of same type in a sequence. They are stored in an indexed manner starting with
index 0. The variables can be either primitive or non-primitive data types.
Example:
int [ ] marks;
import java.io. * ;
import java.util. * ;
Variable in Java is a data container that saves the data values during Java program
execution. Every variable is assigned a data type that designates the type and
quantity of value it can hold. A variable is a memory location name for the data.
A variable is a name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location. All the operations done on
the variable affect that memory location.
In Java, all variables must be declared before use.
Types of Variables in Java
1)Local Variables
2)Instance Variables
3)Static Variables
Local Variable
class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Instance Variables
import java.io.*;
class GFG {
public GFG()
{ // Default Constructor
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}
Static Variables
import java.io.*;
class GFG {
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code.
A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and
use it many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header.
Access Specifier
Access specifier or modifier is the access type of the method. It specifies the visibility of the method.
Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Types of Method
Predefined Method
User-defined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.
Home Work
Syntax:
class <class_name>{
field;
method;
}
Multithread Programming
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.
Thread creation by extending the Thread class: We create a class that extends the
java.lang.Thread class. This class overrides the run() method available in the Thread class. A
thread begins its life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread object.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
Stream: A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Study over the internet in depth about the input stream class and output stream class
and their methods.