0% found this document useful (0 votes)
2 views44 pages

Java

The document provides an overview of the Java programming language, detailing its history, features, and applications. It explains the basic structure of a Java program, variable types, user input methods, constants, and keywords. Additionally, it includes examples of Java code demonstrating these concepts.

Uploaded by

devy6441
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Java

The document provides an overview of the Java programming language, detailing its history, features, and applications. It explains the basic structure of a Java program, variable types, user input methods, constants, and keywords. Additionally, it includes examples of Java code demonstrating these concepts.

Uploaded by

devy6441
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java

Programming
Writing By Abhishek
Yadav

Master of Computer Appliation


Introduction of Java Language
1. It is general-purpose high-level object-oriented programming language.
2. It is developed by James Gosling
3. it is developed at Sun Microsystem in 1995.
History of java
1. James Gosling and his term started to work on java or a client set top box project in
1991.
2. The first version of java (java 1.0) is released in 1995.
3. First name of java is Oak next goes to Green and finally becomes JAVA.
4. Java is the name of Coffee seed.
Features of Java
1. Object Oriented: Java supports object-oriented programming structure so it is called
object oriented.

2. Simple: Java is very simple and easy to learn.


3. Security/Secured: Java is more secure language as compared to other programming
language

4. Platform Independent: Java is called platform independent because a java program


can be run on different kind of platform for example Window os, Linux os etc.

5. Flexible: An application developed in java can be modified as per user requirement


so it called flexible programming language.

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

What is Variable in java


In Java, a variable is a container that holds data that can be changed during the execution
of a program.
1. It is a name of storage space which is used to store data.
2. Its value may be changed
3. It always contains last value stored to it.
4. It is always declared with data type.
Variable Declaration
int
Variable Initialization

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:

int count; // Declaration


count = 10; // Initialization
2. Multiple Variable Declarations
int x = 5, y = 10, z = 15; // Declaring and initializing multiple int variables
3. Other method of variable initialization
We can also initialize a variable after the time of declaration of variable.
Method int rollno;
float marks;
char grade;
****************
rollno=201;
marks=85.6;
grade='A';
Rules to define a variable
4. The first letter of a variable should be alphabet or underscore (_).
5. The first letter of variable Should not be digit.
6. After first character, it may be combination of alphabet and digit.
7. Blank space is not allowed in variable name.
8. Variable names should not be a keyword.

Types of Variables in Java


In Java, variables can be categorized into several types based on their scope, lifetime, and
the data they hold. Here are the main the main type of variable in java

Types of variables in Java:


 Local Variable
 Instance Variable
 Static variable

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

public void display()


{
[Link](x); // Accessing instance variable
}

public static void main(String[] args)


{
Easy obj = new Easy(); // Creating an object of the class
[Link](); // Calling the display method
}
}
OUTPUT = 10;

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 the Scanner Class:


You need to import the [Link] package at the beginning of your Java program.
Create a Scanner Object:
Instantiate a Scanner object to read input.
Read Input:
Use the appropriate methods of the Scanner class to read different types of input (e.g.,
integers, strings, floats, etc.).

 Scanner is a predefined class, which is used to take user input in Java.


 Scanner classes defined inside the java. util package.
 Scanner class consists of many predefine functions to take the user input, which is given
below.

nextInt () : Used to read integer value from the user.


nextFloat () : Used to read float value from the user.
nextDouble () : Used to read double value from the user.
next () : Used to read string while without space from the user.
nextLine () : Used to read string value from the user.
nextByte () : Used to read byte value from the user.
nextShort () : Used to read sort value from the user.
nextLong () : Used to read long value from the user.
[Link](0) : Used to read char value from the user.
Example of all many predefine function which is used to take input all type variable forms the user

import [Link];

public class Easy {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Prompt for a character


[Link]("Enter a character: ");
String input = [Link](); // Read the entire line
char charValue = [Link](0); // Get the first character

// Prompt for an integer


[Link]("Enter an integer: ");
int intValue = [Link]();

// Prompt for a float


[Link]("Enter a float: ");
float floatValue = [Link]();

// Prompt for a double


[Link]("Enter a double: ");
double doubleValue = [Link]();

[Link](); // Consume the newline left-over

// Prompt for a string


[Link]("Enter a string: ");
String stringValue = [Link]();

// Prompt for a boolean value


[Link]("Enter a boolean value (true/false): ");
boolean userInput = [Link]();

// Example of using the boolean value in a conditional statement


if (userInput) { // Check if userInput is true
[Link]("The value is true.");
} else {
[Link]("The value is false.");
}

// Display the entered values


[Link]("You entered:");
[Link]("Character: " + charValue);
[Link]("Integer: " + intValue);
[Link]("Float: " + floatValue);
[Link]("Double: " + doubleValue);
[Link]("String: " + stringValue);
[Link]("Char: " + charValue);
[Link]("You entered: " + userInput);

[Link](); // Close the scanner to prevent resource leaks


}
}

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

Second way to take user input in Java


1. BufferedReader is a predefine Class, which is used to take user input in Java.
2. It is defined inside the Java .io package.
Commonly Used Methods
 read(): Reads a single character from the input stream.
 read(char[] cbuf): Reads characters into a portion of an array.
 readLine(): Reads a line of text. A line is considered to be terminated by any one of a line
feed (\n), a carriage return (\r), or a carriage return followed immediately by a line feed.
 close(): Closes the stream and releases any system resources associated with it.
Example
import [Link];
import [Link];
import [Link];

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

=== Code Execution Successful ===

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.

3. CONTROL FLOW KEYWORDS


 if: Used to create a conditional statement.
 else: Used to specify a block of code that executes if the condition in the if statement is false.
 switch: Used to execute one block of code among many based on the value of a variable.
 case: Defines a branch in a switch statement.
 default: Specifies the default block of code in a switch statement if no case matches.
 for: Used to create a loop that iterates a specific number of times.
 while: Used to create a loop that continues as long as a specified condition is true.
 do: Used to create a loop that executes at least once and continues while a specified condition is true.
 break: Exits a loop or switch statement.
 continue: Skips the current iteration of a loop and proceeds to the next iteration.
 return: Exits from the current method and optionally returns a value.

4. EXCEPTION HANDLING KEYWORDS


 try: Defines a block of code to be tested for exceptions.
 catch: Defines a block of code that handles exceptions thrown by the try block.
 finally: Defines a block of code that executes after the try and catch blocks, regardless of whether an exception
was thrown.
 throw: Used to explicitly throw an exception.
 throws: Indicates that a method can throw exceptions.

5. CLASS AND OBJECT KEYWORDS


 class: Used to declare a class.
 interface: Used to declare an interface.
 extends: Indicates that a class is inheriting from a superclass.
 implements: Indicates that a class is implementing an interface.
 instanceof: Tests whether an object is an instance of a specific class or interface.

6. DATA TYPE KEYWORDS


 int: A primitive data type representing a 32-bit signed integer.
 float: A primitive data type representing a single-precision 32-bit IEEE 754 floating point.
 double: A primitive data type representing a double-precision 64-bit IEEE 754 floating point.
 char: A primitive data type representing a single 16-bit Unicode character.
 boolean: A primitive data type representing a true or false value.
 byte: A primitive data type representing an 8-bit signed integer.
 short: A primitive data type representing a 16-bit signed integer.
 long: A primitive data type representing a 64-bit signed integer.
7. OTHER KEYWORDS
 void: Indicates that a method does not return a value.
 native: Indicates that a method is implemented in platform-specific code, typically in C or C++.
 strictfp: Used to restrict floating-point calculations to ensure portability.
 const: Not used in Java (reserved for future use).
 goto: Not used in Java (reserved for future use).

8. ANNOTATIONS (JAVA 5 AND LATER )


 @Override: Indicates that a method is intended to override a method in a superclass.
 @Deprecated: Marks a method or class as deprecated, indicating that it should no longer be used.
 @SuppressWarnings: Instructs the compiler to suppress specific warnings.

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.

1. Unary arithmetic operators

2. Binary arithmetic operators

1. Unary Arithmetic Operators


Unary operators require only one operand. For example,

+x -y

Here ‘-’change the sign of the operand y.

2. Binary Arithmetic Operators

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.

public class Easy {

public static void main(String[] args) {


int a = 10, b = 20;

[Link]("a == b: " + (a == b)); // false


[Link]("a != b: " + (a != b)); // true
[Link]("a > b: " + (a > b)); // false
[Link]("a < b: " + (a < b)); // true
[Link]("a >= b: " + (a >= b)); // false
[Link]("a <= b: " + (a <= b)); // true
}
}
Output
a == b: false
a != b: true
a > b: false
a < b: true
a >= b: false
a <= b: true
[Link] Operators
Assignment Operators: Used to assign values to variables.

= (Simple assignment)

+=, -=, *=, /=, %= (Compound assignment)


Assignment Operators Example

public class Easy


{
public static void main(String[] args)
{
int a=5,b=5;
a+=b;
[Link](a);
}
}
Output

10

A list of all assignment operators:

== 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

1. Prefix Increment /Decrement (++x or --x)


Here first the value of variable is increment /decrement then the new value is used in the
operation.

Let us take a variable x whose value is 3.

The statement y=++x; mean first increment the value of x by 1, then assign the value of x to
y.

The single statement is equivalent to these two statements

Operators and Expressions

x=x+1;

y=x;

Hence now value of x is 4 and value of y is 4.

The Statement y=-x; means first decrement the value of x by 1 then assign the value of x to
y.

This statement is equivalent to these two statements.

x=x-1;

y=x;

Hence now value of x is 3 and value of y is 3.

2. Postfix Increment / Decrement (x++ or x--)


Here first the value of variable is used in the operation and then increment/decrement is
performed.

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

Operators and Expressions

y = x;

x = x+1;

Hence now value of x is 4 and value of y is 3.

The statement y = x--; means first the value of is assigned to y and then x is decremented.

This statement is equivalent to these two statements.

y=x;

x=x-1;

Hence now value of x is 3 and value of y is 4.

class Easy

{ prefix (++a)

int a=1, b; first time value increment

Increment 2 3 and then Assign.

b=a++ + ++a;
postfix (a++)
Assign 1 + 3 4 first time value Assign

Answer: b=4, a=3 and then increment.


[Link] Operators
Logical Operators or Boolean Operators
Logical operators, also known as Boolean operators, are used to combine two or more
conditions or expressions in a program.

These operators evaluate the conditions and return a Boolean value (True or False) that
signifies the result.

There are three logical operators in C

1. logical AND (&&)


2. logical OR (||)
3. and logical NOT (!)
Types of Logical Operators in C

 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.

The syntax for the conditional operator is:

condition ? expression_if_true : expression_if_false;

Example

public class Easy {

public static void main(String[] args) {


int a = 10;
int b = 20;
int max = (a > b) ? a : b;
[Link]("The maximum value is: " + max);
int number = 15;
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link]("The number " + number + " is: " + result);
}
}
Output
The maximum value is: 20
The number 15 is: Odd

[Link] operators

Symbol Operation Example


& Bitwise And x&y
| Bitwise OR x|y
<< Shift Left x<<2
>> Shift Right x>>2
^ X-OR x^y

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

Data Type in Java


 It is a type of data which is used in the program.
 There are many predefine data types library like int, char,
float etc.
Type of data type
 Primitive Data Type
 Non primitive Data Type

Primitive Data Types


The data type which is predefine in the library is called primitive data type.
It is named by a keyword for example int, char, float etc.
There are eight primitive data types un java.
Byte, short, int, long, float double, Boolean and char.
Integer Type
Type Size in bytes Range
Byte 1 -128 to 128
short 2 -32768 to 32767
Int 4 -2147483648 to 2147483647
long 8 -9223,372,036,854,775,808 to
9223.372,036,854,775,808

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

Non-Primitive Data Type


 The data type which is derived from primitive data type is called non-
primitive data type.
 It is also called reference data type.
 The don’t store he value but store a reference to that value.
 Example: Array, class, interface etc.

Comment in java

 It is used to explain the code to make it more readable.


 It is not considered as a part of program, in other word we can say that
compiler ignores the comment.
 Java comments are statement that are not executed by the complier.
Type of comments in java
 Single line comment
 Multiline comment
Single line comment
it is used comment only one line.
Two forward slashes (//) is used for single line comment.
Single line comment starts with double forward slashes.
//this is a single line comment
[Link]("i am excellent");

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.

Example class and object


There are many ways to create the class in java
1 Method User input

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

[Link] Value Initialization by Object

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

import java .[Link];


public class Easy
{
//Data Member
int a=5;
int b=10;
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();
[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

Rectangle (int height,int width)


{

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

Rectangle (int height,int width)


{

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

// Using the constructor with one parameter


Rectangle rect2 = new Rectangle(5);
[Link](); // Output: Length: 5, Width: 5
[Link]("Area: " + [Link]()); // Output: Area: 25

// Using the constructor with two parameters


Rectangle rect3 = new Rectangle(4, 6);
[Link](); // Output: Length: 4, Width: 6
[Link]("Area: " + [Link]()); // Output: Area: 24
}
}  Output
 Length: 1, Width: 1
 Area: 1
 Length: 5, Width: 5
 Area: 25
 Length: 4, Width: 6
‘THIS KEYWORD’

1. Referring to Instance Variables


When instance variables are shadowed by method or constructor parameters (i.e., they
have the same name), ‘this’ is used to refer to the instance variable.
class Car
{
private String model;
private int year;

// Constructor
public Car(String model, int year)
{
[Link] = model; // '[Link]' refers to the instance variable
[Link] = year; // '[Link]' refers to the instance variable
}

public void display()


{
[Link]("Model: " + model);
[Link]("Year: " + year);

}
}

// 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;

// Constructor with two parameters


public Person(String name, int age)
{
[Link] = name;
[Link] = age;
}

// Constructor with one parameter


public Person(String name)
{
this(name, 0); // Calls the other constructor with a default age of 0
}

public void display()


{
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

// Usage
public class Main
{
public static void main(String[] args)
{
Person person1 = new Person("Alice", 30);
[Link](); // Output: Name: Alice, Age: 30

Person person2 = new Person("Bob");


[Link](); // Output: Name: Bob, Age: 0
}
}

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;

public Builder setName(String name)


{
[Link] = name;
return this; // Returning the current object
}

public Builder setAge(int age)


{
[Link] = age;
return this; // Returning the current object
}
public void display()
{
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

// 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

4. Using this in Inner Classes


In inner classes, ‘this’ refers to the instance of the inner class. If you want to refer to the
outer class instance, you can use ‘[Link]’.

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.

1. Accessing Parent Class Methods:

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");
}
}

class Child extends Parent


{
void display()
{
[Link]("Display from Child class");
}

void show()
{
[Link](); // Calls the display method of Parent class
}
}

public class Main


{
public static void main(String[] args)
{
Child child = new Child();
[Link](); // Output: Display from Parent class
}
}

Output
Display from Parent class

[Link] Parent Class Constructors:

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
}

3. Accessing Parent Class Variables

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;
}

class Child extends Parent {


int value = 20;

void displayValues() {
[Link]("Value in Child class: " + value);
[Link]("Value in Parent class: " + [Link]);
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
[Link]();
}
}
Output:
Value in Child class: 20
Value in Parent class: 10

You might also like