Java Prograaming (22412)- Notes (Unit-1)
Java Prograaming (22412)- Notes (Unit-1)
1. JAVA FEATURES
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.
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
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 {}
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[])
{
System.out.println("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.
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 java.lang.String 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.
Example: static final float PI = 3.14f;
6. DYNAMIC INITIALIZATION
If any variable is not assigned with value at compile-time and assigned at
run time is called dynamic initialization of a variable.
Basically, this is achieved through constructors, setter methods, normal
methods which return a value or object.
public class First{
public static void main( String args[] )
{
int r;
double circumference;
r= 6; //Initialization
circumference = 2 * Math.PI * r; //Dynamic Initialization
System.out.println(" circumference= " + circumference);
}
}
public class First
{
public static void main( String args[] )
{
int [] array = {2,5,7,8,9, 10}; //array initialization
or
int [] array;
array = new int[] {2, 5, 7, 8, 9, 10};
for (int i = 0; i <= 5; i++)
{
System.out.println("Array= " + array[i]);
}
}
}
Here, the above array cannot store more than 100 names. The number of values in
a Java array is always fixed.
// declare an array
double [] data;
// allocate memory
data = new double[10];
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
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.
1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on
variables and data.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
class Main a + b = 17
{ a -b=7
public static void main(String[] args) a * b = 60
{ a /b=2
// declare variables a %b=2
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
2. Assignment Operators
= 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;
3. Relational Operators
operands.
// 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
}
}
4. Logical Operators
// || 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
}
}
5. Unary Operators
Unary operators are used with only one operand. For example, ++ is a
Operator Meaning
6. Bitwise Operators
bits.
Bitwise complement Operation of 35
35 = 00100011 (In Binary)
~ 00100011
________
11011100 = 220 (In decimal)
Here, ~ is a bitwise operator. It inverts the value of each bit
(0 to 1 and 1 to 0)
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
7. instanceof Operator
8. Ternary Operator
else statement.
Variable = Expression ? expression1: expression2
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
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 &= ^= |= <<= >>=
>>>=
class Precedence 2
{
public static void main(String[]
args)
{
int a = 10, b = 5, c = 1, result;
result = a-++c-++b;
System.out.println(result);
}
}
= += -= *= /= %=
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 always positive.
min()
The min() function returns the smallest among two numbers.
The number can be an integer, long, float or double value.
max()
The max() function returns the greater among two numbers.
The number can be an integer, long, float or double value.
sqrt()
The sqrt() function returns the square root of a positive number.
Remember that square root of a negative cannot be calculated.
ceil()
The ceil() function returns the nearest integer number greater
than the number passed as argument.
floor()
The floor() function returns the nearest integer number less
than the number passed as argument.
pow() The pow() function is used to computes the power of a number.