Java
Java
Programming
Writing By Abhishek
Yadav
6. Portable: A java program written in one system can be run in any other system. In
simple a java program can be transferred from one system to another.
7. Multi-threading In Java, we can perform more than one task Simultaneously, so it is
called multithreading.
Application of java
1. It is used to develop Windows Application.
2. It is used to develop web Application.
3. It is used to develop Android/Mobile Application.
4. It is used to develop Embedded System for example SIM card, Television etc.
5. It is used to develop Scientific Application for example MATLAB.
6. It is used to develop Game.
7. It is used for Database Connectivity.
Why to Use Java
1. It is very simple and easy to learn.
2. It powerful, fast and secure.
3. It can be run on different kind of platform for example, windows, Mac Linux etc.
4. It is free and open source.
Syntax of Java
Basic Structure of a Java Program
A simple Java program consists of the following components:
public class Easy
{
public static void main(String[] args)
{
[Link]("Hello, World!");
}
}
Output
Hello, World!
Class
It is a keyword, which is used to declare a class.
Keyword. The keyword, which is predefined in the library, is called keyword for
example, Class, void, main etc.
Easy
It is a user define class name.
public
It is a keyword, which is called access specifier /modifier.
It used to provide accessibility of data member (variable) and member
function(function). The JVM needs to access these methods to start the program.
static
This means that the method belongs to the class rather than instances of the class. You
can call this method without creating an instance(object) of the class. It is a Keyword.
void
1. It is keyword and this indicates that the method does not return any value. The main
method is not expected to return anything to the JVM.
2. It is indicated that there is no value is returning by the function.
3. If we use any other Keyword like int float char etc. in place of void then we will use
return Keyword.
main ()
It is the function which is called the entry point of any program.
The execution of any program starts from the main function.
If in a program there is only one function, then it should be main function.
String [] args
This parameter is an array of strings that can hold command-line arguments passed to
the program. Each argument can be accessed within the method using the args array.
It is also called commend line argument.
You can also write anything in place of args.
[Link]
System: This is a class in java that provide access to system-related resources, such as
input/output stream, system properties and more.
Out: This is a static field in the System class that represents the standard output stream.
It's an object of the PrintStream class.
Println: This is a method of the PrintStream class that prints its argument to the console,
followed by a newline character (\n).
PrintStream is a class in Java that is part of the [Link] package. PrintStream provides
several print and println methods that can handle various data types,
including int, float, double, char, String, and more.
First Program of java
import [Link];
public class Easy{
public static void main(String[] args){
int x,y,z;
[Link]("Enter the value of x :");
Scanner obj=new Scanner([Link]);
x=[Link]();
[Link]("Enter the value of y :");
y=[Link]();
z=x+y;
[Link]("Sum of the x and y is : "+z);
}
}
Output
PS C:\Users\abhis\OneDrive\Desktop\Java> javac [Link]
PS C:\Users\abhis\OneDrive\Desktop\Java> java Easy
Enter the value of x:5
Enter the value of y:5
Sum of the x and y is: 10
After declaring a variable, you can assign a value to it. This process is known as initialization.
You can do this in two ways:
1. Separate Declaration and Initialization:
Local Variables:
Definition: Variables that are declared within a method, constructor, or block and can
only be accessed within that method, constructor, or block.
Lifetime: They are created when the method is called and destroyed when the method
exits.
Initialization: Local variables must be initialized before use.
Example
class Easy
{
public void add ()
{
int x,y=10,z=20; //declarring local variable initialize
x=y+z;
[Link]("Sum of y and z is:"+x);
}
public static void main (String [] args)
{
Easy obj=new Easy(); // Create an instance of Easy
[Link](); // Call the add method
}
OUTPUT = 30;
Instance variable
Definition: Variables that are declared inside a class but outside any method,
constructor, or block. They are associated with an instance of the class.
Lifetime: They are created when an object of the class is created and destroyed when
the object is destroyed.
Initialization: Instance variables are automatically initialized to default values (e.g., 0 for
integers, null for objects).
Example
class Easy
{
int x=10; // Instance variable
Static variable
Definition: Variables that are declared with the static keyword inside a class but outside
any method, constructor, or block. They belong to the class rather than any instance.
Lifetime: They are created when the class is loaded and destroyed when the program
stops.
Initialization: Static variables are initialized to default values if not explicitly initialized.
Example
class Easy
{
static int a = 0; // Static variable
public static void display()
{
[Link](a); // Accessing static variable
}
public static void main(String[] args)
{
Easy obj = new Easy(); // Creating an object of the class
[Link](); // Calling the display method
}
}
OUTPUT = 0;
Types of static
User input in Java
import [Link];
OUTPUT
Enter
Enter a character: Abhishek
Enter an integer: 1
Enter a float: 1.5
Enter a double: 2.00
Enter a string: Abhishek
Enter a boolean value (true/false): True
Result
The value is true.
You entered:
Character: A
Integer: 1
Float: 1.5
Double: 2.0
String: Abhishek
Char: A
You entered: true
class Easy {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String name;
try {
[Link]("Enter your name:");
name = [Link](); // Read user input
[Link]("Hello, " + name); // Output greeting
} catch (IOException e) {
[Link]("An error occurred while reading input: " + [Link]());
} finally {
try {
[Link](); // Close the BufferedReader
} catch (IOException e) {
[Link]("Error closing the reader: " + [Link]());
}
}
}
}
OUTPUT
Enter your name:
Abhishek Yadav
Hello, Abhishek Yadav
Constant in Java
Definition
An element of program whose value cannot be changed at the time of execution of
programs called constant.
It is also called literals.
It may be int, float, and Character data type.
Rule of constructing integer Constant
It must have at least one digit.
It must not have a decimal point.
It may be positive or negative.
No comma or blank space are allowed in integer constant.
Rule for constructing floating point constant
It must have at least one digit.
It must have a decimal point.
It may be positive or negative.
No comma or black space are allowed in floating point constant.
Rules for constructing character constant.
It is a single alphabet, digital or special symbol.
The length of character constant is one character.
Character constant is enclosed within single quotes. For example, c= ‘A’
Keyword in java
The word which is predefined in the library is called keyword.
You do the functionality is also predefined.
Keyword cannot be used as a variable function name, class name, or as an any identifier.
Example of keyword or cat void main etc.
Java Keywords
abstract Indicates that a class or method is abstract and cannot be instantiated
or must be implemented in a subclass.
assert Used for debugging purposes to make an assertion.
boolean A primitive data type that can hold the values true or false.
break Exits a loop or switch statement.
byte A primitive data type that is an 8-bit signed integer.
case Defines a branch in a switch statement.
catch Declares a block of code, known as an exception handler, that can
handle a specific type of exception.
char A primitive data type that represents a single 16-bit Unicode character
class Declares a class
const Not used. Reserved for future use.
continue Skips the current iteration of a loop and proceeds to the next iteration.
default Specifies the default block of code in a switch statement.
do Used in a do-while loop to execute a block of code at least once
double A primitive data type that represents a double-precision 64-bit floating
point.
else Specifies a block of code that executes if the corresponding if condition
is false.
enum Defines a set of named constants
extends Indicates that a class is inheriting from a superclass
final Indicates that a variable, method, or class cannot be changed or
overridden
finally A block of code that will always execute after a try-catch block,
regardless of whether an exception was thrown.
float A primitive data type that represents a single-precision 32-bit floating
point
for Used to initiate a for loop.
goto Not used. Reserved for future use
if Executes a block of code if a specified condition is true.
implements Indicates that a class implements an interface
import Imports other classes or packages into the current class
instanceof Tests whether an object is an instance of a specific class or interface.
int A primitive data type that represents a 32-bit signed integer
interface Declares an interface.
long A primitive data type that represents a 64-bit signed integer
native Indicates that a method is implemented in platform-specific code.
new Creates new objects or instances.
null A literal that represents a null reference.
package Defines a namespace for classes.
private Specifies that a member is accessible only within its own class
protected Specifies that a member is accessible within its own package and by
subclasses.
public Specifies that a member is accessible from any other class.
return Exits from a method and optionally returns a value.
short A primitive data type that represents a 16-bit signed integer.
static Indicates that a member belongs to the class rather than instances of
the class.
strictfp Used to restrict floating-point calculations to ensure portability.
super Refers to the superclass of the current object.
switch Initiates a switch statement.
synchronized Indicates that a method or block of code is synchronized for thread
safety.
this Refers to the current object.
throw Used to explicitly throw an exception.
throws Indicates that a method can throw exceptions.
transient Prevents serialization of a member variable.
try Starts a block of code that will be tested for exceptions.
void Indicates that a method does not return a value.
volatile Indicates that a variable may be changed unexpectedly, often used in
multithreading contexts.
while Initiates a while loop that continues as long as a condition is true.
Notes
Some keywords, like const and goto, are reserved but not currently used in Java.
Keywords are case-sensitive, meaning int and Int would be treated as different identifiers,
but `Int
1. ACCESS MODIFIERS
public: Access modifier indicating that a class, method, or variable is accessible from any other class.
protected: Access modifier indicating that a class, method, or variable is accessible within its own package and by
subclasses.
private: Access modifier indicating that a class, method, or variable is accessible only within its own class.
2. NON-ACCESS MODIFIERS
final: Used to declare constants, prevent method overriding, and prevent inheritance.
static: Indicates that a method or variable belongs to the class rather than instances of the class.
abstract: Used to declare a class that cannot be instantiated or a method that must be implemented by
subclasses.
synchronized: Used in multi-threading to indicate that a method or block of code is synchronized, allowing only
one thread to access it at a time.
volatile: Indicates that a variable's value will be modified by different threads.
transient: Prevents serialization of certain variables in a class.
Operators Java
In C programming, operators are special symbols that perform operations on variables and
values. They can be categorized based on their functionality. Here’s a structured overview
of operators and expressions in C:
Operator
It is a special symbol which is used to perform logical or mathematical operation on data or
variable.
Operand
It is a data or variable on which the operation is to be performed.
Type of Operator
1. Arithmetic Operators
2. Relational Operators
3. Assessment operators
4. Incremental/decrement operator
5. Logical operators
6. Conditional operator
7. Bitwise operators
8. Another operator
[Link] operator
Used for basic mathematical operations.
Arithmetic operators are used for numeric calculations.
They are of two types.
+x -y
Binary operators require two operands. There are five binary arithmetic operators
Operators Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Gives the reminder in int division
Example
class Easy
{
public static void main(String[] args)
{
int a=6,b=3;
[Link]("Add="+(a+b));
[Link]("Subtract="+(a-b));
[Link]("Multiply="+(a*b));
[Link]("Divide="+(a/b));
[Link]("Modulus="+(a%b));
}
}
Output = Add=9, Subtract=3, Multiply=18, Divide=2, Modulus=0
[Link] Operators
Equal To (= =) Checks if both operands are equal
Not Equal To (! =) Checks if both operands are not equal.
Greater Than (>) Checks if the left operand is greater than the right operand.
Less Than (<): Checks if the left operand is less than the right operand
Greater Than or Equal To (>=) Checks if the left operand is greater than or equal to the right
operand.
Less Than or Equal To (<=) Checks if the left operand is less than or equal to the right operand.
= (Simple assignment)
10
== Equal
!= Not equal
> Greater than
< Less than
>= Greater Than or equal to
<= Less than or equal to
class Easy {
public static void main(String[] args) {
int a = 5, b = 5;
boolean isEqual = (a == b); // true
// Print the result
[Link]("Is a equal to b? " + isEqual);
}
}
OUTPUT
Is a equal to b? true
Boolean Variable: The result of the comparison is stored in the boolean variable isEqual.
[Link]/Decrement Operators
Symbol Name Function Example
++ Increment It increments the ++x
value by 1
-- Decrement It decrements the --x
value by 1
C has two useful operators increment (++) and decrement (--).
The increment operator (++) increments the value of the variable by 1 and decrement
operator (--) decrements the value of the variable by 1.
++x to is equivalent to x = x + 1
--x is equivalent to x= x-1
The statement y=++x; mean first increment the value of x by 1, then assign the value of x to
y.
x=x+1;
y=x;
The Statement y=-x; means first decrement the value of x by 1 then assign the value of x to
y.
x=x-1;
y=x;
Let us take a variable whose value is 3. The statement y = x++; means first the value of x is
assigned to y and then x is incremented.
The statement is equivalent to these two statements
y = x;
x = x+1;
The statement y = x--; means first the value of is assigned to y and then x is decremented.
y=x;
x=x-1;
class Easy
{ prefix (++a)
b=a++ + ++a;
postfix (a++)
Assign 1 + 3 4 first time value Assign
These operators evaluate the conditions and return a Boolean value (True or False) that
signifies the result.
Logical AND (&&): This operator checks if both conditions are true. If both conditions
are true, then the result is true. Otherwise, the result is false.
Logical OR (||): This operator checks if at least one condition is true. If either
condition is true, then the result is true. Otherwise, the result is false.
Logical NOT (!): This operator checks if the condition is false. If the condition is false,
then the result is true. Otherwise, the result is false.
Example
class Easy
{
public static void main (String [] args)
{
int a=10, b=60,c=40;
if(a>b && a>c)
[Link]("a is greater");
if(b>a && b>c)
[Link]("b is greater");
if(c>a && c>b)
[Link]("c is greater");
}
}
Output
b is greater
[Link] Operators
The conditional operator, also known as the ternary operator, is a shortest way of
expressing conditional statements in C. It allows you to evaluate a condition and
return one of two values based on whether the condition is true or false.
Example
[Link] operators
Example
class Easy
{
public static void main(String[] args)
{
int a=5,b=3,c;
c=a&b;
[Link]("a&b= "+c);
c=a|b;
[Link]("a|b= "+c);
c=a>>2;
[Link]("a>>2= "+c);
c=a<<2;
[Link]("a<<2=" +c);
c=a^b;
[Link]("a^b= "+c);
}
}
OUTPUT
a&b= 1
a|b= 7
a>>2= 1
a<<2=20
a^b= 6
Float type
Type Size in bytes Range
Float 4 3.4e-038 to 3.4e+038.
Double 8 1.7e-308 to 1.7e+038.
Boolean type
Keyword Boolean
Syntax Boolean x;
Value True/False
Default False
Character
Keyword char
Syntax Char x
Value ‘a’,’@’ ’9’
Range 0 to 65536
Comment in java
Multiline comment
Multiple comment is used to comment a block code.
Multiple comment starts with /* and end with */.
The text between /* and */ is not executed by the compiler.
public class Easy
{
public static void main(String[] args)
{
/* This is a single line comment & Program Written by Abhishek Yadav */
If statement in java
Syntax
if (condition) {
// Code to be executed if the condition is true
}
Keyword
USING THE FINAL KEYWORD WITH PARAMETERIZED CONSTRUCTORS PROVIDES
SEVERAL BENEFITS:
1. Immutability: The final keyword ensures that the variable cannot be changed
once it is initialized, making the object immutable.
2. Thread Safety: Immutable objects are thread-safe, as multiple threads cannot
modify the object's state simultaneously.
3. Code Readability: The final keyword clearly indicates that the variable's value
cannot be changed, making the code more readable and maintainable.
4. class Easy
5. {
6. final int speedlimit;
7.
8. // Parameterized constructor
9. public Easy (int speedlimit) {
10. [Link] = speedlimit;
11. }
12.
13. void run() {
14. // speedlimit = 400; // This line would cause a compilation error
15. [Link]("Speed limit: " + speedlimit);
16. }
17.
18. public static void main(String args[]) {
19. Easy obj = new Easy(90);
20. [Link]();
21. }
22. }
OBJECT ORIENTED PROGRAMMING SYSTEM IN JAVA
Object
In Java, an object is an instance of a class. It. Is a fundamental concept in object-oriented
programming system and represent a real-world entity with state or behavior.
State
The state of an object is represented by its attribute {also known as filled up properties}
These attributes hold data specific to the object.
Behavior
The behavior of an object is defined by the method (function)that can be invoked on it.
This method can be manipulating the object state or perform operations.
Class
It is a collection of data member and member function.
Data members are the variable used inside Class.
Member functions are the function used inside class.
It is also called user defined data type.
import [Link];
public class Easy
{
//Data Member
int a;
int b;
int c;
// Method
void Add()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the value of the a");
a=[Link]();
[Link]("Enter the value of the b");
b=[Link]();
c=a+b;
[Link]("The Result of the c :"+c);
}
public static void main(String[] args)
{
Easy obj=new Easy();
[Link]();
Output
Enter the value of the a
5
Enter the value of the b
5
The Result of the c :10
import [Link];
public class Easy
{
//Data Member
int a;
int b;
int c;
// Method
void Add()
{
c=a+b;
[Link]("The Result of the c :"+c);
}
public static void main(String[] args)
{
Easy obj=new Easy();
obj.a=5;
obj.b=10;
[Link]();
}
Output
The Result of the c :15
[Link] Value Initialization of Instance Data Member
// Method
void Add()
{
c=a+b;
[Link]("The Result of the c :"+c);
}
public static void main(String[] args)
{
Easy obj=new Easy();
[Link]();
Output
The Result of the c :15
CONSTRUCTER
1. It is a special Member function of class that execute when we create the
instance(object) of that [Link] other word we can say that there is no need to call a
constructer.
2. Its name is same as class name.
3. It may be parameterized or non-parametrized.
4. It is used to initialized class level variable.
Types of constructers with Example
1. Default Constructer
2. Parametrized Constructer
3. Copy Constructer
4. Constructer overloading
1. Default Constructer
Example
class Rectangle
{
// data Member
int height;
int width;
int area;
//Constructer
// Notic here there is no return types and name is same as class
Rectangle ()
{
width=10;
height=10;
area=width*height;
[Link]("Area of Rectangle="+area);
}
public static void main(String[] args)
{
Rectangle obj=new Rectangle();
}
}
Output
Area of Rectangle=100
2. Parametrized Constructer
class Rectangle
{
// data Member
int area;
//Constructer
// Notic here there is no return types and name is same as class
area=width*height;
[Link]("Area of Rectangle="+area);
}
public static void main(String[] args)
{
Rectangle obj=new Rectangle(15,25);
}
}
Output
Area of Rectangle=375
3. Copy Constructer
In these types of constructers one Object with parameter is copied into another object, so
it’s called the copy constructor.
Example
class Rectangle
{
// data Member
int area;
//Constructer
// Notic here there is no return types and name is same as class
area=width*height;
}
void show()
{
[Link]("Area of Rectangle="+area);
}
public static void main(String[] args)
{
Rectangle obj1=new Rectangle(15,25);
[Link]();
Rectangle obj2=obj1;
[Link]();
}
}
Output
Area of Rectangle=375
Area of Rectangle=375
[Link] overloading
KEY POINTS:
1. Same Name: All constructors in a class must have the same name as the class.
2. Different Parameters: Each constructor must have a different parameter list
(different type, number, or order of parameters).
3. No Return Type: Constructors do not have a return type, not even void.
Example
class Rectangle {
private int length;
private int width;
// Constructor with no parameters
public Rectangle()
{
[Link] = 1; // default length
[Link] = 1; // default width
}
// Constructor with one parameter
public Rectangle(int side)
{
[Link] = side; // square
[Link] = side;
}
// Constructor with two parameters
public Rectangle(int length, int width)
{
[Link] = length;
[Link] = width;
}
// Method to calculate area
public int area()
{
return length * width;
}
// Method to display dimensions
public void display()
{
[Link]("Length: " + length + ", Width: " + width);
}
}
public class Main
{
public static void main(String[] args)
{
// Using the constructor with no parameters
Rectangle rect1 = new Rectangle();
[Link](); // Output: Length: 1, Width: 1
[Link]("Area: " + [Link]()); // Output: Area: 1
// Constructor
public Car(String model, int year)
{
[Link] = model; // '[Link]' refers to the instance variable
[Link] = year; // '[Link]' refers to the instance variable
}
}
}
// Usage
public class Main
{
public static void main(String[] args)
{
Car car = new Car("Toyota", 2020);
[Link]();
}
}
Output:
Model: Toyota
Year: 2020
Notes: If you keep both classes in the same file, only one can be public, and it should
match the filename.
If you want both classes to be public, they must be in separate files
named [Link] and [Link].
2. Constructor Chaining
‘This’ can be used to call another constructor in the same class. This is known as constructor
chaining and is useful for reusing constructor code.
class Person
{
private String name;
private int age;
// Usage
public class Main
{
public static void main(String[] args)
{
Person person1 = new Person("Alice", 30);
[Link](); // Output: Name: Alice, Age: 30
Output
Name: Alice, Age: 30
Name: Bob, Age: 0
3. Returning the Current Object
In methods, ‘this’ can be used to return the current object. This is often used in method chaining.
class Builder
{
private String name;
private int age;
// Usage
public class Main
{
public static void main(String[] args)
{
Builder builder = new Builder();
[Link]("Alice").setAge(30).display(); // Output: Name: Alice, Age: 30
}
}
// Output
Name: Alice, Age: 30
Example
class Outer
{ Summary
private String outerField = "Outer Field";
this Keyword: Refers to the
public class Inner current object instance.
{
private String innerField = "Inner Field"; Common Uses:
public void display() Distinguishing between
{ instance variables and
[Link](innerField);
parameters.
[Link]([Link]); // Referring to the outer class
field
}
Constructor chaining to
} call another constructor.
}
Returning the current
// Usage object for method
public class Main chaining.
{
public static void main(String[] args) Accessing outer class
{
Outer outer = new Outer(); members from inner
[Link] inner = [Link] Inner(); classes.
[Link](); // Output: Inner Field, Outer Field
} The ‘this’ keyword is a powerful feature
} in Java that helps improve code clarity
and maintainability.
// Output
Inner Field
Outer Field
SUPER ( ) KEYWORD
super is used to access methods, constructors, and variables of the parent class.
In Java, the super keyword is a reference variable used to refer to the immediate parent
class object. It is primarily used in the following contexts:
1. Accessing Parent Class Methods: You can use super to call methods from the parent
class that have been overridden in the child class.
2. Accessing Parent Class Constructors: You can use super () to call a constructor of the
parent class from the child class constructor.
3. Accessing Parent Class Variables: You can use super to access variables of the parent
class when there is a naming conflict with the child class variables.
When a method in a child class overrides a method in the parent class, you can use ‘super’ to call the parent class's version of
the method.
class Parent
{
void display()
{
[Link]("Display from Parent class");
}
}
void show()
{
[Link](); // Calls the display method of Parent class
}
}
Output
Display from Parent class
You can use super() to invoke the constructor of the parent class. This is often done in the constructor of the
child class.
class Parent
{
Parent()
{
[Link]("Parent class constructor");
}
}
class Child extends Parent
{
Child()
{
super(); // Calls the constructor of Parent class
[Link]("Child class constructor");
}
}
public class Main
{
public static void main(String[] args)
output
{ Parent class constructor
Child child = new Child();
} Child class constructor
}
If a child class has a variable with the same name as a variable in the parent class, you can use ‘super’ to refer to the parent class
variable.
class Parent {
int value = 10;
}
void displayValues() {
[Link]("Value in Child class: " + value);
[Link]("Value in Parent class: " + [Link]);
}
}