Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views42 pages

Java Notes 1

Java was developed by a team at Sun Microsystems in 1991, initially named 'Oak' before being renamed to 'Java' in 1995, with the goal of creating a platform-independent programming language. The document outlines the evolution of Java through various versions, highlighting key features and improvements introduced over time. It also compares Java with C and C++, discusses Java architecture, and details data types, variables, tokens, and operators in Java.

Uploaded by

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

Java Notes 1

Java was developed by a team at Sun Microsystems in 1991, initially named 'Oak' before being renamed to 'Java' in 1995, with the goal of creating a platform-independent programming language. The document outlines the evolution of Java through various versions, highlighting key features and improvements introduced over time. It also compares Java with C and C++, discusses Java architecture, and details data types, variables, tokens, and operators in Java.

Uploaded by

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

History of java

 Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991.
 Java is related to C++, which is inherited from the language C.
 The characters of Java is inherited from C and C++ language. It took approx. Eighteen months
to develop the first working version.
 It was first named as “Oak” but was renamed as “Java” in 1995. It is publicly announced in
the spring of 1995.
 The basic idea behind creating this language is to create a platform-independent language
that is used to develop software for consumer electronic devices such as microwave ovens,
remote controls, etc. Initially, it was not designed for Internet applications.

Evolution of Java:
Release
Version Features
Date

JDK
1995 —
Beta

January
JDK 1.0 This is the first stable version.
1996

In this version, added many new library elements, redefined the way of handling
JDK February events, and reconfigured most of the libraries of 1.0 and deprecated some
1.1 1997 features defined by 1.0. Added inner class, JavaBeans, JDBC, RMI, JIT (Just In
time) compiler.

J2SE December Added support for many features, such as Swing and Collection Framework. The
1.2 1998 methods suspend(), resume() and stop() of Thread class were deprecated.

J2SE 1.3 May 2000 A very small improvement, as it just improved the development environment.

It added some upgrades such as the new keyword assert, chained exception and
February
J2SE 1.4 a channel-based I/O subsystem. Also added some feature to the collection
2002
framework and the Networking classes.

The significant new features added to this version are – Generics, Annotation,
September
J2SE 5.0 Autoboxing and Auto-unboxing, Enumeration, for-each, variable-length
2004
argument, Static import, Formatted I/O, Concurrency utilities.

Java SE December In this version the API libraries and several new packages got enhanced and
6 2006 offered improvements to the run time. It supports JDBC 4.0.

Java SE July 2011 Added JVM support for dynamic language, String in the switch, Automatic
7 resource management in try-statement, support for underscore in integers,
binary integer literals etc…

Java SE
March 2014 Added Date and time API, Repeating annotation, JavaFX.
8

Java SE September Added Java platform module system update, jshell, XML Catalog, jlink, and the
9 2017 JavaDB was removed from JDK

Java SE Added features are local variable type interface, Application class data sharing,
March 2018
10 Garbage collector interface, etc…

Java SE September Feature added: Dynamic class file loader, HTTP client, and Transport layer
11 2018 security. JavaFX, Java EE, and CORBA modules have been removed from JDK.

Java SE Added Microbenchmark Suite, JVM Constant API, One AArch64 Port, Default
March 2019
12 CDS Archives etc.

Differences between C, C++ and Java


Metrics C C++ Java
Programming Object-Oriented Pure Object Oriented
Procedural language
Paradigm Programming (OOP) Oriented
Based on assembly
Origin Based on C language Based on C and C++
language
Dennis Ritchie in Bjarne Stroustrup in James Gosling in
Developer
1972 1979 1991
Interpreted language
Translator Compiler only Compiler only (Compiler +
interpreter)
Platform Dependency Platform Dependent Platform Dependent Platform Independent
Executed by JVM
Code execution Direct Direct (Java Virtual
Machine)
Approach Top-down approach Bottom-up approach Bottom-up approach
File generation .exe files .exe files .class files
Pre-processor Support header files Supported (#header, Use Packages
directives (#include, #define) #define) (import)
keywords Support 32 keywords Supports 63 keywords 50 defined keywords
Datatypes (union,
Supported Supported Not supported
structure)
Supported except
Inheritance No inheritance Supported
Multiple inheritance
Support Function
Operator overloading
Overloading No overloading overloading
is not supported
(Polymorphism)
Pointers Supported Supported Not supported
Allocation Use malloc, calloc Use new, delete Garbage collector
Exception Handling Not supported Supported Supported
Templates Not supported Supported Not supported
No constructor
Destructors Supported Not supported
neither destructor
Multithreading/
Not supported Not supported Supported
Interfaces
Database
Not supported Not supported Supported
connectivity
Supported ( auto, Supported ( auto,
Storage Classes Not supported
extern ) extern )

Java Architecture
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the
process of interpretation and compilation. It defines all the processes involved in creating a
Java program. Java Architecture explains each and every step of how a program is compiled
and executed.

Java Architecture can be explained by using the following steps:

o There is a process of compilation and interpretation in Java.

o Java compiler converts the Java code into byte code.

o After that, the JVM converts the byte code into machine code.

o The machine code is then executed by the machine.

The following figure represents the Java Architecture in which each step is elaborate
graphically.
Components of Java Architecture
The Java architecture includes the three main components:

o Java Virtual Machine (JVM)

o Java Runtime Environment (JRE)

o Java Development Kit (JDK)

Java Virtual Machine


The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The
feature states that we can write our code once and use it anywhere or on any operating
system. Our Java program can run any of the platforms only because of the Java Virtual
Machine. It is a Java platform component that gives us an environment to execute java
programs. JVM's main task is to convert byte code into machine code.

JVM, first of all, loads the code into memory and verifies it. After that, it executes the code
and provides a runtime environment. Java Virtual Machine (JVM) has its own architecture,
which is given below:

JVM Architecture

JVM is an abstract machine that provides the environment in which Java bytecode is executed.
The falling figure represents the architecture of the JVM.

.
ClassLoader: ClassLoader is a subsystem used to load class files. ClassLoader first loads the
Java code whenever we run it.

Class Method Area: In the memory, there is an area where the class data is stored during
the code's execution. Class method area holds the information of static variables, static
methods, static blocks, and instance methods.

Heap: The heap area is a part of the JVM memory and is created when the JVM starts up. Its
size cannot be static because it increase or decrease during the application runs.

Stack: It is also referred to as thread stack. It is created for a single execution thread. The
thread uses this area to store the elements like the partial result, local variable, data used for
calling method and returns etc.

Native Stack: It contains the information of all the native methods used in our application.

Execution Engine: It is the central part of the JVM. Its main task is to execute the byte code
and execute the Java classes. The execution engine has three main components used for
executing Java classes.

o Interpreter: It converts the byte code into native code and executes. It sequentially
executes the code. The interpreter interprets continuously and even the same method
multiple times. This reduces the performance of the system, and to solve this, the JIT
compiler is introduced.
o JIT Compiler: JIT compiler is introduced to remove the drawback of the interpreter. It
increases the speed of execution and improves performance.
o Garbage Collector: The garbage collector is used to manage the memory, and it is a
program written in Java. It works in two phases, i.e., Mark and Sweep. Mark is an
area where the garbage collector identifies the used and unused chunks of memory.
The Sweep removes the identified object from the Mark

Java Native Interface

Java Native Interface works as a mediator between Java method calls and native libraries.

Java Runtime Environment


It provides an environment in which Java programs are executed. JRE takes our Java code,
integrates it with the required libraries, and then starts the JVM to execute it. To learn more
about the Java Runtime Environment.

Java Development Kit


It is a software development environment used in the development of Java applications and
applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and several
development tools in it. To learn more about the Java Development Kit,.
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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type

o byte data type

o char data type

o short data type

o int data type

o long data type

o float data type

o double data type


Data Type Default Value Default size

Boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Variables in Java
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 effects that memory location.
 In Java, all the variables must be declared before use.
How to declare variables?
We can declare variables in java as follows:

type: Type of data that can be stored in this variable.


name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be
assigned values in two ways:
 Variable Initialization
 Assigning value by taking input
How to initialize variables?

TOKENS
The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program. The Java compiler identified these words as tokens.
These tokens are separated by the delimiters. It is useful for compilers to detect errors.
Remember that the delimiters are not part of the Java tokens.

token <= identifier | keyword | separator | operator | literal | comment


1. public class Demo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("hello");
6. }
7. }

In the above code snippet, public, class, Demo, {, static, void, main, (, String, args,
[, ], ), System, ., out, println, hello, etc. are the Java tokens.

The Java compiler translates these tokens into Java bytecode. Further, these bytecodes are
executed inside the interpreted Java environment.

Types of Tokens
Java token includes the following:

o Keywords

o Identifiers

o Literals

o Operators

o Separators

o Comments

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:

01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.

o Identifiers are case sensitive.

Some valid identifiers are:

1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:

o Integer

o Floating Point

o Character

o String

o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

Null any reference type

Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:

o Arithmetic Operators

o Assignment Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

o Relational Operators

o Unary Operators

o Logical Operators

o Ternary Operators

o Bitwise Operators

o Shift Operators

Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:

1. separator <= ; | , | . | ( | ) | { | } | [ | ]

Note that the first three separators (; , and .) are tokens that separate other tokens, and the last six (3
pairs of braces) separators are also known as delimiters. For example, Math.pow(9, 3); contains nine
tokens.

o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.

o Curly Braces {}: The curly braces denote the starting and ending of a code block.

o Comma (,): It is used to separate two values, statements, and parameters.

o Assignment Operator (=): It is used to assign a variable and constant.

o Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:

o Line Oriented: It begins with a pair of forwarding slashes (//).

o Block-Oriented: It begins with /* and continues until it founds */.

Type Casting and Type Conversion


1. Type Casting:
In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing
casting, the destination data type may be smaller than the source data type
when converting the data type to another data type, that’s why it is also
called narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
(): is a casting operator.
target_datatype: is a data type in which we want to convert the source
data type.
Type Casting example –

float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data
type into byte(target) data type.

2. Type conversion :
In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination
data type cannot be smaller than the source data type, that’s why it is also
called widening conversion. One more important thing is that it can only be
applied to compatible data types.
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.
Let’s see the difference between Type casting and Type conversion which are
given below:
S.N
O TYPE CASTING TYPE CONVERSION

In type casting, a data type is


converted into another data type Whereas in type conversion, a
by a programmer using casting data type is converted into
1. operator. another data type by a compiler.

Type casting can be applied Whereas type conversion can


to compatible data types as well only be applied to compatible
2. as incompatible data types. datatypes.

In type casting, casting operator Whereas in type conversion,


is needed in order to cast the a there is no need for a casting
3. data type to another data type. operator.

In typing casting, the destination


data type may be smaller than
the source data type, when Whereas in type conversion, the
converting the data type to destination data type can’t be
4. another data type. smaller than source data type.

Type casting takes place during


the program design by Whereas type conversion is done
5. programmer. at the compile time.

Type casting is also called Whereas type conversion is also


narrowing conversion because in called widening conversion
this, the destination data type because in this, the destination
may be smaller than the source data type can not be smaller than
6. data type. the source data type.

7. Type casting is often used in Whereas type conversion is less


coding and competitive used in coding and competitive
S.N
O TYPE CASTING TYPE CONVERSION

programming as it might cause


programming works. incorrect answer.

Type casting is more efficient and Whereas type conversion is less


8. reliable. efficient and less reliable.

Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

 Arithmetic Operators: They are used to perform simple arithmetic operations


on primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
 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 positive value (numbers are positive without
this, however). It performs an automatic conversion to int when the type
of its operand is 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 operator.
 Post-Increment : Value is first used for computing the result
and then incremented.
 Pre-Increment : Value is incremented first and then result is
computed.
 — : Decrement operator, used for decrementing the value by 1. There
are two varieties of decrement operator.
 Post-decrement : Value is first used for computing the result
and then decremented.
 Pre-Decrement : Value is decremented first and then result is
computed.
 ! : Logical not operator, used for inverting a boolean value.
 Assignment Operator : ‘=’ Assignment operator is used to assign a value to
any variable. It has a right to left associativity, i.e value given on right hand side
of operator is assigned to the variable on the left and therefore right hand side
value must be declared before using it or should be a constant.
General format of assignment operator is,

variable = value;
 In many cases assignment operator can be combined with other operators to build
a shorter version of statement called Compound Statement. For example,
instead of a = a+5, we can write a += 5.
 +=, for adding left operand with right operand and then assigning it to
variable on the left.
 -=, for subtracting left operand with right operand and then assigning it
to variable on the left.
 *=, for multiplying left operand with right operand and then assigning it
to variable on the left.
 /=, for dividing left operand with right operand and then assigning it to
variable on the left.
 %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.

 Java Relational Operators


Relational operators are used to check the relationship between two operands. For example,

// check is a is less than b

a < b;

Here, > operator is the relational operator. It checks if a is less than b or not.

It returns either true or false .

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns false

Example : Relational Operators

class Main {
public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}
Note: Relational operators are used in decision making and loops.

 Java Logical Operators


Logical operators are used to check whether an expression is true or false . They are used in
decision making.
Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

expression1 || true if either expression1 or expression2 is


|| (Logical OR)
expression2 true

! (Logical
!expression true if expression is false and vice versa
NOT)

Example : Logical Operators


class Main {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
 Java Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true , expression1 is assigned to the variable .
If the Expression is false , expression2 is assigned to the variable .
Let's see an example of a ternary operator.
class Java {
public static void main(String[] args) {

int februaryDays = 29;


String result;

// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year

 Java Bitwise and Shift Operators


In Java, bitwise operators perform operations on integer data at the individual bit-level. Here,
the integer data includes byte , short , int , and long types of data.
There are 7 operators to perform bit-level operations in Java.
Operator Description

| Bitwise OR

& Bitwise AND

^ Bitwise XOR

~ Bitwise Complement

<< Left Shift

>> Signed Right Shift

>>> Unsigned Right Shift

1. Java Bitwise OR Operator


The bitwise OR | operator returns 1 if at least one of the operands is 1. Otherwise, it returns 0.
The following truth table demonstrates the working of the bitwise OR operator. Let a and b be
two operands that can only take binary values i.e. 1 or 0.
A B a|b

0 0 0
0 1 1

1 0 1

1 1 1
The above table is known as the "Truth Table" for the bitwise OR operator.
Let's look at the bitwise OR operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
____________
00011101 = 29 (In Decimal)

Example 1: Bitwise OR
class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise OR between 12 and 25


result = number1 | number2;
System.out.println(result); // prints 29
}
}

2. Java Bitwise AND Operator


The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it
returns 0.
The following table demonstrates the working of the bitwise AND operator. Let a and b be two
operands that can only take binary values i.e. 1 and 0.
a B a&b

0 0 0

0 1 0

1 0 0

1 1 1
Let's take a look at the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

// Bitwise AND Operation of 12 and 25


00001100
& 00011001
____________
00001000 = 8 (In Decimal)

Example 2: Bitwise AND


class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise AND between 12 and 25


result = number1 & number2;
System.out.println(result); // prints 8
}
}

3. Java Bitwise XOR Operator


The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both
the operands are 0 or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be
two operands that can only take binary values i.e. 1 or 0.
a B a&b

0 0 0

0 1 1

1 0 1

1 1 0
Let's look at the bitwise XOR operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

// Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
____________
00010101 = 21 (In Decimal)

Example 4: Bitwise XOR


class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise XOR between 12 and 25


result = number1 ^ number2;
System.out.println(result); // prints 21
}
}

4. Java Bitwise Complement Operator


The bitwise complement operator is a unary operator (works with only one operand). It is
denoted by ~ .
It changes binary digits 1 to 0 and 0 to 1.
Java Bitwise Complement Operator
It is important to note that the bitwise complement of any integer N is equal to - (N + 1). For
example,
Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36.
Now let's see if we get the correct answer or not.
35 = 00100011 (In Binary)

// using bitwise complement operator


~ 00100011
__________
11011100
In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here,
if we convert the result into decimal we get 220.
However, it is important to note that we cannot directly convert the result into decimal and get
the desired output. This is because the binary result 11011100 is also equivalent to -36.
To understand this we first need to calculate the binary output of -36.

2's Complement
In binary arithmetic, we can calculate the binary negative of an integer using 2's complement.
1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1's complement,
we get the 2's complement of the original number. For example,
// compute the 2's complement of 36
36 = 00100100 (In Binary)

1's complement = 11011011

2's complement:
11011011
+ 1
_________
11011100
Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the
bitwise complement of 35.
Hence, we can say that the bitwise complement of 35 is -(35 + 1) = -36.

Example 3: Bitwise Complement


class Main {
public static void main(String[] args) {

int number = 35, result;

// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Java Shift Operators
There are three types of shift operators in Java:
Signed Left Shift (<<)
Signed Right Shift (>>)
Unsigned Right Shift (>>>)

5. Java Left Shift Operator


It is represented by the symbol <<. It also preserves the leftmost bit (sign bit). It does not
preserve the sign bit.

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.

Representation of 20 in binary is = 00010100

After performing the left shift operator, we get:

a << 3 = 10100000 (last three bits are the filled bits)

a << 3 = 160

Let's check the result by using the formula.

20 << 3

20*23 = 20*8 = 160

Example 2: What will be the result after shifting a<<2. The value of a is -10.

Representation of -10 in binary is = 11110110

a<<2 = 11011000 = -40

Let's check the result by using the formula.

-10 << 3

-10*22 = -10*4 = -40

SignedLeftShiftOperatorExample.java

1. public class SignedLeftShiftOperatorExample


2. {
3. public static void main(String args[])
4. {
5. int x = 12;
6. System.out.println("x<<1 = " + (x << 1));
7. }
8. }

Output

x<<1 = 24

5. Java Signed Right Shift Operator


The signed right shift operator shifts a bit pattern of a number towards the right with a specified
number of positions and fills 0. The operator is denoted by the symbol >>. It also preserves the
leftmost bit (sign bit). If 0 is presented at the leftmost bit, it means the number is positive. If 1 is
presented at the leftmost bit, it means the number is negative.

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.

SignedRightShiftOperatorExample.java

1. public class SignedRightShiftOperatorExample


2. {
3. public static void main(String args[])
4. {
5. int x = 50;
6. System.out.println("x>>2 = " + (x >>2));
7. }
8. }

Output

x>>2 = 12
}

7. Java Unsigned Right Shift Operator


It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note that the
leftmost position after >> depends on the sign bit. It does not preserve the sign bit.

Example: If a=11110000 and b=2, find a>>>b?

a >>> b = 11110000 >>> 2 = 00111100

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.

UnsignedRightShiftOperatorExample.java

1. public class UnsignedRightShiftOperatorExample


2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. System.out.println("x>>>2 = " + (x >>>2));
7. }
8. }

Output

x>>>2 = 5
Java Operator Precedence
Operator precedence determines the order in which the operators in an expression are
evaluated.

int myInt = 12 - 4 * 2;

What will be the value of myInt ? Will it be (12 - 4)*2 , that is, 16 ? Or it will be 12 - (4 *

2) , that is, 4 ?
When two operators share a common operand, 4 in this case, the operator with the
highest precedence is operated first.
In Java, the precedence of * is higher than that of - . Hence, the multiplication is
performed before subtraction, and the value of myInt will be 4.

Operator Precedence Table


The table below lists the precedence of operators in Java; higher it appears in the table,
the higher its precedence.

Java Operator Precedence

Operators Precedence

postfix increment and decrement ++ --

prefix increment and decrement, and unary ++ -- + - ~ !

Multiplicative */%

Additive +-
Shift << >> >>>

Relational < > <= >= instanceof

Equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

Ternary ? :

= += -= *= /= %=
Assignment
&= ^= |= <<= >>= >>>=

Associativity of Operators in Java

If an expression has two operators with similar precedence, the expression is evaluated
according to its associativity (either left to right, or right to left). Let's take an example.

a = b = c;

Here, the value of c is assigned to variable b . Then the value of b is assigned of


variable a . Why? It's because the associativity of = operator is from right to left.
The table below shows the associativity of Java operators along with their associativity.

Java Operator Precedence and Associativity

Operators Precedence Associativity


postfix increment and decrement ++ -- left to right

prefix increment and decrement, and unary ++ -- + - ~ ! 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 exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

Ternary ? : right to left

= += -= *= /= %=
Assignment RIGHT TO LEFT
&= ^= |= <<= >>= >>>=

Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.

String[] array = new String[100];

Syntax:

type var-name[];

OR

type[] var-name;

Example:
int intArray[];
or int[] intArray;

Instantiating an Array in Java


var-name = new type [size];
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in
one

Accessing Java Array Elements using for Loop


Each element in the array is accessed via its index. The index begins with 0 and
ends at (total array size)-1. All the elements of array can be accessed using Java
for Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
Implementation:

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
}
}

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

Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays. A multidimensional array
is created by appending one set of square brackets ([]) per dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

class multiDimensional
{
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++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
Output:
279
361
742

Java Class and Objects


Java is an object-oriented programming language. The core concept of the object-oriented approach
is to break complex problems into smaller objects.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It has
 States: idle, first gear, etc
 Behaviors: braking, accelerating, etc.

Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the
class.
Syntax

class ClassName {
// fields
// methods
}

Here, fields (variables) and methods represent the state and behavior of the object
respectively.
 fields are used to store data

 methods are used to perform some operations

class Bicycle {

// state or field
private int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle , SportsBicycle , TouringBicycle , etc can be considered as objects
of the class.
Creating an Object in Java

Here is how we can create an object of a class.

className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle()

Example: Java Class and Objects

class Lamp {

// stores the value for light


// true if light is on
// false if light is off
boolean isOn;
// method to turn on the light
void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

// method to turnoff the light


void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}

class Main {
public static void main(String[] args) {

// create objects led and halogen


Lamp led = new Lamp();
Lamp halogen = new Lamp();

// turn on the light by


// calling method turnOn()
led.turnOn();

// turn off the light by


// calling method turnOff()
halogen.turnOff();
}
}

Output:

Light on? true


Light on? false

Instance variables in Java


 Instance variables are declared in a class, but outside a method, constructor or any block.
 When space is allocated for an object in the heap, a slot for each instance variable value is
created.
 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
 Instance variables can be declared at the class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors, and block in the class.
 Instance variables have default values. For numbers, the default value is 0, for Booleans it is
false, and for object references it is null. Values can be assigned during the declaration or
within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they should
be called using the fully qualified name. ObjectReference.VariableName.

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object c

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:
Bike is created

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

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.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:

111 Karan
222 Aryan

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior
of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't The method is not provided by the
have any constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or may not be
same as the class name.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

NOTE: In Java, Method Overloading is not possible by changing the return type of the method only.

EXAMPLE:
public class overloadexample
{
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}

public static void main(String args[])


{
overloadexample s = new overloadexample();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output :
30
60
31.0

Constructor Overloading in Java


Overloaded constructor is called based upon the parameters specified when new is executed.

Sometimes there is a need of initializing an object in different ways. This can be done using
constructor overloading.

// Java program to illustrate


// Constructor Overloading
class Box
{
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box()
{
width = height = depth = 0;
}

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

‘this’ reference in Java


‘this’ is a reference variable that refers to the current object.

Following are the ways to use ‘this’ keyword in java :

1. Using ‘this’ keyword to refer current class instance variables


//Java code for using 'this' keyword to
//refer current class instance variables
class Test
{
int a;
int b;

// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test(10, 20);
object.display();
}
}

Output:
a = 10 b = 20

2. Using this() to invoke current class constructor


// Java code for using this() to
// invoke current class constructor
class Test
{
int a;
int b;

//Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}

//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test();
}
}

Output:
Inside parameterized constructor
Inside default constructor

3.Using ‘this’ keyword to invoke current class method


// Java code for using this to invoke current
// class method
class Test {

void display()
{
// calling function show()
this.show();

System.out.println("Inside display function");


}

void show() {
System.out.println("Inside show funcion");
}

public static void main(String args[]) {


Test t1 = new Test();
t1.display();
}
}

Output :
Inside show funcion
Inside display function

Java Garbage Collection


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

How can an object be unreferenced?


There are many ways:

o By nulling the reference

o By assigning a reference to another

o By anonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
new Employee();

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.

public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

You might also like