Java Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Java NOTES

Type Casting: Type casting is when you assign a value of one primitive data type to another
type

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Reverse Number:
while (num > 0) {

int rem = num % 10;

Ans = ans * 10 + rem;

Num = num / 10;

}
System.out.println(ans);
Squarem Pattern:
for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= 5; j++) {

if (i == 1 || j == 1 || i == 5 || j == 5) {

System.out.print("*");
} else {
System.out.print(" ");
}

}
System.out.println();

static keyword : The static keyword in Java is used for memory management mainly
We can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
Java NOTES
1.Java static variable:
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college
name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
 It makes your program memory efficient (i.e., it saves memory).

When use static variable:


1.Common Data for All Instances:
 If you have data that is common to all instances of a class and does not change across
instances, you might use a static variable. For example, a counter to keep track of the number
of instances created.
2.Constants:
 If you have constants that are the same for all instances of a class, you can declare them as
static variables.

2) Java static method


 A static method belongs to the class rather than instances.
Thus, it can be called without creating instance of class

here are some restrictions of static methods :

 Static method can not use non-static members (variables or functions)


of the class.
 Static method can not use this or super keywords.
When static method use: if you need a method, which you want to call directly by class name,
make that method static.

3) Java static block


o is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Java NOTES
Constructor: Constructor is used to initialize value of object & special member of class whose name
is same as class name and it does not have return type The constructor is called when an object
of a class is created.

You might also like