0% found this document useful (0 votes)
27 views49 pages

Java

The document discusses Java programming language. It covers topics like Java features, bytecode, JDK, JRE, JVM, variables, data types, keywords, control statements, loops, casting etc. It provides details about each topic with examples.

Uploaded by

Prashant
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
Download as rtf, pdf, or txt
0% found this document useful (0 votes)
27 views49 pages

Java

The document discusses Java programming language. It covers topics like Java features, bytecode, JDK, JRE, JVM, variables, data types, keywords, control statements, loops, casting etc. It provides details about each topic with examples.

Uploaded by

Prashant
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1/ 49

Git

Git is a free and open source distributed version control system


designed to handle everything from small to very large projects
with speed and efficiency.
GitHub
GitHub is an online software development platform. It's used
for storing, tracking, and collaborating on software projects.

What is difference between c++ and Java ?


Java C++
1) Java is platform independent
1) C++ is platform dependent.
2) There are no pointers in java
2) There are pointers in C++.
3) There is no operator overloading in java
3) C ++ has operator overloading.
4) There is garbage collection in java
4) There is no garbage collection
5) Supports multithreading
5) Does’nt support multithreading
6) There are no templates in java
6) There are templates in java
7) There are no global variables in java
7) There are global variables in c
What is bytecode in java ?
When a javac compiler compiles a class it generates
.class file, This .class file contains set of instructions
called byte code. Byte code is a machine independent language
and contains set of instructions which are to
be executed only by JVM. JVM can understand this byte codes.
Introduction
Java is an class-based object-oriented, , general-purpose
programming language. Java was originally developed by James
Gosling at Sun Microsystems ,Java programming language is
based on the write once, run anywhere (WORA) principle,
meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation. Java
applications are typically compiled to bytecode that can run on
any Java Virtual Machine (JVM) regardless of the underlying
operating system.
There are four editions of the Java programming language.
· Standard Edition (Java SE)
· Enterprise Edition (Java EE)
· Micro Edition (Java ME)
· JavaFX
Java SE:
It is a Java programming platform. It includes Java programming
APIs such as java.lang, java.io, java.net, java.util, java.sql,
java.math etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
Java EE:
it is an enterprise platform that is mainly used to develop web
and enterprise applications. It is built on top of the Java SE
platform. It includes topics like Servlet, JSP, Web Services, EJB,
JPA, etc.
Java ME:
It is a micro platform that is dedicated to mobile applications.
JavaFX:
It is used to develop rich internet applications. It uses a
lightweight user interface API.
Features of Java
Simple
Java is very easy to learn, and its syntax is simple, clean
and easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
There is no need to remove unreferenced objects because there
is an Automatic Garbage Collection in Java.
Object-Oriented:
Java is an object-oriented programming language. Everything in
java is an object. Object-oriented programming language
simplifies software development and maintenance by providing
some rules.
Platform independent:
Java is a platform-independent programming language. We can
write java code once and run it anywhere. Java code can be run
on multiple platforms, for example, Windows, Linux, Mac, etc.
Java code is compiled by the compiler and converted into byte
code. This byte code is platform-independent code because it
can be run on multiple platforms.
Robust:
Java programming language is robust because it uses strong
memory management. There is an automatic garbage collection
in java to destroy the objects which are unused. Exception
handling is another feature that makes java programming
robust.
Portable:
Java programming language is portable because it enables you
to carry byte code to any platform.
Multithreaded:
Java also supports multithreaded programming. We can create
multiple threads in java. The main advantage of multithreading
is that it doesn’t occupy the memory for each thread. It shares a
common memory area. Threads are important for web
applications, multimedia applications, etc.
Distributed:
Java programming language is distributed because it facilitates
the user to create distributed applications. We can create
distributed applications in java by using RMI and EJB.
Secure:
When a java program is compiled, it generates a byte code that
is in the non-readable form. The java byte code cannot be read
by humans. That makes the java language secure.
JDK:
JDK stands for Java Development Kit. JDK provides an
environment to develop and execute the java program. JDK is a
kit that includes two things - Development Tools to provide an
environment to develop your java programs and JRE to execute
your Java programs.
JRE:
JRE stands for Java Runtime Environment. JRE provides an
environment to only run (not develop) the java programs onto
your machine. JRE is only used by the end-users of the system.
JRE consists of libraries and other files that JVM uses at
runtime.
JVM:
JVM stands for Java Virtual Machine, which is a very important
part of both JDK and JRE because it is inbuilt in both. Whatever
java program you run using JDK and JRE goes into the JVM and
JVM is responsible for executing the java program line by line.

public static void main(String args[])


· public:
The public is an access modifier that can be used to specify
who can access this main() method. It simply defines the
visibility of the method. The JVM calls the main() method
outside the class. Therefore it is necessary to make the java
main() method as public.
static:
static is a keyword in java. We can make static variables
and static methods in java with the help of the static keyword.
The main advantage of a static method is that we can call this
method without creating an object of the class. JVM calls the
main() method without creating an object of the class,
therefore it is necessary to make the java main() method static.
void:
void is a return type of method. The java main() method
doesn’t return any value. Therefore, it is necessary to have a
void return type.
main:
main is the name of the method. It is a method where
program execution starts.
String args[]:
String in java is a class that is used to work on Strings and args
is a reference variable that refers to an array of type String. If
you want to pass the argument through the command line then
it is necessary to make the argument of the main() method as
String args[].
Java Variables
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
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.
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:
Primitive data types:
primitive data types are the building blocks of data
manipulation. These are the most basic data types available in
Java language.
1. boolean
2. char
3. byte
4. short
5. int
6. long
7. float
8. double
Non-primitive data types:
9. Classes
10. Interfaces
3. Arrays
Java Keywords
Java keywords are also known as reserved words. These are
predefined words by Java so they cannot be used as a variable
or object name or class name.
Decision Making statements
decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean
expression
· if statement
In Java, the "if" statement is used to evaluate a condition,The
condition of the If statement gives a boolean value, either true
or false.
· switch statement
· The switch statement contains multiple blocks of code
called cases and a single case is executed based on the
variable which is being switched.
Loop statements
loop statements are used to execute the set of instructions in a
repeated order.
· do while loop
· while loop
· for loop
· for-each loop
Jump statements
Jump statements are used to transfer the control of the
program to the specific statements.
· break statement
· continue statement

TypeCasting in Java
TypeCasting in Java is the process of converting one primitive
data type into another. TypeCasting can be done automatically
and explicitly.
There are two types of TypeCasting in Java.
Widening or Automatic Type Conversion.
Narrowing or Explicit Type Conversion.
1. Widening or Automatic Type Conversion:
When we assign a value of a smaller data type to a large data
type, this process is known as Widening Type Casting. It is also
known as Automatic Type Conversion because the Java
compiler will perform the conversion automatically. This can
happen only when the two data types are compatible.
byte -> short -> int -> long -> float -> double ( Widening or
Automatic Type Conversion)
For example, In Java, int data types are compatible, but it isn't
compatible with char and boolean data types. Also, char and
boolean data types are not compatible with each other.
Example:
public class WideningConversation {
public static void main(String args[]) {
// Automatic Type Conversion.
int i = 2147483647; // Int max value in java.
long l = i; // Automatically converted to long, now we can
extend l's value.
l = l + 1;
double d = l; // Automatically converted to double.
System.out.println("Int value : " + i);
System.out.println("Long value : " + l);
System.out.println("Double value : " + d);
}
}
Output
Int value : 2147483647
Long value : 2147483648
Double value : 2.147483648E9
2. Narrowing or Explicit Type Conversion:
When we assign a value of a large data type to a small data
type, the process is known as Narrowing Type Casting. This
can’t be done automatically. We need to convert the type
explicitly. If we don’t perform casting, the java compiler will give
a compile-time error.
double -> float -> long -> int -> short -> byte ( Narrowing or
Explicit Type Conversion)
Example:
public class ExplicitConversation {
public static void main(String args[]) {

// Explicit Type Conversion


double d = 25.123;
int i = (int) d;
byte b = (byte) i;
System.out.println("Double value : " + d);
System.out.println("Int value : " + i);
System.out.println("Byte value : " + b);
}
}
Output
Double value : 25.123
Int value : 25
Byte value : 25
Overflow and Underflow in Java
Overflow in java happens when we assign a value to a variable
that is more than its range and Underflow is opposite to
overflow. In case of overflow and underflow, the Java compiler
doesn’t throw any error. It simply changes the value.
For example, in the case of an int variable, its size is 4 bytes or
32 bits. The maximum value of int data type is 2,147,483,647
(Integer.MAX_VALUE) and after incrementing 1 on this value, it
will return -2,147,483,648 (Integer.MIN_VALUE). This is known
as overflow. The minimum value of int data type is -
2,147,483,648 (Integer.MIN_VALUE) and after decrementing 1
on this value, it will return 2,147,483,647 (Integer.MAX_VALUE).
This is known as underflow in Java.
Example:
public class OverflowExample {
public static void main(String args[]) {
// Overflow
int overFlow = 2147483647;
System.out.println(“Overflow : “ + (overFlow + 1));
// Underflow
int underFlow = -2147483648;
System.out.println(“Underflow : “ + (underFlow - 1));
}
}
Output
Overflow : -2147483648
Underflow : 2147483647
Operators in Java
Operators in Java are the special symbol which use to
manuplate data to produse usefull inforamtion
· Arithmetic Operators
· Unary Operators
· Assignment Operators
· Relational Operators
· Logical Operators
· Bitwise Operators
· Ternary Operators
· Instance of Operators
Arithmetic Operators
Arithmetic Operators in Java are used to perform mathematical
operations,
· Addition
· Subtraction
· Multiplication
· Division
· Modulus Operator (%) :
Unary Operators
Unary operators are work only one bit
+,-,++,--
Bitwise operators
Bitwise op. are used to perform operation on individual bits of
a no.
· & AND
· | OR
· ^ XOR
· ~ NOT
· << left shift
· >>RIGHT SHIFT
Relational operators
Always give boolean type value
<,>,<=,>=
Logical op.
! , &&, ||
Ternary Operator
Java Ternary operator is also known as the conditional operator:
This operator is the only conditional operator in java that takes
three operands. We can use ternary operator in place of if-else
statement or even switch statement. The syntax of the ternary
operator is shown below:
variable = expression1 ? expression2 : expression3
Instance of operator
The instanceof operator in java is used to compare an object to
a specified type. We can use it to check if an object is an
instance of a class, an instance of a subclass, or an instance of a
class that implements a particular interface. The instanceof
operator is either returned true or false.
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table,
computer, watch, etc.
Object-Oriented Programming is a methodology to design a
program using classes and objects. It simplifies software
development and maintenance by providing some concepts:
· Object
· Class
· Inheritance
· Polymorphism
· Abstraction
· Encapsulation
Object
An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory.
Any entity that has state and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can
create an individual object. Class doesn't consume any space.
Inheritance
When a class acquires all the properties and behaviors of a
parent class, it is known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as
polymorphism.
In Java, we use method overloading and method overriding to
achieve polymorphism.
new keyword in Java
The new keyword is used to allocate memory at runtime. All
objects get memory in Heap memory area.
Anonymous object
Anonymous simply means nameless. An object which has no
reference is known as an anonymous object. It can be used at
the time of object creation only.
example
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous
object
}
}
Garbage colletcter =
Garbage colletcter is a part of jvm , whose job is to release
memory of unrefrenced object from the heap:
Automatic memory managment or automatic Garbage
colletcter is the proces of looking at heap memory , identifing
which objects are in use and which are not and deleting the
unused objects,
in programing language like c and c++ alocating and
deallocating memory is a mannual process.
Wrapper class
Why java is not completely oops language
• Java is an object oriented progreming language and as said
everything in java is an object
· But what about the primitive types
· primitive types are sort of left out in the world of object.
that why they can not participate in the object activities
Wrapper class
As a Salution to this problem, Java allows you to Include the
primitives in the familly of objects by using wrapper class
there is a wrapper class for every primitive data type in java,
primitive type
Primitive types are the basic building block of data that
represent simple values.
Wrapper calss
wrapper class is a class that provide an object representation of
a primitive data type
wrapper class are used to convert primitive type into object ans
vice-versa
Types of Methods in Java
In Java, there are two types of methods:
· Predefined Method
· User-defined Method

Predefined Method
Predefined methods that are already defined in the libraries.
It's also known as the built-in method or the standard library
method.
Some predefined methods in java are:
sqrt(), max(), min(), round(), etc.
These are defined inside the Math class.
Some predefined methods of String class are:
length(), toUpperCase(), toLowerCase(), equals(), etc.
Let’s look at some examples using predefined methods.
Example 1: Find the maximum of two numbers using the built-in
method.
public class MaxOfTwoNumbers {
public static void main(String args[]) {
// Maximum of two numbers using Math.max()
int maximum = Math.max(100, 30);
System.out.println(maximum);
}
}
Output:
100
Example 2: Find the minimum of two numbers using the built-in
method.
public class MinOfTwoNumbers {
public static void main(String args[]) {
// Minimum of two numbers using Math.min()
int minimum = Math.min(100, 30);
System.out.println(minimum);
}
}
Output:
30
Example 3: Find the square root of a number using the built-in
method.
public class SqrtOfNumber {
public static void main(String args[]) {

// Finding the square root of a number using


Math.sqrt()
double sqrt = Math.sqrt(144);
System.out.println(sqrt);
}
}
Output:
12.0
Example 4: Find string length using the built-in method.
public class FindStringLength {
public static void main(String args[]) {
String str = "Coding Ninjas";
// Printing string length using length()
System.out.println(str.length());
}
}
Output:
13
Example 5: Convert the string into the upper case using the
built-in method.
public class UpperCaseString {
public static void main(String args[]) {

String str = "Coding Ninjas";

// Printing upper case string using toUpperCase()


System.out.println(str.toUpperCase());
}
}
Output:
CODING NINJAS

User-defined Method
The method written by the user is called the user-defined
method. We can modify these methods based on our
requirements.
No argument(s) passed and no return value
When a function has no arguments, it doesn’t receive any data
from the calling method. Similarly, when it doesn’t return a
value, the calling method doesn’t receive any data from the
called method.
Syntax:
Function declaration : void function();
Function call : function();
Function definition : void function()
{
Statements;
}
Example: In this example, we have created a method
checkEvenOdd() and we don’t pass any parameters to it. We
simply write the code to check whether a number is even or
odd as the body of the function. If the number is even, we
simply print “Even Number”, else we print “Odd Number” and
doesn’t return any value.
public class Solution {
public static void checkEvenOdd() {
int num = 24;
if(num % 2 == 0) {
System.out.println("Even Number");
}
else {
System.out.println("Odd Number");
}
}
public static void main(String args[]) {
// Method Calling
checkEvenOdd();
}}
Output:
Even Number
No arguments passed but return a value
There could be a requirement in our program where we may
need to design a method that takes no argument(s) but returns
a value to the calling method.
Example:
public class Solution {
public static int sumOfTwoNumbers() {
int a = 10;
int b = 20;
int sum = a + b;
return sum;
}
public static void main(String args[]) {
// No arguments passed in the method
int sum = sumOfTwoNumbers();
System.out.println(sum);
}

}
Output:
30
Arguments passed but don't return a value
In this example, we have created a method to check whether a
number is even or odd. This method doesn’t return any value
but when we call this function we need to pass argument(s) to
it.
Example:
public class Solution {
public static void findEvenodd(int num) {
if(num % 2 == 0) {
System.out.println("Even Number");
}

else {
System.out.println("Odd Number");
}
}
// Driver Method
public static void main(String args[]) {
int num = 24;
// argument passed in the method
findEvenodd(num);
}
}
Output:
Even Number
Arguments passed and do return a value
In this example, we have created a method that returns the
sum of the two numbers and accepts argument(s).
Example:
public class Solution {
public static int sumOfTwoNumbers(int num1, int
num2) {
int sum = num1 + num2;
// Return sum
return sum;
}
public static void main(String args[]) {
int a = 10;
int b = 20;

// Method calling with arguments


System.out.println(sumOfTwoNumbers(a, b));
}

}
Output:
30

* Modifiers=
There are two type of Modifiers in Java
access modifiers and non-access Modifiers,
* access Modifiers
access madifiers is the access type of the Method, it specified
the visibility of the Method,
→ public
→ protected
→ private
→ default
Non-access modifiers
Non-access modifiers provide information
about the characteristics of a class , method
or variable to the JVM
→ Static
→ Final
→ Abstract
→ Synchronized
→ Volatile
→ Transient
→ Native
Access modifires
Private
The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
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.
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.
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.
Non-access modifiers
Non-access modifiers provide information about the
characteristics of a class, method, or variable to the JVM. Seven
types of Non-Access modifiers are present in Java. They are –
Static
can be accessed without creating as instance of the class,
Final
The value of the variable cannot be changed once it is
assigned, it can be appiled to method and class aslo,
Abstract
abstract keyword is used to declare a class as particially
impemented means that objet can not be created directly from
this class,
Synchronized
the synchronized keyword used to indicate that a
method can be accessed by only one thread at a time,
Transient
Attributes and methods are skipped when serializing
the object containing them
Volatile
The value of an attribute is not cached thread-locally,
and is always read from the "main memory"

* Constructas =

→ Constructor is a special type method Whose name same as


the class name
→ the main perpose of constructor is instilze the object
→ every java class has a constructor.
→ A Constructor is automatically called at the time of object
creation
→ A Constructor never contain any return-type including
void
→ A Constructor can not be abstarct, final,and Synchronized
→ Constructor can be parametrirized,
→ Constructor can be overladed.
→Any access Modifier can be used in constructor
→ Constructor are used to assigne value to instance variable

* Type of Constructor
· Default constructor (no-arg constructor)
· Parameterized constructor
* Default Constructor=
A Constructor which have not any
paramter is called default constructer.
Example
class A {
int age;
String name;
A() {
age = 23;
name = "Adil";
}
void show() {
System.out.println(age + " " + name);
}
}
class B {
public static void main(String args[]) {
A sc = new A();
sc.show();
}
}
Java Parameterized Constructor
A constructor which has a specific number of parameters is
called a parameterized constructor
class A {
int x, y;
A(int a, int b) {
x = a;
y = b;
}
A(int a, String b) {
System.out.println(a + " " + b);
}
void show() {
System.out.println(x + " " + y);
}
}
class B {
public static void main(String args[]) {
A sc = new A(100, 200);
sc.show();
System.out.println("");
A s = new A(10, "Adil");
}
}
Constructor Overloading
output= 111 Adil
222 Adil 25
Java static keyword
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.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
this keyword in Java
this is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
· this can be used to refer current class instance variable.
· this can be used to invoke current class method (implicitly)
· this() can be used to invoke current class constructor.
· this can be passed as an argument in the method call.
· this can be passed as argument in the constructor call.
· this can be used to return the current class instance from
the method.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires
all the properties and behaviors of a parent object.

You might also like