0% found this document useful (0 votes)
22 views17 pages

Java Mynotes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

Java Variables

A variable is a container which holds the value while the Java program is executed.
A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java:
local, instance and static.

A variable is the name of a reserved area allocated in memory. In other words, it is


a name of the memory location. It is a combination of "vary + able" which means
its value can be changed.

There are two types of data types in Java: primitive and non-primitive.

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.
A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not


shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local.


You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.

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:

 boolean data type: The Boolean data type is used to store only two possible
values: true and false. This data type is used for simple flags that track
true/false conditions. The Boolean data type specifies one bit of information,
but its "size" can't be defined precisely.

 byte data type : The byte data type is an example of primitive data type. It
isan 8-bit signed two's complement integer. Its value-range lies between -
128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127. Its default value is 0.The byte data type is used to save memory in large
arrays where the memory savings is most required. It saves space because a
byte is 4 times smaller than an integer. It can also be used in place of "int"
data type.
 char data type : The char data type is a single 16-bit Unicode character. Its
value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The
char data type is used to store characters.

 short data type : The short data type is a 16-bit signed two's complement
integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is
0.The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
 Int data type : The int data type is a 32-bit signed two's complement
integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is
0.The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
 long data type : The long data type is a 64-bit two's complement integer. Its
value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.
 float data type : The float data type is a single-precision 32-bit IEEE 754
floating point. Its value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values,
such as currency. Its default value is 0.0F.
 double data type : The double data type is a double-precision 64-bit IEEE
754 floating point. Its value range is unlimited. The double data type is
generally used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default value is
0.0d.
Q) Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system. To get detail explanation about Unicode visit next
page.

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:

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 Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication,


and division. They act as basic mathematical operations.

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 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 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.

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.

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 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.

Operator Type Category Precedence


Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
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 Keywords
Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
Class Definition
In object-oriented programming, a class is a basic building block. It can be defined
as template that describes the data and behavior associated with the class
instantiation. Instantiating is a class is to create an object (variable) of that class
that can be used to access the member variables and methods of the class.

A class can also be called a logical template to create the objects that share
common properties and methods.

For example, an Employee class may contain all the employee details in the form
of variables and methods. If the class is instantiated i.e. if an object of the class is
created (say e1), we can access all the methods or properties of the class.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by
convention).
4. Super class (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.
5. Interfaces (if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
6. Body: The class body surrounded by braces, { }.

EXAMPLE:

public class Main {

int x = 5;

Create an Object
In Java, an object is created from a class. o create an object of Main, specify the
class name, followed by the object name, and use the keyword new:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

}
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.

 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.


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

Syntax of default constructor:


<class_name>(){}
EXAMPLE:

class Bike1{

Bike1(){System.out.println("Bike is created");}

public static void main(String args[]){

Bike1 b=new Bike1();

Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

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.

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.

class Student4{

int id;

String name;

Student4(int i,String n){

id = i;

name = n;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

s1.display();

s2.display();

Output:
111 Karan

222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor


with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types.

Example of Constructor Overloading


class Student5{

int id;

String name;

int age;

//creating two arg constructor

Student5(int i,String n){

id = i;

name = n;

//creating three arg constructor

Student5(int i,String n,int a){

id = i;

name = n;

age=a;
}

void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){

Student5 s1 = new Student5(111,"Karan");

Student5 s2 = new Student5(222,"Aryan",25);

s1.display();

s2.display();

Output: 111 Karan 0

222 Aryan 25
Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a
value).

Q) Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform
any operation in the constructor as you perform in the method.

Q) Is there Constructor class in Java?

Yes.
Q) What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information
of a constructor in the class. It is found in the java.lang.reflect package.

You might also like