IP Notes Java
IP Notes Java
Introduction :
⮚ Java is a general-purpose, class-based, object-oriented programming language
⮚ It is widely used for developing Java applications in laptops, data centers, game consoles,
scientific supercomputers, cell phones, etc.
⮚ Here are some important Java applications:
Features of Java
A list of most important features of Java language is given below
✔ Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used in Java.
✔ Object-Oriented: In Java, everything is in the form of the object. It means it has some
data and behaviour. A program must have at least one class and object.
✔ Robust: Java makes an effort to check error at run time and compile time. It uses a strong
memory management system called garbage collector. Exception handling and garbage
collection features make it strong.
✔ Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines the
access of Java classes.
✔ Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.
✔ High Performance: Java is an interpreted language. Java enables high performance with
the use of the Just-In-Time compiler.
✔ Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the
internet. EJB and RMI are used to create a distributed system.
✔ Multi-threaded: Java also supports multi-threading. It means to handle more than one
job a time.
3 Approach It uses the top- It uses the bottom- It also uses the bottom-up approach.
down approach. up approach.
5 Code The code is The code is The code is executed by the JVM.
Execution executed directly. executed directly.
7 Translator It uses a compiler It also uses a Java uses both compiler and interpreter
only to translate compiler only to and it is also known as an interpreted
the code into translate the code language.
machine language. into machine
language.
10 Source File The source file has The source file has The source file has a .java extension.
Extension a .c extension. a .cpp extension.
Java and Internet: Java is strongly associated with the Internet. Internet users can use Java
to create applet programs and run them locally using a "Java-enabled browser" such as HotJava.
They can also use a Java-enabled browser to download an applet located on a computer
anywhere in the Internet and run it on his local computer. In fact, Java applets have made the
Internet a true extension of the storage system of the local computer.
Java Environment
✔ Java Development Kit
✔ Java Standard Library
✔ Java runtime environment
✔ The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program.
✔ The information includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability of the
program.
✔ To write the statements in the documentation section, we use comments. The comments
may be single-line, multi-line
✔ Single-line Comment: It starts with a pair of forwarding slash (//).
For example://First Java Program
✔ Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols.
For example:
/*It is an example of
multiline comment*/
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.
✔ These tokens are separated by the delimiters. It is useful for compilers to detect errors.
The Java compiler translates these tokens into Java bytecode.Thebytecodes are executed inside
the interpreted Java environment.
Types of Tokens
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords:
These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It is usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character.
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source
code. Java provides five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Implementing a java program
Java is one of the most popular and widely used programming languages and platforms.
Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web
applications.
Steps to Implement Java Program
class Test
{
public static void main(String []args)
{
System.out.println("My First Java Program.");
}
};
To compile the program, we must run the Java compiler (javac), with the name of the source file
on the ―command prompt‖ like as follows
If everything is OK, the ―javac‖ compiler creates a file called ―Test.class‖ containing the byte
code of the program.
● Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
● Compile it by typing ―javac HelloWorld.java‖ in the terminal window.
● Execute (or run) it by typing ―java HelloWorld‖ in the terminal window.
●
classHelloWorld {
publicstaticvoidmain(String args[])
{
System.out.println("Hello, World");
}
}
Output
Hello, World
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
⮚ Loads code
⮚ Verifies code
⮚ Executes code
⮚ Provides runtime environment
JVM provides definitions for the:
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
Constants
Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants. There is an alternative way to define the constants in Java by using the non-access
modifiers static and final.
In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must be
in capital letter.
The syntax to declare a constant is as follows:
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.
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.
Example
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Data Types
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.
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;
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Example:
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive).
Example:
● The float data type is a single-precision 32-bit IEEE 754 floating point
● 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.
Example:
1. float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited
Example:
1. double d1 = 12.3
Example
public class Demo
{
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[])
{
//local variable
int marks = 72;
}
}
Type casting
In Java, type casting is a method or process that converts a data type into another data
type in both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer.
Types of Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down.
Converting a higher data type into a lower one is called narrowing type casting. I
double -> float -> long -> int -> char -> short -> byte
publicclassMain{
publicstaticvoidmain(String[]args){
doublemyDouble=9.78d;
intmyInt=(int)myDouble;
System.out.println(myDouble);
System.out.println(myInt);
}
}
output
9,78
9
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
7. Ternary Operators
8. Special Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
classMain {
publicstaticvoidmain(String[] args) {
// declare variables
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));
}
}
Output:
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2
= 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;
Example:
classMain {
publicstaticvoidmain(String[] args) {
// create variables
int a = 4;
intvar;
Output:
var using =: 4
var using +=: 8
var using *=: 32
Example:
classMain {
publicstaticvoidmain(String[] args) {
// create variables
int a = 7, b = 11;
// 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
}
}
OUTPUT:
a is 7 b is 11
false
true
false
true
false
true
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
|| (Logical true if
expression1 || expression2
OR) either expression1 or expression2 is true
! (Logical
!expression true if expression is false and vice versa
NOT)
Example:
classMain {
publicstaticvoidmain(String[] args) {
// && operator
System.out.println((5>3) && (8>5)); // true
System.out.println((5>3) && (8<5)); // false
// || 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
}
}
OUTPUT:
true
false
true
true
false
true
false
Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that
increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the
value of the operand by 1, while -- decrease it by 1. For example,
intnum = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
Example:
classMain {
publicstaticvoidmain(String[] args) {
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
System.out.println("Value of b: " + b);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
output:
value of a is:12
after increment:13
value of b is:12
after decrement:11
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
OPERATOR MEANING
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
| Binary OR operator
EXAMPLE:
publicclassbitwiseop {
publicstaticvoidmain(String[] args) {
//Variables Definition and Initialization
int num1 =30, num2 =6, num3 =0;
//Bitwise AND
System.out.println("num1 & num2 = "+ (num1 & num2));
//Bitwise OR
System.out.println("num1 | num2 = "+ (num1 | num2) );
}
}
OUTPUT:
num1 & num2 = 6
num1 | num2 = 30
num1 << 1 = 120
num1 >>1 = 7
Ternary Operators:
A ternary operator evaluates the test condition and executes a block of code based on the result
of the condition.
Example:
importjava.util.Scanner;
classMain {
publicstaticvoidmain(String[] args) {
Scanner input = newScanner(System.in);
System.out.println("Enter your marks: ");
double marks = input.nextDouble();
The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the
name ternary operator.
SPECIAL OPERATORS
Java supports some special operators of interest such as instance of operator and
member selection operator(.)
INSTANCE OF OPERATOR
1. The instance of is an object reference operator and returns true if the object on the
left-hand side is an instances if the class given in the right-hand side.
2.This operator allows us to determine whether the object belongs to a particulars class
or not.
Example:
Person instance of student
Is true if the object person belongs to the class student : otherwise it is false.
DOT OPERATOR
The dot operator (.) is used to access the instance variables and methods of class objects,
Examples
Personl.age # Reference to the variable stage
Personal.salary # Reference to the method salary( )
Decision Making
Decision making in Java executes a particular segment of code based on the result of a
booleancondition.It is important because conditions define the flow of programs and the output
of a particular program.
The decision making principles in Java chiefly consist of if else statements, continue, break and
switch statements. It decides the flow of the program control during the execution of the
program.
1. if
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump-break,continue,return
1. If Statement in Java
Java if statement is the simplest decision making statement. It encompasses a boolean condition
followed by a scope of code which is executed only when the condition evaluates to true.
Syntax:
if(condition)
{
//code to be executed
}
Example
packagecom.dataflair.decisionmaking;
public class IfStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlair";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
}
}
Output
Understanding if statements.
The string is DataFlair
If else statement in Java
This pair of keywords is used to divide a program to be executed into two parts, one being the
code to be executed if the condition evaluates to true and the other one to be executed if the
value is false.
Syntax
if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}
EXAMPLE
packagecom.dataflair.decsionmaking;
public class IfElseStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlairJava";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
else {
System.out.println("The string is not DataFlair");
}
}
}
Output
The string is not DataFlair
Nested if Statements in Java
If the condition of the outer if statement evaluates to true then the inner if statement is evaluated.
Nested if’s are important if we have to declare extended conditions to a previous condition
Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
EXAMPLE
packagecom.dataflair.decisionmaking;
public class IfNestedStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlair";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
if (s.charAt(0) == 'D') {
System.out.println("The first character is D! ");
}
}
else {
System.out.println("The string is not DataFlair");
}
}
}
Output
Understanding if statements.
The string is DataFlair
The first character is D!
if-else-if Statements in Java
These statements are similar to the if else statements . The only difference lies in the fact that
each of the else statements can be paired with a different if condition statement. This renders the
ladder as a multiple choice option for the user.
Syntax:
if
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else
{
//code to be executed
}
EXAMPLE
packagecom.dataflair.decisionmaking;
public class IfElseIfStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlairPython";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
else if (s.equals("DataFlairJava")) {
System.out.println("The string is DataFlair and course is Java");
}
else if (s.equals("DataFlairPython")) {
System.out.println("The string is DataFlair and the course is Python");
}
}
}
Output
Understanding if statements.
The string is DataFlair and the course is Python
Switch Statement in Java
● This saves the hassle of writing else if for every different option.
● It branches the flow of the program to multiple points as and when required or specified by
the conditions.
● It bases the flow of the program based on the output of the expression.
Syntax:
switch(expression)
{
case <value1>:
//code to be executed
break;
case <value2>:
//code to be executed
break;
default:
//code to be defaultly executed
}
EXAMPLE
● package com.dataflair.decisionmaking;
importjava.util. * ;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.println("You have two options of courses at DataFlair");
System.out.println("1.Java");
System.out.println("2.Python");
System.out.println("Enter the number of course:");
intch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Congrats you have chosen Java!");
break;
case 2:
System.out.println("Congrats you have chosen Python!");
break;
default:
System.out.println("Wrong input!");
break;
}
}
}
Output
You have two options of courses at DataFlair
1.Java
2.Python
Enter the number of course:
2
Congrats you have chosen Python!
The labeled and unlabeled break statement are the two forms of break statement in Java. The
break statement is used for terminating a loop based on a certain condition.
int j;
boolean foundName = false;
Output:
syntax.
label:
for (int; testExpression; update){
if(condition to break){
break label;
}
}
}
EXAMPLE
class LabeledBreakExample {
public static void main(String[] args) {
int j, k;
outerMost:
for(j=1; j<5; j++) {
innerMost:
for(k=1; k<3; k++ ) {
System.out.println("j = " + j + " and k = " +k);
if ( j == 3)
break outerMost;
}
}
}
}
Output:
● The continue statement is another branching statement used to immediately jump to the
next iteration of the loop.
● We can use the continue statement for any control flow statements like for, while,
and do-while.
Syntax
control-flow-statement;
continue;
Example
The return statement is also a branching statement, which allows us to explicitly return value
from a method. The return statement exits us from the calling method and passes the control flow
to where the calling method is invoked.
Syntax
return value;
Or,
return;
Example
class ReturnExampleWithoutValue {
void increment(int number)
{
if (number < 10)
return;
number++;
System.out.println(number);
}
public static void main(String[] args)
{
ReturnExampleWithoutValue obj = new ReturnExampleWithoutValue();
obj.increment(4);
System.out.println("In main");
obj.increment(12);
System.out.println("In main");
}
}
Output:
Loops in Java
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
There are three types of for loops in Java.
for(initialization;condition;increment/decrement)
{
Statement(s);
}
EXAMPLE
Class ForLoopDemo
{
public static void main(String args[])
{
for(int num = 1; num <= 5; num++)
{
System.out.println(num);
}
}
}
Output:
1
2
3
4
5
While Loop in Java:
The while statement or loop continually executes a block of statements while a particular
condition is true. The while statement continues testing the expression and executing its block
until the expression evaluates to false. The syntax to use while loop in java is given below.
SYNTAX
while(condition)
{
Statement(s);
}
EXAMPLE
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;
{
System.out.println("Value of x:" + x);
x++;
}
}
}
Output:
value of x:1
Value of x:2
Value of x:3
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top.
SYNTAX:
do{
Statement(s);
}
while(condition);
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Output: Value of x: 21
Core/Elective/Supportive Core : 4 6 0 0 4