0% found this document useful (0 votes)
25 views45 pages

Java Youtube 1

Uploaded by

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

Java Youtube 1

Uploaded by

YouTube Fun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

JAVA

JAVA

Float or Double

In Java, "float" is a primitive data type that represents a single-precision 32-bit floating-point number.

It can hold a value between approximately 1.4E-45 to 3.4E38 and is declared using the keyword "float".

Here is an example of declaring a float variable and assigning a value to it:


float myFloat = 3.14f;
Note that we need to use the suffix "f" after the value to indicate that it is a float literal. If we don't use the
"f" suffix, the compiler will assume it is a double and give a compile-time error.
Eg in code:
float x = 2.5f;
float y = 1.5f;
float result = x + y;
System.out.println("The result is: " + result);
This code will output "The result is: 4.0" to the console.
JAVA
Double in Java
In Java, "double" is a primitive data type that represents a double-precision 64-bit floating-point
number.

It can hold a value between approximately 4.9E-324 to 1.8E308 and is declared using the keyword
"double".

Here is an example of declaring a double variable and assigning a value to it:

java
double myDouble = 3.14159;
We don't need to use any suffix to indicate that a literal is a double, unlike the float data type.

We can perform arithmetic operations on double values, just like any other numeric data type. For
example:
code
double x = 2.5;
double y = 1.5;
double result = x + y;
System.out.println("The result is: " + result);
This code will output "The result is: 4.0" to the console.
In general, we use double when we need a higher precision or a wider range of values than float.
-------------------------------------------------------------------------------------------------------------------------------

In Java, a bit is the smallest unit of information and can have a value of either 0 or 1. A byte, on the other
hand, is a unit of data that consists of 8 bits.

In Java, the primitive data type byte is used to represent an 8-bit value. It has a range of -128 to 127,
inclusive. You can declare a variable of type byte as follows:
Character

In Java, a char is a primitive data type that represents a single character. It can hold any character from the
Unicode character set, including letters, digits, punctuation marks, and special characters.
JAVA
Note that characters are enclosed in single quotes (' '), while strings are enclosed in double quotes (" ").
Boolean

In Java, Boolean is a primitive data type that can hold one of two values: true or false.

You can declare a variable of type boolean as follows:


Boolean b= true;
This creates a variable called Boolean and initializes it to the value of true.

------------------------

Note : At Long data type , we need to mention “l” after number

Code

class Hello{

public static void main(String a[])


{
int num1 = 56;
byte b = 127;
short s = 500;
long l = 5000l;

float f = 5:8f;
double d = 5.8;

char c = 'Koushik'
boolean b = true;

}
}
JAVA
Java literals
are fixed values or constants that are used to represent data in a program's source code. They are values
that are directly written in the code, and their value cannot be changed during the program's execution.

There are several types of literals in Java, including integer literals, floating-point literals, boolean literals,
character literals, string literals, and null literals.

For example, 123 is an integer literal, 3.14159 is a floating-point literal, true and false are boolean literals,
'a' is a character literal, "Hello, World!" is a string literal, and null is a null literal.

Literals are used in Java to represent values that are known at compile-time, and they help make the code
easier to read and understand.

Underscores in Java are used as a separator to make large numeric literals easier to read.

Starting from Java 7, you can use underscores as separators in integer, long, float, and double literals. For
example, instead of writing 1000000, you can write 1_000_000.
JAVA

Datatype

In computer science, a data type is a classification of data based on the type of value it represents and
the operations that can be performed on it.

There are several common data types, including:

Integer: A whole number, either positive, negative, or zero.


Floating-point: A number with a fractional part, represented with a decimal point.
Boolean: A value that can be either true or false.
Character: A single letter, digit, or special symbol.
String: A sequence of characters.
Array: A collection of values of the same data type.
Object: A data type that stores a collection of related data and behaviors.
JAVA
Different programming languages support different data types, and each data type has its own set of rules
for how it can be used and manipulated. Understanding data types is an important concept in
programming as it affects the way data is stored, manipulated, and processed.

In computer programming, a byte is a unit of digital information that is used to represent a


single character or data element. In most programming languages, a byte is made up of
eight bits, each of which can be either 0 or 1, resulting in a total of 2^8 possible
combinations.

2^8 (two to the power of eight) is equal to 256.

int age = 30;


This statement declares a variable named "age" of Data type "int", which can hold integer
values, and initializes it with the value 30 (30 is Integer Literal)
JAVA

Takeaways
 Every Variable needs a name
 Every Variable needs a Type aswell
 To get variable for number – we use , Int Float Double or Long
 To get variable character – we use Char
 To get variable Boolean – we use Boolean

Type conversion and Type casting

In Java, explicit conversion (also known as type casting) refers to the process of converting a value of one
data type to another data type, explicitly indicating the type to which the value is being converted.

To perform explicit conversion in Java, you can use the cast operator, which is represented by the
parenthesis ( ) and the data type to which the value is being converted. Here's an example:
JAVA
Java code below;
double d = 3.14;

int i = (int) d; // explicit conversion from double to int

In this example, the value of the double variable d is explicitly converted to an integer data type using the
cast operator. The resulting value is assigned to the integer variable i.

When you try to convert Float to Integer we loose the point value data

o convert the float value 5.65 to an int in Java, you can use the cast operator. Here's an example:

float f = 5.65f;
int i = (int) f; // explicit conversion from float to int
In this example, the value of the float variable f is explicitly converted to an integer data type using the cast
operator. The resulting value is assigned to the integer variable i.

However, it's important to note that when you convert a float to an int, the fractional part of the float
value is truncated. So in this case, the resulting integer value would be 5. Any fractional part of the float
value is lost during the conversion to an integer, and the resulting integer value only represents the whole
number part of the original float value.

Note : In Java, double forward slashes (//) are used to indicate a single-line comment. Anything written
after the // symbol on the same line is not executed as code

Conversion is Automatic conversion


Casting mean explicit or deliberate conversion

Type promotion is the implicit conversion of a smaller data type to a larger data type, where the range
and precision of the value are preserved. This is done automatically by the Java compiler, without
requiring any explicit casting or conversion.

For example, if we have an expression that involves both an integer and a floating-point number, Java will
automatically promote the integer to a floating-point number before performing the arithmetic operation. This
ensures that the result of the operation is accurate and has the correct data type.

Here's an example of type promotion in Java:

int a = 5;
JAVA
double b = 3.14;

double result = a * b; // the int 'a' is promoted to a double before the multiplication operation
System.out.println(result); //

Output: 15.7

In this example, the integer value 'a' is automatically promoted to a double before the multiplication operation with
'b'. The result is a double with the value 15.7, which is the accurate product of 5 and 3.14.

Sometimes we get answer of

5.1033992E7 , what’s e7 mean


In scientific notation, "e" stands for exponent of 10. In the number 5.1033992E7, "E7" means 10 to the
power of 7, or 10^7. Therefore, the number is equivalent to 5.1033992 multiplied by 10^7, which is
51,033,992.

5.1033992E7 in real number


5.1033992E7 is scientific notation for the number 51,033,992.

Assignment Operators

Arithmetic Operators

In Java, arithmetic operators are used to perform basic mathematical operations on numerical data
types. These operators can be used with integers, floating-point numbers, and other numerical data
types.
Here are the arithmetic operators in Java:
 Addition (+): The addition operator is used to add two or more numerical values together. For example,
2 + 3 would evaluate to 5.
 Subtraction (-): The subtraction operator is used to subtract one numerical value from another. For
example, 5 - 2 would evaluate to 3.
 Multiplication (*): The multiplication operator is used to multiply two or more numerical values
together. For example, 3 * 4 would evaluate to 12.
 Division (/): The division operator is used to divide one numerical value by another. For example, 6 / 3
would evaluate to 2.
 Modulus (%): The modulus operator is used to find the remainder of a division operation between two
numbers. For example, 7 % 3 would evaluate to 1.
JAVA
int num1 = 7;
int num2 = 5;

int result = num1 + num2;

Here + is operator

Modules operator

Dividend
In math, the term "dividend" refers to the number being divided in a division operation. It is the number
that is being split into equal parts or groups. For example, in the division problem 10 ÷ 2 = 5, the number
10 is the dividend.
Divisor
In math, the term "divisor" refers to the number by which another number (called the dividend) is being
divided in a division operation. It is the number that determines how many equal parts or groups the
dividend will be split into. For example, in the division problem 10 ÷ 2 = 5, the number 2 is the divisor.

Difference between Division and Reminder

Division and remainder are two related concepts in math that are used when dividing one number by
another.

Division is a mathematical operation that involves dividing one number (the dividend) by another
number (the divisor) to find how many times the divisor goes into the dividend. The result of a division
operation is called the quotient. For example, when you divide 10 by 2, the quotient is 5, because 2 goes
into 10 five times.

Remainder, on the other hand, refers to the amount that is left over after division. It is the "leftover" or
"unused" part of the dividend that cannot be divided evenly by the divisor. For example, when you divide
10 by 3, the quotient is 3 with a remainder of 1, because 3 goes into 10 three times with 1 left over.

In Java, the modulus operator is used to find the remainder of a division operation between two numbers.
The modulus operator is represented by the percent sign "%". Here's an example:

int dividend = 10;


int divisor = 3;
JAVA
int remainder = dividend % divisor;
System.out.println(remainder); // Output: 1
In the above code, we have two variables dividend and divisor. We use the modulus operator % to find the
remainder of dividend divided by divisor. The result is assigned to the remainder variable. When we print
out the value of remainder, we get 1 as the output.

You can also use the modulus operator with floating-point numbers:
Code
double dividend = 10.5;
double divisor = 3.2;
double remainder = dividend % divisor;
System.out.println(remainder); // Output: 1.0999999999999996
In the above code, we have two variables dividend and divisor of type double. We use the modulus
operator % to find the remainder of dividend divided by divisor. The result is assigned to the remainder
variable. When we print out the value of remainder, we get 1.0999999999999996 as the output.
Note that the result of the modulus operator is the remainder after division, and not the modulus
operation itself.

--------------------------------------

----------------------------------------------------------
Relational Operators

In Java, relational operators are used to compare two values and determine whether they are equal or not, and
whether one value is greater than, less than, or equal to another value. Relational operators are often used in
control structures such as if statements, loops, and switch statements.

Here are the relational operators in Java:

 Equality (==): The equality operator is used to test whether two values are equal to each other. For example,
3 == 3 would evaluate to true.

 Inequality (!=): The inequality operator is used to test whether two values are not equal to each other. For
example, 3 != 4 would evaluate to true.

 Greater than (>): The greater than operator is used to test whether one value is greater than another value.
For example, 5 > 3 would evaluate to true.
JAVA
 Less than (<): The less than operator is used to test whether one value is less than another value. For
example, 3 < 5 would evaluate to true.

 Greater than or equal to (>=): The greater than or equal to operator is used to test whether one value is
greater than or equal to another value. For example, 5 >= 3 would evaluate to true.

 Less than or equal to (<=): The less than or equal to operator is used to test whether one value is less than or
equal to another value. For example, 3 <= 5 would evaluate to true.

Relational operators return a boolean value, which is either true or false. It's important to note that when
comparing two values for equality, the double equals sign (==) must be used, rather than a single equals sign, which
is used for assignment.

Relational Operator in Practice

Logical Operators

In Java, logical operators are used to combine multiple boolean expressions and determine whether they are true
or false. The logical operators in Java are:

AND (&&): The AND operator is used to check if both boolean expressions are true. For example, true && true would
evaluate to true, while true && false would evaluate to false.

OR (||): The OR operator is used to check if at least one of the boolean expressions is true. For example, true || false
would evaluate to true, while false || false would evaluate to false.

NOT (!): The NOT operator is used to negate a boolean expression. For example, !true would evaluate to false,
while !false would evaluate to true.

Logical operators are often used in conditional statements, such as if statements and while loops, to evaluate
multiple conditions at once. It's important to note that the expressions being evaluated with logical operators must
be boolean expressions, and not other data types.
JAVA
For example, int x = 5; is an assignment statement and cannot be used with logical operators. However, x > 3 is a
boolean expression and can be used with logical operators.

&& - AND Operator


JAVA

OR Operator - ||

NOT Operator
JAVA

In above code --- Result is false but in system out print () we mentioned !result – NOT result which reverse
the Boolean result

Conditional Statements

The Flow in AI Depends on True or False

The "if-else" statement is a fundamental concept in programming that allows a program to make decisions and
perform different actions based on the outcome of a condition.

The basic syntax of an "if-else" statement is:

if (condition) {

// code to execute if condition is true

} else {

// code to execute if condition is false

Here, the "condition" is a logical expression that can be evaluated to true or false. If the condition is true, the code
inside the first set of curly braces will be executed, otherwise, the code inside the second set of curly braces will be
executed.

There is a compulsion to Use “If “, when you want to use “else”, else can’t be alone
JAVA

Note

Why we don’t mention semicolum (;) after If statement ??

In Java, the semicolon (;) is used to terminate statements. If you put a semicolon immediately after the if statement,
it will be interpreted as an empty statement that does nothing.
JAVA

The Moment we have more than one statement in If statement we have to mention curly brackets {}
JAVA
If else with three statements – else if
JAVA
The ternary operator is a shorthand way of writing an if-else statement in many programming languages. It's
called "ternary" because it involves three operands: a condition, a result for true, and a result for false.

condition ? result_if_true : result_if_false

Here, condition is the boolean expression that is being evaluated. If the condition is true, then the expression
evaluates to result_if_true, and if it is false, the expression

ternary operator in java

In Java, the syntax for the ternary operator is the same as in most other programming languages:

condition ? result_if_true : result_if_false

int a = 5;

int b = 10;

int max = (a > b) ? a : b;

System.out.println(max); // output: 10

In this example, the condition (a > b) is evaluated first. If it's true, the expression evaluates to a, and if it's false, the
expression evaluates to b. In this case, since b is greater than a, the expression evaluates to b, and the value of max
is set to 10.

You can use the ternary operator to assign values to variables, as well as to return values from methods. It's a
concise way of expressing simple if-else statements, and is often used in Java code.

Switch Statements
Based on values 1-7 , we want to print Monday – Sunday
JAVA

Output
Thursday

Mistakes I made while writing code

1. Written actual
case ; case :

2. Written actual
system.out .println System.out.println
JAVA
Loop in Java
If you want to use same thing multiple times, we use loops

In Java, a loop is a programming construct used to execute a set of instructions repeatedly until a certain condition is
met. There are three types of loops in Java:

for loop - A for loop is used when the number of repetitions is known in advance.

while loop - A while loop is used when the number of repetitions is not known in advance. The loop will continue to
execute until the condition is false.

do-while loop - A do-while loop is similar to a while loop, but it executes at least once before checking the condition.

We mostly use “For Loop”

Steps/imp points to use loop.

 First put the code u want loop in a block which mean in curly braces { code } and outside the block or curly
braces you can use While

 generally we use Loops we use i as variable mostly.

 The variable name i is often used for loops because it stands for "index" or "iterator (also called repetitive)"
which are common terms in programming when referring to loop counters

here when we want to print Hi and values of” i “ we use + symbol which acts as printing output of char and num in
same line.

while loop
A while loop is used when the number of repetitions is not known in advance. The loop will continue to execute until
the condition is false.

Code
JAVA
Mistake I done initially in above code is to close statement in while loop after (i<=5), which I taken away after
chatgpt suggestion.

Nested While Loop with Output


JAVA
While Loop in my practice:

 The program starts by declaring an integer variable i and initializing it to 10.

 The while loop is used to execute the code block repeatedly as long as the condition (i >= 4) is true. In other
words, the loop will continue to run as long as i is greater than or equal to 4.

 Inside the while loop, the current value of i is printed using the System.out.println() statement.

 The value of i is then incremented by 1 using the i++ statement. This ensures that the loop will eventually
terminate if the if condition is not met.

 The if statement checks whether i is greater than or equal to 20. If it is, the break statement is executed, which
causes the program to exit the while loop immediately.

 Finally, the program terminates after the while loop has finished executing.

 So in summary, this program will print out the numbers 10 to 19, and then terminate. The if statement with the
break keyword is used to ensure that the loop stops executing once the value of i reaches 20.
JAVA

do-while loop
A do-while loop is similar to a while loop, but it executes at least once before checking the condition.

This will execute the code at least once - even condition is false

Here the condition of ‘i’ is greater than 4 is not true as we declared i = 2 is False but , the code is executed with
output 2 once
JAVA

for loop
A for loop is used when the number of repetitions is known in advance.

In for loop , we can mention three different statements in one sentence by using semicolons in between
JAVA
Nested For loop

Why We Do Debug In Java


 Debugging in Java (or any programming language) is an essential part of the development process. Here are
some reasons why debugging is important in Java:

 Finding and fixing errors: Debugging helps identify and fix errors or bugs in your code. It allows you to step
through your code line by line and see what's happening at each step, which can help you identify where errors
are occurring and why.
JAVA
 Improving code quality: Debugging can help you write better, more efficient code. By identifying and fixing
errors, you can improve the quality of your code and make it more reliable.

 Saving time and effort: Debugging can help you save time and effort by catching errors early on in the
development process. This can prevent you from having to spend hours or days tracking down issues later on.

 Enhancing performance: Debugging can also help you optimize the performance of your code. By identifying and
fixing bottlenecks or inefficiencies, you can improve the overall performance of your application.

 Overall, debugging is an essential part of the software development process, and it can help you write better,
more reliable code while saving time and effort.

Object-oriented programming (OOP)

 Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects, which
can contain data and code to manipulate that data.

 In simple terms, OOP is a way of organizing and structuring code so that it is easier to manage and maintain.
Instead of focusing on procedures or functions, OOP focuses on creating objects that can perform specific tasks
and interact with each other.

Class and Object

 Every Object Knows Something


 Every Object Does Something
 Every Object has a Property and It has Behaviour
 To create an Object , first we need to create a Class
 A Class is a Blueprint to Create and JVM Creates objects in Java
 A class is a blueprint or a template for creating objects, while an object is an instance of a class.
JAVA
Class

 We need to type class and we have to give a name to class and code we have to write in btw two curly
braces
 Class has 1. Variables (In class they are called Instance variables) and 2. Methods

In object-oriented programming (OOP), a class is a blueprint or a template for creating objects. The class defines the
attributes (variables) and behaviours (methods) of the objects that will be created from it.

Variables in a class are used to represent the state of an object, or its data. They can be any type of data, such as
strings, integers, booleans, or other objects. For example, if we have a class called "Person", we might define
variables to represent the person's name, age, and address.

Methods in a class are used to define the actions or behaviours that the objects can perform. Methods can take
parameters as input, and can also return values. For example, if we have a class called "Car", we might define
methods to represent the car's acceleration, braking, and turning.

Knows Something (eg: Structure, Logo , clour of a phone) = Variable


Does something (Calling, chat in Phone) = Method

Object

 Whatever the Object state is Variable


 Action performed by Object is Method
JAVA
Class
Class in Practical Code:

 The public static void main(String[] args) is a method signature in Java that is used to declare the main method in
a class. The main method is the entry point of the Java application, and it is the method that is executed when
you run the application.
--------------------------------------------------------------
public class Dog {

It defines a class named "Dog" with the "public" access modifier, which means that the class can be accessed from
any other class as its open/public in nature.
If you don’t know about access modifiers just put public as access modifier for creating class.
-----------------------------------------------------------------------------------------------------------------

 In Java, methods are a type of class member.


 After creating object we can access the data in class
 Object is a Superclass for any Class we make.

----------------------------------------------------------------------------------------------------------------------
Error I made while doing program

public static void main(String[] args) ;

The public static void main(String[] args) is a method signature in Java that is used to declare the main method in a
class. The ; at the end of the method signature is not required and would actually result in a syntax error if you put.
JAVA
Data Types

 When we create a Variable, what kind of data we store in that variable has to be told to computer using Data
Types.
 We specify Datatype before variable name
 Data Type is classification of Data which tells compiler/Interpretator how programmers intend to use the
Data

 Data Types are used to do Memory Management


 If we assign higher values for all data – our application memory we run out soon.

In Java, data types can be classified as primitive data types and non-primitive (or reference) data types.

Primitive data types are the most basic data types in Java, and they represent single values. There are eight primitive
data types in Java:

 byte: 8-bit integer value


 short: 16-bit integer value
 int: 32-bit integer value
 long: 64-bit integer value
 float: 32-bit floating-point value
 double: 64-bit floating-point value
 char: 16-bit Unicode character
 boolean: true or false value

How to write the Primitive Datatypes in Java Code

(Char store one ASCII value or One word)


JAVA
Non-primitive (or reference) data types, on the other hand, are not basic data types and they represent objects in
Java. They are called reference types because they refer to objects in memory. Examples of non-primitive data types
include:

 String: a sequence of characters


 Arrays: a collection of elements of the same data type
 Classes: a user-defined data type
 Interfaces: a collection of abstract methods and constants
 Enumerations: a special class that defines a set of constants

 The main difference between primitive and non-primitive data types is that primitive data types are built-in
to the Java language, and they are not objects, whereas non-primitive data types are created by the
programmer, and they are objects. Primitive data types are also passed by value, whereas non-primitive data
types are passed by reference.
 Predefined Size and usage is not defined before hand in Non Primitive Data Types
 We have to define data in Non primitive data types with primitive datatypes only

How to Find Min and Maximum values of Data Types in Java with Wrapper classes.
JAVA
Variables

 Class has members, This members are Variables and Methods.


 Variables are properties or Variables are used for storing Information/ Presenting the Data and Behaviour is
method.
 A variable is a container which holds the value while java program is being executed.

Types of Variables in Java

Global Variables
1. Instance Variables
2.Class Variables
Local Variables
1.Local Variables
2. Parameters

Syntax for Variable

data_type variable_name = value;

Here's a breakdown of the different parts of the syntax:

 datatype: This is the type of data that the variable can hold, such as int, double, String, or a user-defined
class type.

 variable name: This is the name given to the variable. It must be a valid identifier and follow naming
conventions such as starting with a letter or underscore, not containing spaces, and using camel case for
multi-word names.

 =: This is the assignment operator, which assigns the value on the right side to the variable on the left side.

 value: This is the initial value assigned to the variable. It must match the data type of the variable. If no initial
value is provided, the variable will be assigned a default value based on its data type.
 We can access the Data in Variable by printing variable name in S.out.println

Reassigning the Variable value will override prev value and give new value
JAVA
Instance Variables (Non Static Field)

 This are not created inside method , They have to be created inside class
 We don’t use static key word in this variable
 Instance variable can be accessed only by creating instance /object

In Java, objects are created using the new keyword followed by a call to the constructor of the class. The syntax for
creating an object is as follows:

ClassName objectName = new ClassName();

Here's a breakdown of the different parts of the syntax:

ClassName: This is the name of the class that the object belongs to.

objectName: This is the name given to the object. It must be a valid identifier and follow naming conventions such as
starting with a letter or underscore, not containing spaces, and using camel case for multi-word names.

new: This is the keyword used to create a new instance of the class.

ClassName(): This is the constructor of the class that initializes the object. Constructors have the same name as the
class and do not have a return type.
JAVA
Class Variables – Static Fields

 These variables are also created inside class , outside the method
 Only difference btw Class variable and Instance (Non Static) are static key word
 Static variable doesn’t ask u to create any object to access data. They don’t need any reference
 Variables created inside Class are called Global Variables

Local Variables

Local Variables:

 When you create a variable inside method, Its local variable


 We never provide static keyword to Local variables
 Its scope is only in one method
JAVA

Parameters

Parameters will be in method itself

public static void main (String[] args)

Here args is parameter

------------------------------------------------------------

We cant assign values to parameters – The below cod

Main Method
JAVA
 The main method is a special method in Java that is required in every program. It is the entry point for the
program, and it is called by the Java Virtual Machine (JVM) when the program is started.
 The public keyword in the signature indicates that the main method can be accessed from anywhere, even from
outside the class. The static keyword means that the method belongs to the class rather than individual objects
of the class. The void keyword means that the method does not return any value.
 The String[] args parameter in the signature allows command-line arguments to be passed to the program when
it is executed. The args parameter is an array of strings that contains the command-line arguments.
 Inside the main method, you can write code to perform any desired functionality for the program. When the
main method finishes executing, the program terminates

Naming conventions for Variables

Variables are case sensitive

1. Lower case and Upper case are different in Java

2. If our variable name is single word , it should be in lower case


3. Camel case
JAVA
If there are multiple words in variable name – first word will be lower case and subsequent words has to Capital.

4. No Variable name should be java key words

5. Variable names should be self explanatory for Data it holds.It should not to be shortcuts or misspelled
words.
6. We can use special characters in variables like _ $
but java recommendation is don’t use at starting use in subsequent way.
We use symbol _ for constants like PI values etc
Where we know PI value is 3.14;

Methods
 Behaviour in Real world = Methods in Java
 Members of class are Variables and Methods
 A block of code created for performing actions
 We create method inside class
 We can create N number of methods in Class
 We create a method which has proper relation with the class
JAVA

 In image orange fields/words are optional


 We have to create name for every class , variable and method
 Method Body: Action we want to perform / code we use to perform an action

Lets understand Methods with a Banking Application

void = reserved word in java – when we don’t want any data to return from our code (void is not a data type)

Even though u create a method you will not be getting the permission to run the code until you create a Main
method

Remember only code in main method is executed is executed by default, no other methods will be executed
instantly as main method, you have to call the data.

For eg below code give no output

How to write it
JAVA
Creating Method in Non Static

For example if we want to give inputs to a method we use parameters.

Explanation

This is a Java code for a Bank class with some functionalities like deposit, withdrawal, and getting current balance.

The class has a static variable "currentBalance" which is initially set to 1000. It also has three methods:
JAVA
greetCustomer() - A static method that just prints a welcome message to the console.

deposit(int amount) - A non-static method that takes an integer parameter "amount" and adds it to the current
balance. It also prints a message to the console indicating that the deposit was successful.

withdrawl(int amount) - A static method that takes an integer parameter "amount" and subtracts it from the current
balance. It also prints a message to the console indicating that the withdrawal was successful.

Additionally, there is a non-static method "getcurrentBalance()" that returns the current balance as an integer value.

In the main method, an object of the Bank class is created to access the non-static methods. The greetCustomer()
method is called using the class name because it's a static method. The deposit and withdrawal methods are called
using the object of the Bank class. Finally, the current balance is printed to the console using the getcurrentBalance()
method.

Constructor

Constructor is also a Block of code similar to method, it is called when instance of the class is created.
We have to call constructor whenever we want to create an object.
Why we need constructors

 We create object to create memory for a class


 All operations we need to be done to create memory for variables in Class we use constructors
 Java creates objects for us internally when we mention class name (); while object creation.
 Constructor name has to be same as class name
 No return type concept available for Constructors so u never mention void keyword
 Any Constructor created by java are parameter less only.

Default or Implicit Constructor


When we don’t create a constructor, Java internally create constructor for us.
Java constructor will always be in public
If we define constructor in class, java stops adding constructors itself.

syntax of default constructor created by Java

public classname ();

Explicit Constructor:

An explicit constructor is defined explicitly in the class. It is also known as a user-defined constructor. When an
explicit constructor is defined, the Java compiler does not create a default constructor for the class.

modifier ClassName(parameters)
{

// constructor body

 Here, modifier can be public, protected, private, or no modifier (also known as the default modifier).
 ClassName is the name of the class for which the constructor is defined.
 parameters are the input values passed to the constructor.
JAVA
Example code for printing an int value with the help of creating object with Default constructor

---------------------------------------------------------------------------------------------------------------------------------------

Parameter and Parameter less

Example code for printing an int value with the help of creating object with

Explicit constructor (Parameter less)

Explicit constructor (Parameterized)


JAVA

 Just like method , you can perform any action like print as well in constructor because its also a block of code
 We can’t define static or non static to Constructors
 We call constructors while creating object itself unlike methods which are called after creating object.
 Constructors are used for Memory allocation during object creation.

Object

 We use object to create memory allocation class


 We cant access the Variables or methods in class, memory for them has to be be created and we can access that
memory using object

Objects and constructors are closely related in object-oriented programming, as constructors are used to create and
initialize objects. Here's how they work:

How objects work:

 Objects are instances of a class and are created using the new keyword followed by the name of the class.
 Once an object is created, it has its own set of attributes and behaviors that are defined by the class.
 Objects can be manipulated by calling their methods, accessing their attributes, and passing them as parameters
to other methods.

How constructors work:

 Constructors are special methods that are called when an object is created using the new keyword.
 Constructors have the same name as the class and are used to initialize the object's attributes and prepare it for
use.
 Constructors can take parameters that are used to set the initial state of the object.
 Constructors can also perform other tasks such as allocating memory, opening files, and establishing connections
to databases.

Actions on One object will not effect other object, If we work on one object we have to be on that object itself.

Hash Code
In Java, the hashCode() method is used to generate a unique integer value for an object. This integer value is called
the object's hash code. The hashCode() method is defined in the Object class, which is the root class of all Java
classes, and can be overridden by subclasses to provide their own implementation.

See the syntax of hashCode correctly ---------------hash (small) first letter in Code (C is capita)
Example
JAVA

What will be there in Object when its created


JAVA
Example with output in VS Code

Summarize

 Object is a Class Instance


 Class is Blueprint having variables and methods
 To access the Variables and methods we must allocate memory to them
 The process of memory allocation is object creation
 Then only we can access variables and methods
 The memory allocation is done by object and internally we call contractor to create memory
 We use class and invoke constructor to create object and store that object in a variable
 Object contain variables and methods

--------------------------------------------------------------------------------------------------------------------------------------

You might also like