Java Notes 2
Java Notes 2
Java compiler translates source code into byte code.The JVM (DTL) loads
and executes the byte code. Optionally, some JVMs may choose to
interpret the byte code directly for certain use cases.This combination
of compilation and interpretation allows Java programs to be both
platform-independent (byte code run on any machine).
|| DAY 1 ||
JDK :https://www.oracle.com/java/technologies/downloads/#jdk21-windows
IDE :https://www.jetbrains.com/idea/download/?section=windows
}
}
Entry Point
The main method is the entry point for executing a Java application.
When you run a Java program, The JVM or java compiler looks for
a public static void main(String args[]) method in that class, and the
signature of the main method must be in a specified format for the JVM
to recognize it as its entry point.
If we update the method's signature, the program will throw the
error NoSuchMethodError:main and terminate.
|| DAY 2 ||
Comments
Single-line comment: Use // to add a single-line comment.
Example : // This is single line comment
1. Variable Declaration:
int age;
String name; //int and string is data types
2. Variable Initialization:
age = 69;
name = "the boys";
3. Combined Declaration and Initialization:
|| DAY 3 ||
6. Length – No Limit
|| DAY 4 ||
Literal or Constant:
Any constant value which can be assigned to the variable.
DATA TYPES
Data types are used to classify and define the type of data that a
variable can hold.
There are 2 types of Data Types:
Default Values
Default Value (for
Data Type
fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
char a = 'a';
char b = 'b';
System.out.println(a+b);//97+98=195
Output : 195
|| DAY 5 ||
Scanner
To take input from users we use Scanner class.
To use the Scanner class, you need to create an object of it, and then
you can use that object to interact with the input data.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);//object
int n = sc.nextInt();
The nextInt() method parses the token from the input and returns the
integer value.
Java does not give us a chance to input anything for the name variable.
When the method input.nextLine() is called Scanner object will wait for
us, to hit enter and the enter key is a character(“\n”).
Example
Scanner scanner = new Scanner(System.in);
Console :
Enter an integer: 69
Enter a string: age is = 69
1. We first prompt the user to enter an integer age using nextInt().
2. After reading the integer, we immediately hit enter and enter is
also a character represented by “\n” – 69\n
3. The int value 69 is assigned in age but not the \n still left in the
memory or buffer.
4. In next line when we Call nextLine() to consume the name it first
check in buffer is there any thing as we have \n in buffer it take \n
(for nextLine() method \n is the stopping point it will consider we
stop giving input and return) and skip the line.
Solution :
Scanner scanner = new Scanner(System.in);
\ is a special symbol
\n (next Line), \b (backspace), \t (tab), \" (double quote), \' (single
quote), and \\ (backslash).
|| DAY 6 ||
Operators
Operators can be easily defined as characters that represent an
operation. These symbols perform different operations on several
variables and values.
Types of Operator
1. Arithmetic Operator :
Arithmetic operator can be divided into two categories -
● Unary Operators :
Increment Operator (++) : Increase the value by 1.
Decrement Operator( - -) : Decrease the value by 1.
4. ShortHand operators
The assignment operator can be combined with other operators to
build a shorter version of the statement. +=, -=, *=, /=, %=
|| DAY 7 ||
Package
A Java package is a collection of similar types of sub-packages,
interfaces, and classes. They help you manage and group related
classes, interfaces, and sub-packages to avoid naming conflicts and
create a more organized and maintainable codebase.
Example:
Math Class
java.lang.Math class is a built-in class. It provides mathematical
functions and constants for mathematical operations.
Math.ceil(a) Returns the closest value that is greater than or equal to the
argument
Math.random() Returns a double value with a positive sign, greater than or equal to 0.0
CONTROL-FLOW STATEMENTS
Control Flow statements in programming control the order of execution
of statements within a program. They allow you to make decisions,
repeat actions, and control the flow of your code based on conditions.
For example :
int number = 10;
if (number % 2 == 0) {
System.out.println("Number is even.");
}
else if (number % 2 != 0) {
System.out.println("Number is odd.");
}
else {
System.out.println("Invalid input.");
}
If Ladder :
|| DAY 11 ||
Ternary Operator
The ternary operator, also known as the conditional operator, is a
shorthand way of writing an if-else statement with a single expression.
Output : Even
Type Conversion
Type casting in Java is the process of converting one data type to
another. It can be done automatically or manually.
Order :byte->short->int->long->float->double
char->int
Example :
int intValue = 42;
double doubleValue = intValue; // Implicit conversion
2.Explicit or Narrowing Conversion:
● Sometimes, we need to convert a larger data type to a smaller one
explicitly and it requires a cast operator.
● Narrowing Type Casting in Java is not secure as loss of data can
occur due to a shorter range of supported values in lower data
type.
Example :
double doubleValue = 42.0;
int intValue = (int) doubleValue; // Explicit
conversion (casting)
|| DAY 12 ||
Loops
When we want to perform certain tasks again and again till a given
condition.
For e.g. : Our daily routine, certain song listen again & again
Looping is a feature that facilitates the execution of a set of instructions
repeatedly until a certain condition holds false.
e.g. : print 1 to 10,000 number
Types of Loop
Categorized into two main types
1.Entry Controlled
Check the loop condition before entering the loop body. If the condition
is false initially, the loop body will not execute at all.
for and while loops are examples of entry-controlled loops as we check
the condition first and then evaluate the body of the loop..
a. for loop
When we know the exact number of times the loop is going to run, we
use for loop.
Syntax:
for(declaration,Initialization ; Condition ; Change){
// Body of the Loop (Statement(s))
}
Example :
for (int i = 1; i<= 5; i++) {
System.out.println(i);//run 1 to 5
}
Output : 1 2 3 4 5
FLOW DIAGRAM
Optional Expressions :
In loops, initialization, condition, & update are optional. Any or all of
these are skippable.The loop essentially works based on the semicolon ;
// Empty loop
for (;;) {}
// Infinite loop
for (int i = 0;; i++) {}
Syntax tweaks
● Initialize the variable outside the loop.
● Multiple conditions.
● Increment or Decrement of variable inside loop body
An infinite loop is a loop that continues executing indefinitely, and it
doesn't have a condition that will terminate the loop naturally.
for (;;){
System.out.println("This is an infinite loop");
}
In the above code there is no initialization, no condition, and no
iteration expression, meaning it will run indefinitely unless explicitly
terminated.
for(;;);
|| DAY 13 ||
while loop
The while loop is used when the number of iterations is not known but
the terminating condition is known.
Loop is executed until the given condition evaluates to false.
Syntax:
initialization
while (condition){
// Body of the loop
// Updation
}
Example :
int i=0;
while (i<5){
System.out.println(i);
i++;
}
Output :0 1 2 3 4
FLOW DIAGRAM
While always accepts true, if you initially give a false condition (not
Boolean false) it will neither give a syntax error nor enter in the loop.
int i=0;
while (i>9){// false condition but no syntax error
System.out.println(i);
}
While loop always accepts true ,if you initially give false(Boolean value)
it will give syntax error.
while (false){ //Syntax error
System.out.println(“Hello LOLU”);
|| DAY 14 ||
do-while Loop
The do-while loop is like the while loop except that the condition is
checked after evaluation of the body of the loop. Thus, the do-while
loop is an example of an exit-controlled loop.
This loop runs at least once irrespective of the test condition, and at
most as many times the test condition evaluates to true.
Syntax :
Initialization;
do {
// Body of the loop (Statement(s))
// Updation;
}
while(Condition);
Example :
int i=1;
do {
System.out.println("Hii");
i++;
}while (i<3);
There will be no output for the above code also, the code will never
end. Value of initialize to 0 then increment by 1 so it can never be -1
hence the loop will never end.