Java Language
Java Language
It is the most popular programming model among developers. It is well suited for programs that
are large, complex, and actively updated or maintained. It simplifies software development and
maintenance by providing major concepts such as abstraction, inheritance, polymorphism,
and encapsulation. These core concepts support OOP.
Pillars of OOP
The major concepts that we have discussed above are known as pillars of OOP. There
are four pillars on which OOP rests.
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
2. Inheritance
3. Abstraction
4. Polymorphism
Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity.
It protects data and functions from outside interference and misuse. Therefore, it also provides
security. A class is the best example of encapsulation.
Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class) into a
newly created class (child class). It is known as inheritance. It provides code reusability.
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs.. Poly means many
and morphs means forms. It allows us to create methods with the same name but different
method signatures. It allows the developer to create clean, sensible, readable, and resilient code.
The above figure best describes the concepts of polymorphism. A person plays an employee role
in the office, father and husband role in the home.
What is Java?
Java is a programming language and a platform.. Java is a high level, robust, object-oriented
object
and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his tea
teamm changed the name from Oak to
Java.
Importance of Java
One of the essential reasonss for Java's popularity is the cross-platform
platform compatible and built-in
built
security. Java program can run on any machine with a Java Runtime Environment (JRE)
installed. Programs operate on various computers. Java is used by many banks, manufacturers,
insurance organizations, utilities, and retailers. It is the reason that major industries ruled by
Java.
In this section, we will discuss what makes Java so popular and what are the major industries
that uses Java programming language.
The following features make the Java programming language special and popular.
o Simple to use
o Built-in Security
o Open Source
o Robust API
o Strong community
o Excellent documentation
o Versatility
Features of Java
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
Java buzzwords.
A list of the most important features of the Java language is given below.
Java Industry Usage:
Java is used in almost all fields, be it financial, e-commerce, enterprise, mobile, distributed, or
big data applications.. For example, most of the financial software used by big players like
Citigroup, Barclays, etc. is Java--based. E-commerce giant Amazon uses Java-based
based applications
for its operations
1: Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes the source
code into a machine-independent
independent encoding, known as Bytecode. The content of each class
contained in the source file is stored in a separate ‘.class’ file.
2: Execution
The class files generated by the compiler are independent of the machine or the OS, which
allows them to be run on any system. To run, the main class file (the class that contains the
method main) is passed to the JVM and then goes through three main stages before the final
machine code is executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun
Microsystems
JVM (Java Virtual Machine)
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).
It is:
What it does
o Loads code
o Verifies code
o Executes code
o 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.
OOP-Unit-2 Notes
Variable
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.
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
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.
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 to understand the types of variables in java
public class A
{
static int m=500;//static variable
void method()
{
int n=10;//local variable
}
public static void main(String args[])
{
int data=40;//instance variable
}
}//end of class
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 and builtin api methods which returns a value or object.
Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance
variable. The general scope of an instance variable is throughout the class except in static
methods. The lifetime of an instance variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is known
as a class variable. The general scope of a class variable is throughout the class and the lifetime
of a class variable is until the end of the program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local variables
including the parameters in a method. Scope of a local variable is within the block in which it is
declared and the lifetime of a local variable is until the control leaves the block in which it is
declared.
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.
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.
Example:
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.
Example:
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.
Example:
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
Example:
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.
Example: float f1 = 234.5f
Example:
double d1 = 12.3
Example:
Type casting
Convert a value from one data type to another data type is known as type casting.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
WideningTypeCastingExample.java
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java
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 Assignment Operator.
o negating an expression
The bitwise & operator always checks both conditions whether first condition is true or false.
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.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean
expression and control the program flow depending upon the result of the
condition provided. There are two types of decision-making statements in
Java, i.e., If statement and switch statement.
1) If Statement:
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. if-else-if ladder
4. 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.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the
java code.
Student.java
2) if-else statement
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Student.java
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.
Program that finds greatest among three number
class Gr
int a=2,b=3,c=5;
if(a>b)
if(a>c)
System.out.println(“a is greatest”);
else
System.out.println(“c is greatest”);
else
if(b>c)
System.out.println(“b is greatest”);
else
System.out.println(“c is greatest”);
}
}
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
Calculation.java
Calculation.java
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Calculation .java
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.
Consider the following example to understand the functioning of the do-while
do
loop in Java.
Calculation.java
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.
BreakExample.java
1. Write a program that takes 3 subject marks as an input, and print percentage.
Also print the grade according to following criteria
Percentage >=90 ----------- <=100
Print “A grade”
Percentage >=70 ----------- <90
Print “B grade”
Percentage >=40 ----------- <70
Print “C grade”
Otherwise
Print Fail
Solution:
import java.uti.*;
class Grade
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
float a,b,c,per;
System.out.println("Enter three subject marks");
a=sc.nextFloat();
b=sc.nextFloat();
c=sc.nextFloat();
per=(a+b+c)/3;
System.out.println("Percentage="+per);
if(per>=90 && per<=100)
System.out.println("A Grade");
if(per>=70 && per<90)
System.out.println("B Grade");
if(per>=40 && per<70)
System.out.println("C Grade");
else
System.out.println("Fail");
}
}
import java.uti.*;
class Prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,rev=0,t;
System.out.println("Enter Numer");
n=sc.nextInt();
t=n;
while(t!=0)
{
rev=rev*10+t%10;
t=t/10;
}
System.out.println("Reversed Number="+rev);
if(rev==n)
System.out.println("Number is Palindrome");
else
System.out.println(""Number is not Palindrome");
}
}
OOP-Unit-4-Notes
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
o Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
o Random access: We can get any data located at an index position.
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.
Single Dimensional Array in Java is basically a linear array that allows its user
to store multiple values of the same data type. It's a collection of data that
stores elements of the same type in a sequentially allocated space in memory.
import java.util.*;
class Search
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,I;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int el,f=0;
System.out.println("Enter Element to be searched");
el=sc.nextInt();
for(i=0;i<n;i++)
{
if(el==a[i])
{
f=1;
break;
}
if(f==0)
System.out.println("Element not found");
else
System.out.println("Element found");
}
}
import java.util.*;
class Sort
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,i,sum=0;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int t,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=c;
}
}
}
System.out.println("Sorted Array ");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Multi Dimensional Array in Java
import java.util.*;
class TwoDArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int r,c,i,j;
System.out.println("Enter row and column");
r=sc.nextInt();
c=sc.nextInt();
int a[][]=new int[r][c];
System.out.println("Enter Array Elements");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=sc.nextInt();
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println(" ");
}
}
}
OOP-Unit-5 Notes
What is a class in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Object Definitions:
Example:
class A
{
int s=2;
public static void main(String args[])
{
A a=new A(); //object creation
System.out.println(a.s)
}
}
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=10;
s1.name="Arshad";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Method in Java
A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We
do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use these
methods just by calling them in the program at any point
Example:
import java.util.*;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int n=scan.nextInt();
//method calling
checkEvenOdd(n);
}
//user defined method
public static void checkEvenOdd(int n)
{
//method body
if(n%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A
method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
Method Overloading:
// Java program to demonstrate working of method
// overloading in Java
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Java constructor
In Java, a constructor is a block of codes similar to the method. It iscalled
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. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
Class Student{
1.int rollno;
2.String name;
3.float fee;
4.Student(int rollno,String name,float fee){
5.rollno=rollno; //this.rollno=rollno;
6.name=name; //this.name=name;
7.fee=fee;//this.fee=fee
8.}
9.void display(){System.out.println(rollno+" "+name+" "+fee);}
10.}
11.class TestThis1{
12.public static void main(String args[]){
13.Student s1=new Student(111,"ankit",5000f);
14.Student s2=new Student(112,"sumit",6000f);
15.s1.display();
16.s2.display();
17.}}
Class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A(10);
}}
OUTPUT: hello a
10
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A();
}}
OUTPUT: 5
hello a
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change the
value of it.
1. variable
2. method
3. class
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //Compile time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
2) Java final method
If you make any method as final, you cannot override it.
We use inner classes to logically group classes and interfaces in one place to
be more readable and maintainable.
Additionally, it can access all the members of the outer class, including private
data members and methods.
Example:
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Garbage Collection
3) By anonymous object:
1. New Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class.
void finalize(){}
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.