Java Prograaming - Notes (Unit-1)
Java Prograaming - Notes (Unit-1)
Simple
Java is a simple programming language and easy to understand because it does not contain
complexities. Java contains the same syntax as in C, C++, so the programmers who are switching to Java
will not face any problem in terms of syntax. Secondly, the concept of pointers has been completely
removed from Java which leads to confusion for a programmer and pointers are also vulnerable to
security.
Object-Oriented
Means in Java everything is written in terms of classes and objects. Now, what is an Object?
Object is nothing but a real world entity that can represent any person, place, or thing and can be
distinguished from others. Every object near us has some state and behavior associated with it. For
example, my mobile phone, it is a real world entity and has states like color, model, brand, camera
quality, etc. The main concepts of any Object Oriented Programming language are given below:
Platform Independent
Here platform means a type of operating system and hardware technology.
Java allows programmers to write their program on any machine with any configuration and to execute it
on any other machine having different configurations.
In Java, Java source code is compiled to bytecode and this bytecode is not bound to any
platform. In Fact, this bytecode is only understandable by the Java Virtual Machine which is installed in
our system. What I meant to say is that every operating system has its own version of JVM, which is
capable of reading and converting bytecode to an equivalent machine native language. This reduces the
overhead of programmers writing system specific code. Now programmers write programs only once,
compile it, to generate the bytecode and then export it anywhere.
Portable
The WORA (Write Once Run Anywhere) concept and platform independent feature make Java
portable. Now using the Java programming language, developers can yield the same result on any machine,
by writing code only once. The reason behind this is JVM and bytecode.
Robust
The Java Programming language is robust, which means it is capable of handling unexpected
termination of a program. There are 2 reasons behind this, first, it has a most important and helpful
feature called Exception Handling. If an exception occurs in java code then no harm will happen
whereas, in other low level languages, the program will crash. Another reason why Java is strong lies in
its memory management features. Unlike other low level languages, Java provides a runtime Garbage
collector offered by JVM, which collects all the unused variables.
1
Secure
In today’s era, security is a major concern of every application. As now every device is connected to
each other using the internet and this opens up the possibility of hacking. And our application build
using java also needs some sort of security. So Java also provides security features to the programmers.
Security problems like virus threat; tampering, eavesdropping, and impersonation (act of pretending to
be another person on the internet.) can be handled or minimized using Java.
Virus is a program that is capable of harming our system and this is generally spread with .exe files,
image files, and video files but cannot be spread using a text file and good thing is java bytecode is also a
text file (yes .class file also a text file with non-human readable format).
Interpreted
In programming languages, you have learned that they use either the compiler or interpreter, but
Java programming language uses both a compiler and interpreter. Java programs are compiled to
generate bytecode files then JVM interprets the bytecode file during execution.
Multi-Threaded
Thread is a lightweight and independent sub process of a running program (i.e., process) that shares
resources. And when multiple threads run simultaneously is called multi-threading. In many
applications, you have seen multiple tasks running simultaneously, for example, Google Docs where
while typing text, the spell checks and autocorrect task are running.
JDK (Java Development Kit): JDK is intended for software developers and includes
development tools such as the Java compiler, Javadoc, Jar, and a debugger.
JRE (Java Runtime Environment): JRE contains the parts of the Java libraries required to run
Java programs and is intended for end-users. JRE can be viewed as a subset of JDK.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime
environment in which java bytecode can be executed. JVMs are available for many hardware and
software platforms.
STEPS:
● Download & install Jdk 8 version
● Set environment variable & set path
Class: is a template used to create objects and to define object data types and methods.
For Example: In Java, the “Cat” class is the blueprint from which all individual cats can be
generated that includes all cat characteristics, such as race, fur color, tail length, eyes shape, etc.
A class declaration is made up of the following parts:
● Modifiers
● Class name
2
● Superclass (the name of a class’ parent, if available)
● Implemented Interfaces (if any)
● Appropriate Keywords depending on whether the class extends from a Superclass
and/or implements one or more interface
● Class body within curly brackets {}
Object: an object is an instance of a Java class, meaning it is a copy of a specific class. Java
objects have three primary characteristics: identity, state, and behavior. These characteristics are the
building blocks of any class object.
Identity: The identity of an object is a unique identifier, such as a memory address, ID, or
even a name.
State: The state controls aspects of an object; in the case of describing a fan, you could have
an on, off, low, medium, or high state. State monitors behavior, such as turning a fan on or off, the state
will change when the behavior happens.
Behavior: Object behavior is used to describe what an object can do, such as a fan turning
on or off or changing speeds.
For example: suppose Bicycle is a class
then MountainBike, SportsBike, TouringBike, etc. can be considered as objects of the class.
Creating an Object in Java
className object = new className();
JAVA 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.
token <= identifier | keyword | separator | operator | literal | comment
For example, consider the following code. public
class Demo
{
public static void main(String args[])
{
[Link]("javatpoint");
}
}
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [,],), System,
out, println, javatpoint, etc. are the Java tokens.
DATA-TYPES
As the name suggests, data types specify the type of data that can be stored inside variables in Java.
This means that all variables must be declared before they can be used. Example:
int speed;
Here, speed is a variable, and the data type of the variable is int.
3
There are 8 data types predefined in Java, known as primitive data types.
Boolean type
The Boolean data type has two possible values, either true or false. Default value: false.
They are usually used for true/false conditions.
Byte type
If it's certain that the value of a variable will be within -128 to 127, then it is used instead of int
to save memory.
Default value: 0
Short type
If it's certain that the value of a variable will be within -32768 and 32767, then it is used instead
of other integer data types (int, long).
Default value: 0
int type
The int data type can have values from -231 to 231-1 (32-bit signed two's complement integer).
Default value: 0
Long type
The long data type can have values from -263 to 263-1 (64-bit signed two's complement integer).
Default value: 0
Double type
The double data type is a double-precision 64-bit floating-point. It should never
be used for precise values such as currency.
Default value: 0.0 (0.0d)
Float type
The float data type is a single-precision 32-bit floating-point. Learn more about single-precision
and double-precision floating-point if you are interested.
It should never be used for precise values such as currency. Default value: 0.0
(0.0f)
Char type
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000' (0) and the maximum value of the is '\uffff'.
Default value: '\u0000'
String type
Java also provides support for character strings via [Link] class. Strings in Java are not
primitive types. Instead, they are objects. For example, String myString = "Java
Programming";
Here, myString is an object of the String class.
5. CONSTANTS
A constant is something that in immutable. In Java programming constant is a variable whose
value cannot be changes once it has been assigned.
Constants can be declared using Java's static and final keywords.
The static keyword is used for memory management and final keyword signifies the property that the value
of the variable cannot be changed. It makes the primitive data types immutable.
4
Example: static final float PI = 3.14f;
double [] data;
// allocate memory data =
new double[10];
5
String is basically an object that represents sequence of char values.
An array of characters works same as Java string.
1. When we create a local variable inside a method, constructor, or block, its scope only remains
within the method, block, or constructor.
They are visible only within the method, constructor, or block. As you exit from the method or block, then the
scope of a local variable is destroyed.
2. We cannot access local variables from outside the method, constructor, or block.
3. We cannot change their values from outside of any block. There are
three types of variables in java. They are as:
1. Local variables
1. A variable that is declared and used inside the body of methods, constructors,
or blocks is called local variable in java. It is called so because local variables are not
available for use from outside.
2. We must assign a local variable with a value at the time of creating. If you use a local
variable without initializing a value, you will get a compile- time error like “variable x not
have been initialized”.
3. We cannot use access modifiers with local variables.
4. The local variables are visible only within the declared constructors, methods,
or blocks.
5. A local variable is not equivalent to an instance variable.
6. A local variable cannot be static.
2. Instance variables
1. A variable that is declared inside the class but outside the body of the methods,
constructors, or any blocks is called instance variable in java. They are available for the
entire class methods, constructors, and blocks. It is also called non-static variable because it
is not declared as static.
2. Instance variables are created when an object is created using the keyword
‘new’ and destroyed when the object is destroyed.
3. We can also use access modifiers with instance variables. If we do not specify any
modifiers, the default access modifiers will be used which can be accessed in the same
package only.
4. It is not necessary to initialize the instance variable.
3. Class/Static variables
6
1. A variable which is declared with a static keyword is called static variable in
java. A static variable is also called class variable because it is associated with the class.
2. Static variables are always declared inside the class but outside of any methods,
constructors, or blocks.
3. Static variable will get the memory only once. If anyone changes the value of the
static variable using the class name, it will replace the previous value and display the
changed value. This is because it is constant for every object created.
9. TYPECASTING
The process of converting the value of one data type (int, float , double , etc.)
to another data type is known as typecasting.
7
10. OPERATORS
Operators are symbols that perform operations on variables and values.
For example, is an operator used for addition, is also an operator used
while
for multiplication.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
8
class Main a + b = 17 a -
{ b=7
public static void main(String[] args) a * b = 60 a /
{ b=2a%b
// declare variables int a = =2
12, b = 5;
// addition operator [Link]("a + b = " +
(a + b));
// subtraction operator [Link]("a - b = "
+ (a - b));
// multiplication operator [Link]("a * b =
" + (a * b));
// division operator [Link]("a / b = " +
(a / b));
// modulo operator
[Link]("a % b = " + (a % b));
}
}
9
2. Assignment Operators
Assignment operators are used in Java to assign values to variables.
Example Equivalent to
Operator
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
{
// create variables int a =
4;
int var;
// assign value using = var = a;
[Link]("var using =: " + var);
10
Operator Description Example
// value of a and b
[Link]("a is " + a + " and b is " + b);
// == operator [Link](a == b); //
false
// != operator
[Link](a != b); // true
// > operator
[Link](a > b); // false
// < operator
[Link](a < b); // true
// >= operator
[Link](a >= b); // false
// <= operator
[Link](a <= b); // true
}
}
11
Operator Example Meaning
12
&& (Logical expression1 && true only if both expression1 and
AND) expression2 expression2 are true
class Ma in truefalse
{ static void main(String[] args) operator true true
public [Link]((5 > 3) && (8 > 5)); // true false true
{ [Link]((5 > 3) && (8 < 5)); // false false
// &&
Syste operator
Syste [Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
// || [Link]((5 < 3) || (8 < 5)); // false
Syste
Syste perator
Syste [Link](!(5 == 3)); // true [Link](!(5 > 3)); // false
// ! o
Syste
Syste
}
}
Unary operators are used with only one operand. For example, ++ is a unary operator
that increases the value of a variable by 1.
Operator Meaning
Unary plus: not necessary to use since numbers are positive without using
+
it
13
Logical complement operator: inverts the value of a boolean
!
14
Java Increment & decrement operator class Main Value of a: 12
{ After increment: 13 Value of b:
public static void main(String[] args) 12
{ After decrement: 11
// declare variables int a
= 12, b = 12; int res1,
res2;
// original value [Link]("Value of a: "
+ a);
// increment operator result1 =
++a;
[Link]("After increment: " + res1);
[Link]("Value of b: " + b);
// decrement operator result2 = --b;
[Link]("After decrement: " + rest2);
}
}
~ 00100011
Operator Description
~ Bitwise Complement
15
>> Right Shift
16
Variable = Expression ? expression1: expression2
17
11. OPERATOR PRECEDANCE & ASSOCIATIVITY
Operator precedence determines the order in which the operators in an expression are evaluated.
The table below lists the precedence of operators in Java; higher it appears in the table, the
higher its precedence.
Operators Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
= += -= *= /= %= &=
assignment ^= |= <<= >>=
>>>=
18
class Precedence 2
{
public static void main(String[]
args)
{
int a = 10, b = 5, c = 1, result;
result = a-++c-++b;
[Link](result);
}
}
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).
The table below shows the associativity of Java operators along with their associativity.
19
bitwise inclusive OR | left to right
20
logical AND && left to right
= += -= *= /= %=
assignment &= ^= |= <<= right to left
>>= >>>=
12. EXPRESSION
Expression consists of variables, operators, literals.
Double a = 2.2, b = 3.4, result; result =
a + b - 3.4;
Here in this example, a + b - 3.4 is an expression.
13. MATHEMATICAL FUNCTIONS
Java Mathematical functions are predefined functions which accept values and return the result.
To use mathematical functions, we have to
use Math class in our program.
With the help of mathematical functions we can easily solve a complex equation in our program
abs()
The abs() function returns the absolute value of a
number. The number can be an integer, long, float or
double value. Here Absolute value means number
without negative sign. The absolute value of a number is
min() always positive.
22