Java NOTES IA-1-1
Java NOTES IA-1-1
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Object
o 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.
o 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.
o 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.
Class
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
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.
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.
//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}
Different lexical issues in Java:
White space
free-form means we can write total code in a single line. like tab, space.
Identifiers
names used to classes, behaviors, variables.
uses numbers, dollar symbol, underscore, letters.
valid- Method, Addition1, run_any, $method.
invalid- 123.
Literals
A value of a corresponding variable.
example: 12,123.0.'r',"String".
Comments
the content ignored by the compiler which explains the operation of the
program.
single line comment- // for line by line description.
multi line comment- /* */ for 3-4 lines description.
Documentation comment- in html document like /** */.
Separators
terminate the statements.
()- Parentheses--- to arguments, control statements like if, while, for.
[]-Brackets---- to declare size of arrays.
{}-Braces--- to define methods ,classes, automatic initialization of arrays.
,- comma--- to declare variables, in for loop.
;- semicolon---terminates the statements.
.- Period-- for packages, sub packages, references to class.
::- Colons--- Used to create a method or constructor reference
Keywords
totally 50 are there which are cannot be used as variables, class names,
method names.
Libraries
Java has built in class libraries that contain methods for IO operations, GUI,
Networking, String handling etc which provides greater functionality to java.
DATA TYPES:
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. The Boolean with uppercase B is a wrapper class
for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String,
Array, etc.
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:
Descripti Defau Siz Example
Type on lt e Literals Range of values
boolea true or 8
false true, false true, false
n false bits
twos-
8
compleme 0 (none) -128 to 127
bits
byte nt integer
‘a’, characters
Unicode \u000 16 ‘\u0041’, representation of
character 0 bits ‘\101’, ‘\\’, ASCII values
char ‘\’, ‘\n’, ‘β’ 0 to 255
twos-
16
compleme 0 (none) -32,768 to 32,767
bits
short nt integer
twos- -2,147,483,648
32
compleme 0 -2,-1,0,1,2 to
bits
int nt intger 2,147,483,647
-
9,223,372,036,854,775,
twos- -2L,-
64 808
compleme 0 1L,0L,1L,2
bits to
nt integer L
9,223,372,036,854,775,
long 807
1.23456e30
IEEE 754
64 0d , -
floating 0.0 upto 16 decimal digits
bits 123456e-
point
double 300d , 1e1d
Non-Primitive (Reference) Data Types
The Non-Primitive (Reference) Data Types will contain a memory address
of variable values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities
2. Class
A class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access. Refer
to access specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized
by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-
life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State : It is represented by the attributes of an object. It also reflects
the properties of an object.
2. Behavior : It is represented by the methods of an object. It also
reflects the response of an object to other objects.
3. Identity : It gives a unique name to an object and enables one object
to interact with other objects.
4. 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.
Java Arrays:
Normally, an array is a collection of similar type of elements which has
contiguous memory location.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
Advantages
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
In such case, data is stored in row and column based index (also known as matrix
form).
Output:
123
245
445
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.
multiplicative */%
Arithmetic
additive +-
bitwise inclusive OR |
Ternary ternary ?:
= += -= *= /= %= &= ^= |=
Assignment assignment
<<= >>= >>>=
15
5
50
2
0
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.
14
16
13
9
18
9
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.
Syntax:
variable = Expression1 ? Expression2: Expression3
2
Another Example:
Java Relational Operators are a bunch of binary operators used to check for
relations between two operands, including equality, greater than, less than, etc.
They return a boolean result after the comparison and are extensively used in
looping statements as well as conditional if-else statements and so on. The
general format of representing relational operator is:
Syntax:
variable1 relation_operator variable2
Let us look at each one of the relational operators in Java:
Operator 1: ‘Equal to’ operator (==)
This operator is used to check whether the two given operands are equal or
not. The operator returns true if the operand at the left-hand side is equal to the
right-hand side, else false.
Syntax:
var1 == var2
Example:
// Java Program to Illustrate equal to Operator
// Main class
class GFG {
// Main class
class GFG {
// Main class
class GFG {
// Main class
class GFG {
// Main class
class GFG {
// Main class
class GFG {
program that implements all relational operators in Java for user input:
import java.util.Scanner;
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the
If statement gives a Boolean value, either true or false. In Java, there are four
types of if-statements given below.
1. Simple if statement
2. if-else statement
3. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of code
if the expression evaluates to true.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the
java code.
Student.java
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block
of code, i.e., else block. The else block is executed if the condition of the if-block
is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else {
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
x + y is greater than 20
3.Nested if-statement
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
o The case variables can be int, short, byte, char, or enumeration. String type
is also supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value
of expression. It is optional.
o Break statement terminates the switch block when the condition is
satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will
be of the same type as the variable. However, it will also be a constant
value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value. The
switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of code.
We use the for loop only when we exactly know the number of times, we want to
execute the block of code.
The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
The do-while loop checks the condition at the end of the loop after executing the
loop statements. When the number of iteration is not known and we have to
execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with
the for loop.
}
Output:
0
1
2
3
4
5
6
Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Constructors in Java:
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.
Every time an object is created using the new() keyword, at least one constructor
is called.
1. <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 creation.
//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
111 Karan
222 Aryan
There are many differences between constructors and methods. They are given
below.
A constructor is used to initialize the state A method is used to expose the behavior of
of an object. an object.
A constructor must not have a return type. A method must have a return type.
The constructor name must be same as the The method name may or may not be same
class name. as the class name.