UNIT 1
Object
Any entity that has state and behavior is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
An Object can be defined as an instance of a class. An object contains an
address and takes up some space in memory. Objects can communicate
without knowing the details of each other's data or code. The only
necessary thing is the type of message accepted and the type of response
returned by the objects.
Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.
ADVERTISEMENT
ADVERTISEMENT
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks
meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.
ADVERTISEMENT
ADVERTISEMENT
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different
medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
Benefits of OOPs
1. Modularity
2. Reusability
3. Better Code Organization
4. Maintenance
5. Collaborative Development
6. Code reuse
7. Scalability
8. Real-World Modeling
Application of OOPs
1. Real Time Systems
2. Client Server System
3. Hypertext and Hypermedia
4. Object Oriented Database
5. Neural Networks and Parallel Programming
6. AI Expert Systems
7. Simulation and Modeling System
8. Office Automation Systems
9. CIM/CAD/CAM Systems
10. Computer Aided Designs
Genesis of Java
The history of Java starts with the Green Team. Java team members
(also known as Green Team), initiated this project to develop a
language for digital devices such as set-top boxes, televisions, etc.
However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-Oriented, Interpreted,
and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members
started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc. Following are given significant
points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in
electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt.
4) After that, it was called Oak and was developed as a part of the
Green project.
JAVA Byte Code
Byte Code can be defined as an intermediate code generated by
the compiler after the compilation of source code(JAVA Program).
This intermediate code makes Java a platform-independent
language.
How is Byte Code generated?
Compiler converts the source code or the Java program into the
Byte Code(or machine code), and secondly, the Interpreter
executes the byte code on the system. The Interpreter can also
be called JVM(Java Virtual Machine). The byte code is the
common piece between the compiler(which creates it) and the
Interpreter (which runs it).
Example:
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
System.out.println("GFG!");
}
}
Output
GFG!
The above-written code is called JAVA source code.
The compiler compiles the source code.
Finally, Interpreter executes the compiled source code.
Whenever we write any program, it is not written in
machine code. We write it in a high-level language like
JAVA, C++, Python, etc. But the computer understands only
the machine code. So when we execute our program, it is
first converted into machine code or Byte code by the
compiler and then executed by the Interpreter.
This intermediate code or the byte can run on any
platform making, JAVA a platform-independent
language.
JAVA BUZZWORDS
Java buzzwords are the keywords that describe the features
and characteristics of the Java programming
language .Some of the Java buzzwords are :
12 12
Simple: Java is easy to learn and use for a professional programmer.
Object-Oriented: Java is a true object-oriented programming
language that supports encapsulation, inheritance, and
polymorphism.
Distributed: Java is designed to create distributed applications on
networks.
Platform-Independent: Java is compiled into bytecode that can run
on any Java Virtual Machine (JVM) regardless of the underlying
hardware and operating system.
Garbage Collection: Java automatically manages the memory
allocation and deallocation for objects, freeing the programmer from
manual memory management.
Lexical Issues in Java
The clarity and consistency of Java, one of the most widely used
computer languages, are well known. To build clear, error-free code,
developers must be aware of the language's unique collection of lexical
difficulties, which are present in every language. Lexical issues in
Java concern how the language structures and interprets source code
at the lexical level, which relates to how the language reads and
interprets specific characters and tokens in code. We shall examine
some typical lexical problems in Java in this post and offer mitigation
techniques.
Reserved Keywords and Identifiers
Java features a list of reserved terms with predetermined meanings
that are not allowed to be used as identifiers (variable, class, or
method names). Compilation faults will be produced if reserved
keywords are used as identifiers. The phrases "public," "static," "class,"
and "int" are some frequently used reserved keywords in Java.
Solution: To get around this problem, give your variables, classes, and
methods names that are relevant and descriptive that do not conflict
with reserved terms. Use an Integrated Development Environment
(IDE) that offers code assistance if you're unsure whether a word is a
reserved keyword or reference the Java documentation.
Case Sensitivity
The identifiers "myVariable" and "myvariable" are processed differently
in Java because of the case-sensitivity of the language. It can be more
difficult to read and maintain your code if the cases are mixed together
inconsistently and can result in subtle problems.
Solution: Stick to a consistent naming convention throughout your
software, such as camelCase or snake_case. By doing so, case-related
errors are reduced and code readability is improved.
Comments and Whitespace
Although they have no bearing on how your Java program runs,
comments and whitespace are quite important for making the code
more readable. Ignoring these details could make it more difficult to
maintain or share your code with others.
Solution: Use comments to explain and set the stage for your code. To
avoid using too many comments, use names for variables and methods
that make sense. To improve readability, properly indent your code
and keep a consistent coding style.
String Escapes
Special characters like newline ('n') and double quotes ('"') may be
required when creating strings in Java. Syntax issues can occur when
using these characters without the correct escapes.
Solution: For a workaround, represent special characters in strings
using escape sequences. Use """ for a double quotation inside of a
string, for instance, and "n" for a newline character. By doing this, you
can be certain that the Java compiler will understand these characters
properly.
Incorrect Operators and Punctuation
Java utilizes a number of operators and punctuation marks, such as "+"
for addition, "-" for subtraction, and ";" to end statements. A program
may behave unexpectedly if these are misused or omitted, leading to
compilation issues.
ADVERTISEMENT
Solution: Understand the usage conventions and operator precedence
of Java. In order to correctly end statements, pay particular attention to
semicolons. Make expressions clearer and the right evaluation order
guaranteed by using parentheses.
Improperly Closed Brackets and Parentheses
Java syntax errors are frequently caused by mismatched or poorly
closed brackets ('' and '') and parentheses ('(' and ')').
Data Types in Java
Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories in
which data types are segregated
1. Primitive Data Type: such as Boolean, char, int, short, byte, long,
float, and double
2. Non-Primitive Data Type or Object Data type: such as String,
Array, etc.
Understanding and effectively using these data types is crucial for
writing efficient and error-free Java code. If you’re aiming to master
Java, exploring detailed resources or Java Programming Course can
help you gain a strong command over data types and other essential
Java concepts
Primitive Data Types in Java
Primitive data are only single values and have no special capabilities.
There are 8 primitive data types. They are depicted below in tabular
format below as follows:
ta 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
Non-Primitive Data Type or Reference Data Types
The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value
directly in memory. They are strings,arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to
hold a sequence of characters in a single variable whereas, a character
array is a collection of separate char-type entities. Unlike C/C++, Java
strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2.Array
An Array is a group of like-typed variables that are referred to by a
common name. Arrays in Java work differently than they do in C/C++.
The following are some important points about Java arrays.
In Java, all arrays are dynamically allocated. (discussed below)
Since arrays are objects in Java, we can find their length using
member length. This is different from C/C++ where we find length
using size.
A Java array variable can also be declared like other variables with []
after the data type.
The variables in the array are ordered and each has an index
beginning with 0.
Java array can also be used as a static field, a local variable, or a
method parameter.
The size of an array must be specified by an int value and not long
or short.
The direct superclass of an array type is Object.
Variables in Java
Java 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.
Variables in Java are 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.
How to Declare Variables in Java?
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be
assigned values in two ways:
Variable Initialization
Assigning value by taking input
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Types of Variables in Java
Now let us discuss different types of variables which are listed
as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a
local variable.
The Local variable is created at the time of declaration and
destroyed after exiting from the block or when the call returns from
the function.
The scope of these variables exists only within the block in which
the variables are declared, i.e., we can access these variables only
within that block.
Initialization of the local variable is mandatory before using it in the
defined scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class
outside of any method, constructor, or block.
As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier, then the default
access specifier will be used.
Initialization of an instance variable is not mandatory. Its default
value is dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes
like Integer it is null, etc.
Instance variables can be accessed only by creating objects.
We initialize instance variables using constructors while creating an
object. We can also use instance blocks to initialize the instance
variables.
3. Static Variables
Static variables are also known as class variables.
These variables are declared similarly to instance variables. The
difference is that static variables are declared using the static
keyword within a class outside of any method, constructor, or block.
Unlike instance variables, we can only have one copy of a static
variable per class, irrespective of how many objects we create.
Static variables are created at the start of program execution and
destroyed automatically when execution ends.
Initialization of a static variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null,
for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.
If we access a static variable like an instance variable (through an
object), the compiler will show a warning message, which won’t halt
the program. The compiler will replace the object name with the
class name automatically.
If we access a static variable without the class name, the compiler
will automatically append the class name. But for accessing the
static variable of a different class, we must mention the class name
as 2 different classes might have a static variable with the same
name.
Static variables cannot be declared locally inside an instance
method.
Static blocks can be used to initialize static variables.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence
Operator Category Precedence
Type
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise ^
exclusive OR
bitwise |
inclusive OR
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators
are used to perform various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
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
}}
Output:
10
12
12
10
Java Unary Operator
Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21
Java Unary Operator
Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which star
ts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts fro
m 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical
operations.
Java Arithmetic Operator
Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
50
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a
value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right
operand.
Java Right Shift Operator Example
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
}}
Output:
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the
first condition is false. It checks the second condition only if the first
one is true.
The bitwise & operator always checks both conditions whether first
condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
1. }}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one
is false.
The bitwise | operator always checks both conditions whether first
condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-
else statement and used a lot in Java programming. It is the only
conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Java Assignment Operator
Java assignment operator is one of the most common operators. It is
used to assign the value on its right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
ADVERTISEMENT
ADVERTISEMENT
Output:
13
9
18
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20