0% found this document useful (0 votes)
6 views

u1 java

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is an object-oriented, platform-independent language utilized for various applications including mobile, web, and enterprise solutions. Key features include simplicity, portability, security, and support for multithreading, making it suitable for diverse fields such as banking, retail, and big data.

Uploaded by

srsf091114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

u1 java

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is an object-oriented, platform-independent language utilized for various applications including mobile, web, and enterprise solutions. Key features include simplicity, portability, security, and support for multithreading, making it suitable for diverse fields such as banking, retail, and big data.

Uploaded by

srsf091114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Java

Java is a popular programming language, created in 1995.


It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
•Mobile applications (specially Android apps)
•Desktop applications
•Web applications
•Web servers and application servers
•Games
•Database connection
•And much, much more!
Banking: To deal with transaction management.
Retail: Billing applications that you see in a store/restaurant are completely written
in Java.
Information Technology: Java is designed to solve implementation dependencies.
Android: Applications are either written in Java or use Java API.
Financial services: It is used in server-side applications.
Stock market: To write algorithms as to which company they should invest in.
Big Data: Hadoop Map Reduce framework is written using Java.
Scientific and Research Community: To deal with huge amount of data.

Dr. Tarun Singhal


History
Java is a programming language developed by James Gosling with other team members
named Mike Sheridan and Patrick Naughton also called as Green Team in 1995 for Sun
Microsystems for digital devices such as set-top boxes, televisions etc.

What is Java?
It is an object-oriented language similar to C++, but with advanced and simplified
features. This language is free to access and can run on all platforms.

Dr. Tarun Singhal


Concurrent where you can execute many statements instead of sequentially executing
it.
Class-based and an object-oriented programming language.
Platform Independent programming language that follows the logic of “Write once,
Run anywhere” i.e. the compiled code can run on all platforms which supports java.
In simple words, it is a computing platform where you can develop applications.
Features
Simple: Java has made life easier by removing all the complexities such as pointers,
operator overloading as you see in C++ or any other programming language.
Portable: This is platform independent which means that any application written on
one platform can be easily ported to another platform.
Object-oriented: Everything is considered to be an “object” which possess some state,
behavior and all the operations are performed using these objects.
Secured: All the code is converted in byte code after compilation, which is not
readable by a human.
Dynamic: It has the ability to adapt to an evolving environment which supports
dynamic memory allocation due to which memory wastage is reduced and
performance of the application is increased.

Dr. Tarun Singhal


Distributed: This language provides a feature which helps to create distributed
applications. Using Remote Method Invocation (RMI), a program can invoke a method of
another program across a network and get the output. You can access files by calling the
methods from any machine on the internet.
Robust: Java has a strong memory management system. It helps in eliminating error as it
checks the code during compile and runtime.
High Performance: Java achieves high performance through the use of bytecode which can
be easily translated into native machine code.
Multithreaded: Many processes can run simultaneously.

Dr. Tarun Singhal


What is Object-Oriented Programming?
Object-Oriented programming (OOP) refers to a type of programming in which
programmers define the data type of a data structure and the type of operations that
can be applied to the data structure.

Dr. Tarun Singhal


What is an object in Java
An entity that has state and behavior is known as an object

Dr. Tarun Singhal


What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class.

building blocks of object oriented programming


•Inheritance
Inheritance is one such concept where the properties of one class can be inherited by
the other.
there are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived
class )
A class which inherits the properties
is known as Child Class whereas a
class whose properties are inherited
is known as Parent class.

Dr. Tarun Singhal


1.Single Inheritance:

In single inheritance, one class inherits the properties of another.

Multilevel Inheritance:

When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is
called Multilevel Inheritance.

Dr. Tarun Singhal


Hierarchical Inheritance:
When a class has more than one child classes (sub classes) or in other words, more than one child classes
have the same parent class, then such kind of inheritance is known as hierarchical.Tree type structure.

Dr. Tarun Singhal


Encapsulation
Encapsulation is a mechanism where you bind your data and code together as a single
unit. It also means to hide your data in order to make it safe from any modification.

•Abstraction
abstraction( data hiding) helps to reduce complexity.

Dr. Tarun Singhal


Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. Same things can be used in many phase.

Dr. Tarun Singhal


Differences between C, C++ and Java

Metrics C C++ Java


Object-Oriented Pure Object Oriented
Programming Paradigm Procedural language
Programming (OOP) Oriented
Based on assembly
Origin Based on C language Based on C and C++
language
Developer Dennis Ritchie in 1972 Bjarne Stroustrup in 1979 James Gosling in 1991
Interpreted language
Translator Compiler only Compiler only
(Compiler + interpreter)
Platform Dependency Platform Dependent Platform Dependent Platform Independent
Executed by JVM (Java
Code execution Direct Direct
Virtual Machine)
Approach Top-down approach Bottom-up approach Bottom-up approach
File generation .exe files .exe files .class files
Support header files Supported (#include,
Pre-processor directives Use Packages (import)
(#include, #define) #define)
keywords Support 32 keywords Supports 63 keywords 50 defined keywords
Supported except
Inheritance No inheritance Supported
Multiple inheritance
Support Function
Operator overloading is
Overloading No overloading overloading ,operator
not supported
overloading
Pointers Supported Supported Not supported
Allocation Use malloc, calloc Use new, delete Garbage collector
Exception Handling Not supportedDr. Tarun Singhal Supported Supported
JDK and JRE: The JDK enables programmers to create Java programs that can be run by
the JRE, which included JVM and class libraries.
Class Libraries: It is a group of dynamically loadable libraries that Java program can call
at run time.
Compilers: It is a Java program that accepts text file of developers and compiles into Java
class file. It is the common form of output given by compiler, which contains Java byte
code. In Java, the primary compiler is Javac.
JavaDoc: JavaDoc is documentation made by Sun Microsystems for the Java.

Dr. Tarun Singhal


JRE (Java Runtime Environment)
Class loaders: The class loader loads various classes that are
necessary for running a Java program. JVM uses three class
loaders called the bootstrap class loader, extensions class loader,
and system class loader.
Byte code verifier: Byte code verifier verifies the bytecode so
that the code doesn't disturb the interpreter.
Interpreter: Once the classes get loaded, and the code is verified,
the interpreter reads the code line by line.
Run-time: Run-time is a system used mainly in programming to
describe time period during which a particular program is
running.
Hardware: Once you compile Java native code, it runs on a
specific hardware platform.
JVM (Java Virtual Machine)
JVM is an engine that provides a runtime environment to drive the
Java Code or applications. It converts Java bytecode into machine
language. JVM is a part of Java Run Environment (JRE). It cannot be
separately downloaded and installed. To install JVM, you need to
install JRE. The full form of JVM is Java Virtual Machine.
In many other programming languages, the compiler produces
machine code for a specific system. However, Java compiler
produces code forDr. a Tarun Singhal
virtual machine which is called as JVM.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called
enterprise application.
4) Mobile Application
An application which is created for mobile devices is called a mobile application.

Dr. Tarun Singhal


Java Programming

(Basic Building Blocks)

Dr. Tarun Singhal


class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}

}
File: Simple.java

Dr. Tarun Singhal


• Syntax:
classes
Class <class_name>
{
data member;
member function;
}

All code will be part of some class


Example
class student
{ //start of class student
/*body of class is written here!*/
} // end of class student
• The code for class student will be in a file named student.java
– just a text file with the .java extension
– a class is a programmer defined data type
• A complete program will normally consist of many different classes and thus many different .class files

Dr. Tarun Singhal


Blocks
A pair of braces in a program forms a block that
groups components of a program .

public class Test {


public static void main(String[] args) { Class block
System.out.println("Welcome to Java!"); Method block
}
}

A statement represents an action or a


sequence of actions

Dr. Tarun Singhal


Access Modifiers
• public member (function/data)
– Can be called/modified from outside.
• protected
– Can be called/modified from derived classes
• private
– Can be called/modified only from the current class
• default ( if no access modifier stated )
– Can be called/modified/instantiated from the same package.

Dr. Tarun Singhal


static: You can make a method static by using the keyword static. We should call
the main() method without creating an object. Static methods are the method
which invokes without creating the objects, so we do not need any object to call
the main() method
void: In Java, every method has the return type. Void keyword acknowledges
the compiler that main() method does not return any value.
main(): It is a default signature which is predefined in the JVM. It is called by
JVM to execute a program line by line and end the execution after completion
of this method.
String args[]: The main() method also accepts some data from the user. It
accepts a group of strings, which is called a string array.

We should use a public keyword before the main() method so that JVM can identify the
execution point of the program. If we use private, protected, and default before the main()
method, it will not be visible to JVM.

Values passed to the main() method is called arguments. These arguments


are stored into args[] array, so the name args[] is generally used for it.

Dr. Tarun Singhal


What happens if the main() method is
written without String args[]?
• The program will compile, but not run,
because JVM will not recognize the main()
method. Remember JVM always looks for the
main() method with a string type array as a
parameter.

Dr. Tarun Singhal


• the main() method should always be written as:
• public static void main(String args[])

• We can interchange public and static and write it


as follows:
• static public void main(String args[])

• We can also use the different name for the String


type array and write it as:
• static public void main(String[] x)

• static public void main(String []x)


Dr. Tarun Singhal
System.out.println
It is a method: a collection of statements that performs a sequence of operations to
display a message on the console. It can be used even without fully understanding
the details of how it works.

Dr. Tarun Singhal


Comments
In Java, comments are preceded by two slashes (//) in a
line, or enclosed between /* and */ in one or multiple
lines.
•When the compiler sees //, it ignores all text after //
in the same line.
•When it sees /*, it scans for the next */ and ignores any
class Simple{
text between /* public
and static
*/. void main(String args[]){
// we are writing a hello java program
/* Aim
to print hello java
*/
System.out.println("Hello Java");
}
}

Dr. Tarun Singhal


Identifiers
• In programming languages, identifiers are used for identification purpose. In
Java, an identifier can be a class name, method name, variable name or a label.
public class Test {
public static void main(String[] args)
{
int a = 20;
}
}
• Test : class name.
• main : method name.
• String : predefined class name.
• args : variable name.
• a : variable name.

Dr. Tarun Singhal


•The only allowed characters for identifiers are all alphanumeric characters([A-
Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).
•Identifiers should not start with digits([0-9]).
•Java identifiers are case-sensitive.
•There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
•Reserved Words can’t be used as an identifier.

a+c // plus sign is not an alphanumeric character


variable-2 // hyphen is not an alphanumeric character
sum_&_difference // is not an alphanumeric character

Dr. Tarun Singhal


Keywords

• Keywords are predefined, reserved words used in


programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as
an identifier. For example:
• int money;
• Here, int is a keyword that indicates money is a variable of
type int (integer)

Dr. Tarun Singhal


Dr. Tarun Singhal
Creating and Compiling Programs

Dr. Tarun Singhal


The Java Class Loader is a part of the Java Runtime Environment that dynamically loads
Java classes into the Java Virtual Machine. The Java run time system does not need to
know about files and file systems because of class loaders.
Java classes aren’t loaded into memory all at once, but when required by an application.
At this point, the Java Class Loader is called by the JRE and these Class Loaders load
classes into memory dynamically.
Bytecode verifier
When a class loader presents the bytecodes of a newly loaded Java platform class to the
virtual machine, these bytecodes are first inspected by a verifier. The verifier checks that
the instructions cannot perform actions that are obviously damaging.
Here are some of the checks that the verifier carries out:
Variables are initialized before they are used.
Method calls match the types of object references.
Rules for accessing private data and methods are not violated.
Local variable accesses fall within the runtime stack.
The runtime stack does not overflow.
If any of these checks fails, then the class is considered corrupted and will not be loaded.
JIT compiler
In order to speed up the performance, JIT compiler communicates with JVM at the
execution time in order to compile byte code sequences into native machine code.
Basically, when using JIT Compiler, the native code is easily executed by the hardware
when compared to JVM Interpreter. By doing so, there will be a huge gain in execution
speed. Dr. Tarun Singhal
A Picture is Worth…
The output of the
compiler is .class file

Dr. Tarun Singhal


Dr. Tarun Singhal
Variable
• Variable is name of reserved area allocated in memory. In other
words, it is a name of memory location. It is a combination of "vary +
able" that means its value can be changed.

• Syntax
type variable = value;
int data=50;//Here data is variable

Dr. Tarun Singhal


• 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 instance variable.
3) Static variable
A variable which is declared as static is called static
variable. It cannot be local. You can create a single copy
of static variable and share among all the instances of
the class. Memory allocation for static variable happens
only once when the class is loaded in the memory.
Dr. Tarun Singhal
Example to understand the types of
variables in java
• class A
• {
• int data=50; //instance variable
• static int m=100; //static variable
• void method()
• {
• int n=90; //local variable
• }
• } //end of class

Dr. Tarun Singhal


• Data Member - Same data is used for all the
instances (objects) of same Class.
Assignment performed
Class A {
on the first access to the
int y = 0;
Class.
static int x = 1;
Only one instance of ‘x’
exists in memory
A a = new A();
a b
A b = new A();
System.out.println(b.x); Output: 0 0
a.x = 5; y y
System.out.println(b.x); 1
A.x = 10; 5
10 1
System.out.println(b.x);
A.x_

Dr. Tarun Singhal


Objects and new
You can declare a variable that can hold an
object:
Student s;
but this doesn’t create the object! You have to
use new:
Student s = new Student();

Dr. Tarun Singhal


Using objects
– object.method();
– object.variable ;

Dr. Tarun Singhal


Strings
• Java provides a class definition for a type called
String
• Since the String class is part of the java.lang package,
no special imports are required to use it.
• Just like regular datatypes , variables of type String
are declared as:
String s1;
String s2, s3; //etc.
• Note that String is uppercase. This is the Java
convention for classnames.

Dr. Tarun Singhal


The char type only represents one character. To
represent a string of characters, use the data
type called String. For example,

String message = "Welcome to Java";

String is actually a predefined class in the Java


library just like the System class and
JOptionPane class. The String type is not a
primitive type. It is known as a reference type.

Dr. Tarun Singhal


Strings
• Initializing a String is painless
s1 = “This is some java String”;
• Note that double quotes are required.
• Memory is allocated dynamically.
• Think of above method as shortcut for more
standard way (assuming s1 has been declared):
s1 = new String(“This is some java String”);
• new operator required to create memory for new
String object.

Dr. Tarun Singhal


String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s becomes
SupplementB

Dr. Tarun Singhal


Add two numbers
Class Simple
{
Public static void main(String ar[])
{
Int a=7; //or int a=7,b=8,c;
Int b=8; c=a+b;
Int c=a+b;
System.out.println( c);
} }
Output : 15

Dr. Tarun Singhal


When we use a variable in java program, we have to declare first it as:
int x;
Here, “x” is a variable that can store int (integer) type data. It means that int
represents the nature of data that can be stored into x.

Dr. Tarun Singhal


Primitive Data types in Java
Primitive data types are those data types whose variables can store only one
value at a time. You cannot store multiple values of the same type. These data
types are predefined in Java. They are named by a Keyword.

For example:
int x; // valid
x = 10; // valid because “x” store only one value at a time because it is
the primitive type variable.

x = 10, 20 ,30 40; // invalid


Primitive data types are not user-defined data-types. i.e. Programmers cannot
develop primitive data types.
Java defines eight primitive data types: boolean, byte, short, int, long, char, float, and
double. These can be further categorized into four groups. They are as follows:
1. Conditional category data type: boolean
2. Character category data type: char
3. Integer category data types: byte, short, int, and long.
4. Float category data types: float and double
All the data types are the keywords which are predefined in Java. They are in small
letters.
Dr. Tarun Singhal
Important terms for data type
1. Memory size allocated
Each data type has some memory size defined in Java. Whenever a variable is declared
with a data type, the memory size is automatically defined in the RAM by the JVM. For
example, If we declare int a; then the size of the memory is defined as 4 bytes.
2. Default value
Every primitive data type has default values defined in java. When the programmer does
not declare any value to the variables, default values will be assigned by the JVM during
the object creation.
For example:
The default value of int is 0 (zero).
The default value of the byte is 0.
3. Range of values
The range of value represents min or max value that a data type can hold. When we
assign the value of a variable which is not fit in the range of data type, error, or
exception will be thrown.

Dr. Tarun Singhal


Dr. Tarun Singhal
•byte
•Byte data type is an 8-bit signed two's complement integer
•Minimum value is -128 (-2^7)
•Maximum value is 127 (inclusive)(2^7 -1)
•Default value is 0
•Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.
•Example: byte a = 100, byte b = -50
class Byte
{
public static void main(String[] args)
{
byte n, a;
n = 127;
a=177;
System.out.println(n); // prints 127
System.out.println(a); // throws an error because it cannot store more
than 127
}
}
Dr. Tarun Singhal
•short
•Short data type is a 16-bit signed two's complement integer
•Minimum value is -32,768 (-2^15)
•Maximum value is 32,767 (inclusive) (2^15 -1)
•Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
•Default value is 0.
•Example: short s = 10000, short r = -20000

class ShortE
{
public static void main(String[] args)
{
short n= 3435;
System.out.println(n); // prints the value present in n i.e. 3435
}
}

Dr. Tarun Singhal


•int
•Int data type is a 32-bit signed two's complement integer.
•Minimum value is - 2,147,483,648 (-2^31)
•Maximum value is 2,147,483,647(inclusive) (2^31 -1)
•Integer is generally used as the default data type for integral values unless there is a
concern about memory.
•The default value is 0
•Example: int a = 100000, int b = -200000

Dr. Tarun Singhal


•long
•Long data type is a 64-bit signed two's complement integer
•Minimum value is -9,223,372,036,854,775,808(-2^63)
•Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
•This type is used when a wider range than int is needed
•Default value is 0L
•Example: long a = 100000L, long b = -200000L

long num = 15000000000L;


System.out.println(num); // prints 15000000000

Dr. Tarun Singhal


•float
•Float data type is of 32-bit .
•Float is mainly used to save memory in large arrays of floating point numbers
•Default value is 0.0f
•Float data type is never used for precise values such as currency
•Example: float f1 = 234.5f

•double
•double data type is 64-bit
•This data type is generally used as the default data type for decimal values, generally
the default choice
•Double data type should never be used for precise values such as currency
•Default value is 0.0d
•Example: double d1 = 123.4d

Dr. Tarun Singhal


boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for track true/false conditions
Default value is false
Example:
class boolType{
public static void main(String args[])
{
// Setting the values for boolean data type

boolean Java = true;


boolean Python = false;
System.out.println(Java); // Output will be true
System.out.println(Python); // Output will be false
}
}
char
char data type is a single 16-bit Unicode character
Char data type is used to store any character
Example: char A = 'A'
Dr. Tarun Singhal
Dr. Tarun Singhal
Array

An array declaration has two components: the type and the name.

int intArray[]; or
int[] intArray;

Dr. Tarun Singhal


Dr. Tarun Singhal
package datatypePrograms;
public class ByteExample
{
public static void main(String[] args)
{
byte num = 100; // byte is 8 bit value.
System.out.println(num);
}
}

package datatypePrograms;
class ShortExample
{
public static void main(String[] args)
{
short num = 200; // Here, 200 is stored into num which is declared as
short type.
System.out.println(num);
}
}

Dr. Tarun Singhal


package datatypeProgram;
class IntegerExample
{
public static void main(String[] args)
{
int a = 200; // Here, 200 is stored into a which is declared as int type.
int b = 300; // 300 is stored into b which is declared as int type.
System.out.println(a+b);
}
}

Dr. Tarun Singhal


Type Size

float Four bytes

double Eight bytes

Dr. Tarun Singhal


Operator in Java is a symbol which is used to perform operations.

Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups −
•Arithmetic Operators
•Relational Operators
•Bitwise Operators
•Logical Operators
•Assignment Operators
•Misc Operators

Dr. Tarun Singhal


The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
Assume integer variable A holds 10 and variable B holds 20,
Operator Description Example

Adds values on either side of the operator.


+ (Addition) A + B will give 30

Subtracts right-hand operand from left-hand


- (Subtraction) operand. A - B will give -10

Multiplies values on either side of the operator.


* (Multiplication) A * B will give 200

Divides left-hand operand by right-hand operand.


/ (Division) B / A will give 2

Divides left-hand operand by right-hand operand


and returns remainder.
% (Modulus) B % A will give 0

Increases the value of operand by 1.


++ (Increment) B++ gives 21

Decreases the value of operand by 1.


-- (Decrement) B-- gives 19

Dr. Tarun Singhal


The Relational Operators

Operator Description Example


Checks if the values of two operands are equal
== (equal to) or not, if yes then condition becomes true. (A == B) is not true.

Checks if the values of two operands are equal


!= (not equal to) or not, if values are not equal then condition (A != B) is true.
becomes true.

Checks if the value of left operand is greater


> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.

Checks if the value of left operand is less than


< (less than) the value of right operand, if yes then condition (A < B) is true.
becomes true.

Checks if the value of left operand is greater


>= (greater than or than or equal to the value of right operand, if yes
then condition becomes true. (A >= B) is not true.
equal to)

Checks if the value of left operand is less than or


<= (less than or equal equal to the value of right operand, if yes then
condition becomes true. (A <= B) is true.
to)

Dr. Tarun Singhal


The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100 Operator Description Example
b = 0000 1101 Binary AND Operator copies a bit to the (A & B) will give 12 which
& (bitwise and)
----------------- result if it exists in both operands. is 0000 1100
a&b = 0000 1100 | (bitwise or)
Binary OR Operator copies a bit if it exists (A | B) will give 61 which is
a|b = 0011 1101 in either operand. 0011 1101

a^b = 0011 0001 ^ (bitwise XOR)


Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
set in one operand but not both. 0011 0001
~a = 1100 0011
(~A ) will give -61 which is
~ (bitwise Binary Ones Complement Operator is 1100 0011 in 2's
compliment) unary and has the effect of 'flipping' bits. complement form due to a
signed binary number.
Binary Left Shift Operator. The left
operands value is moved left by the A << 2 will give 240 which
<< (left shift)
number of bits specified by the right is 1111 0000
operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 will give 15 which is
>> (right shift)
number of bits specified by the right 1111
operand.
Shift right zero fill operator. The left
operands value is moved right by the
>>> (zero fill right A >>>2 will give 15 which is
number of bits specified by the right
shift) Dr. Tarunand
Singhal 0000 1111
operand shifted values are filled up
with zeros.
The Logical Operators

Called Logical AND operator. If both


the operands are non-zero, then
the condition becomes true.
&& (logical and) (A && B) is false

Called Logical OR Operator. If any


of the two operands are non-zero,
then the condition becomes true.
|| (logical or) (A || B) is true

Called Logical NOT Operator. Use to


reverses the logical state of its
operand. If a condition is true then
Logical NOT operator will make
! (logical not) false. !(A && B) is true

Dr. Tarun Singhal


The Assignment Operators
Operator Description Example
Simple assignment operator. Assigns values from right C = A + B will assign value of A
=
side operands to left side operand. + B into C
Add AND assignment operator. It adds right operand to C += A is equivalent to C = C +
+= the left operand and assign the result to left operand. A
Subtract AND assignment operator. It subtracts right
C -= A is equivalent to C = C –
-= operand from the left operand and assign the result to
A
left operand.
Multiply AND assignment operator. It multiplies right
C *= A is equivalent to C = C *
*= operand with the left operand and assign the result to
A
left operand.
/= Divide AND assignment operator. It divides left
C /= A is equivalent to C = C /
operand with the right operand and assign the result
A
to left operand.
Modulus AND assignment operator. It takes modulus
C %= A is equivalent to C = C
%= using two operands and assign the result to left
%A
operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2


^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive ORDr.
andTarun Singhal operator.
assignment C |= 2 is same as C = C | 2
Precedence of Java Operators

Category Operator Associativity


Postfix expression++ expression-- Left to right
Unary ++expression –-expression +expression –expression ~ ! Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left

Dr. Tarun Singhal


A constructor initializes an object when it is created.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once
you define your own constructor, the default constructor is no longer used.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, an

No argument Constructors
As the name specifies the no argument constructors of Java does not accept any
parameters instead, using these constructors the instance variables of a method will be
initialized with fixed values for all objects.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.

Dr. Tarun Singhal


Static Method
Static methods are the methods in Java that can be called without creating an object of
class. They are referenced by the class name itself or reference to the Object of that
class.
When to use static methods?
When you have code that can be shared across all instances of the same class, put that
portion of code into static method.
They are basically used to access static field(s) of the class.
Instance method vs Static method
Instance method can access the instance methods and instance variables directly.
Instance method can access static variables and static methods directly.
Static methods can access the static variables and static methods directly.
Static methods can’t access instance methods and instance variables directly. They must
use reference to object. And static method can’t use this keyword as there is no
instance for ‘this’ to refer to.

Dr. Tarun Singhal


Access Modifiers in Java
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.

Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.

Dr. Tarun Singhal


Garbage Collection in Java
Java garbage collection is the process of releasing unused memory occupied by unused
objects. This process is done by the JVM automatically because it is essential for memory
management.
When a Java programs run on the JVM, objects are created on the heap, which is a portion
of memory dedicated to the program. Eventually, some objects will no longer be needed.
When there is no reference to an object, then that object is assumed to be no longer
needed and the memory occupied by the object are released. This technique is
called Garbage Collection.

The garbage collection is a part of the JVM and is an automatic process done by JVM. We
do not need to explicitly mark objects to be deleted. However, we can request to the JVM
for garbage collection of an object but ultimately it depends on the JVM to call garbage
collector.
Dr. Tarun Singhal
Advantages of Garbage Collection
•Programmer doesn't need to worry about dereferencing an object.
•It is done automatically by JVM.
•Increases memory efficiency and decreases the chances for memory leak.
An object is able to get garbage collect if it is non-reference. We can make an object non-
reference by using three ways.
1. set null to object reference which makes it able for garbage collection.
class a=new class();
a=null;
2. We can non-reference an object by setting new reference to it which makes it able for
garbage collection.
class a=new class();
clas b=new clas();
a=b;
3. Anonymous object does not have any reference so if it is not in use, it is ready for the
garbage collection.
new class();
Request for Garbage Collection
We can request to JVM for garbage collection however, it is up to the JVM when to start the
garbage collector.
Java gc() method is used to call garbage collector explicitly. However gc() method does not
guarantee that JVM will perform the garbage collection. It only request the JVM for garbage
Dr. Tarun Singhal
collection.
Dr. Tarun Singhal

You might also like