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

Java Notes 1

Java is a high-level, object-oriented programming language created by Sun Microsystems in 1995, known for its WORA (Write Once Run Anywhere) capability. It consists of three main components: JVM (Java Virtual Machine), JRE (Java Runtime Environment), and JDK (Java Development Kit), each serving different purposes in program execution and development. The document also covers variables, data types, operators, and control flow statements in Java.
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 views15 pages

Java Notes 1

Java is a high-level, object-oriented programming language created by Sun Microsystems in 1995, known for its WORA (Write Once Run Anywhere) capability. It consists of three main components: JVM (Java Virtual Machine), JRE (Java Runtime Environment), and JDK (Java Development Kit), each serving different purposes in program execution and development. The document also covers variables, data types, operators, and control flow statements in Java.
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

Sunday, May 24, 2026 12:01 PM

What is java
JAVA is the high level ,object oriented programming language
It is created by sun microsystems in 1995
Its biggest promise is Write Once Run Anywhere (WORA),That means one we write the program we can execute in any platform like
windows ,linux,mac,andriod without rewriting it with the help of JVM.

There are three pillars in java


 JVM
 JRE
 JDK

JVM
JAVA VIRTUAL MACHICE is the engine to runs our program
It doesn’t not run the .java file and even it cannot understand the .java file
it runs the .class file which contain bytecode

Key jobs of JVM

class loader
it loads the .class file into the memory
bytecode verifier
it checks the byte code for security issues
JIT(JAVA IN TIME) compiler
It converts the bytecode into machine code in runtime for speed
Garbage collector
It automatically frees memory which is no longer use
Runtime area
It manages stack area(class area),heap area(object area),Method area,etc.
NOTE
JVM is platform-specified there are different jvm for different platforms like linux windows mac android
but the byte code it contains is same for all the platform

JRE

JAVA RUNTIME ENVIRONMENT is the combination of JVM and java standard libraries
It includes everything which is need to run the java program not to devlop the program
if anyone want to just run the java program not to devlop the java program , they just install the JRE

Libraries include

[Link] - String ,Math,Object (auto -imported in all program)


[Link]- Arrays,Hashmap,Scanner
[Link]- file reading and writing
[Link] - sockets and networking

JDK
JAVA DEVLOPMENT KIT is a complete software which is installed in java developer machine to write compile debug and run the
program

it is the combination of JRE and java development tool


javac
javadoc
jdb
jar
jps
jstat
jconsole
jshell

java Page 1
VARIABLES
variables are the containers used to store the data.

In Java, there are different types of variables, for example:


• String - stores text, such as "Hello". String values are surrounded by double quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
• boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable in Java, we need to:
• Choose a type (like int or String)
• Give the variable a name (like x, age, or name)
• Optionally assign it a value using =

Syntax
type variableName = value;

Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for naming variables are:


• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter, and cannot contain whitespace
• Names can also begin with $ and _
• Names are case-sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or boolean) cannot be used as names

java Page 2
Constants (final keyword)
When we do not want a variable's value to change, use the final keyword.
A variable declared with final becomes a constant, which means unchangeable and read-only:

Example
final int myNum = 15;
myNum = 20; // Error: cannot assign a value to final variable 'myNum'

DATA TYPES
Datatypes are the classification that specify kind of value the variable stores and memory space it
requires
Java is a statically typed language that means every variable must be declared with a specifc data type
before it can be used

Data types are divided into two groups:


• Primitive data types - includes byte, short, int, long, float, double, boolean and char
• Non-primitive data types - such as String, Arrays and classes

Primitive Data Types


A primitive data type specifies the type of a variable and the kind of values it can hold.
There are eight primitive data types in Java:
Data Type Description
byte Stores whole numbers from -128 to 127
short Stores whole numbers from -32,768 to 32,767
int Stores whole numbers from -2,147,483,648 to 2,147,483,647
long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits
boolean Stores true or false values
char Stores a single character/letter or ASCII values

We Cannot Change the Type


Once a variable is declared with a type, it cannot change to another type later in the program:

Example
int myNum = 5; // myNum is an int
// myNum = "Hello"; // Error: cannot assign a String to an int
String myText = "Hi"; // myText is a String
// myText = 123; // Error: cannot assign a number to a String

Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type we should use,
depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double

Boolean Types
java Page 3
Boolean Types
Very often in programming, we will need a data type that can only have one of two
values, like:
• YES / NO
• ON / OFF
• TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or false

Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c'

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.
The main differences between primitive and non-primitive data types are:
• Primitive types in Java are predefined and built into the language, while non-primitive types are created by the
programmer (except for String).
• Non-primitive types can be used to call methods to perform certain operations, whereas primitive types cannot.
• Primitive types start with a lowercase letter (like int), while non-primitive types typically starts with an uppercase letter
(like String).
• Primitive types always hold a value, whereas non-primitive types can be null.
Examples of non-primitive types are String,Array,classes etc

The var Keyword


The var keyword was introduced in Java 10 (released in 2018).
The var keyword lets the compiler automatically detect the type of a variable based on the value we assign to it.
This helps we write cleaner code and avoid repeating types, especially for long or complex types.
For example, instead of writing int x = 5;, we can write:

Example
var x = 5; // x is an int
[Link](x);

Java Type Casting


Type casting means converting one data type into another. For example, turning an int into
a double.
In Java, there are two main types of casting:
○ Widening Casting (automatic) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
○ Narrowing Casting (manual) - converting a larger type to a smaller type size
double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type into a larger size type.
This works because there is no risk of losing information. For example, an int value can safely fit
inside a double:

Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0

java Page 4
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses () in front of the
value.
This is required because narrowing may result in data loss (for example, dropping decimals when
converting a double to an int):

Example
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9

Java Operators
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison or Relational operators
• Logical operators
• Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Example
int x = 10;
int y = 3;
[Link](x + y); // 13 add
[Link](x - y); // 7 sub
[Link](x * y); // 30 mul
[Link](x / y); // 3 div
[Link](x % y); // 1 mod
int z = 5;
++z; //inc
[Link](z); // 6
--z; //dec
[Link](z); // 5

Assignment Operators
Assignment operators are used to assign values to variables.

java Page 5
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find
answers and make decisions.
The return value of a comparison is either true or false. These values are known as Boolean values

A list of all comparison operators:


Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators
As with comparison operator, we can also test for true or false values with logical operators.

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Bitwise operators
— work on bits
Operator Name Example (a=5, b=3) Result
& AND 5 & 3 (0101 & 0011) 1 (0001)
| OR 5 | 3 (0101 | 0011) 7 (0111)
^ XOR 5 ^ 3 (0101 ^ 0011) 6 (0110)
~ NOT (complement) ~5 -6
<< Left shift 5 << 1 10 (multiply by 2)
>> Right shift 10 >> 1 5 (divide by 2)
>>> Unsigned right shift -1 >>> 28 15

Ternary operator
— one-line if-else

java Page 6
— one-line if-else

Syntax: condition ? valueIfTrue : valueIfFalse

example
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
String result = (a%2==0) ? "Even" : "Odd"; // "Even"
// Nested ternary (avoid — hard to read)
String grade = (marks>=90)?"A":(marks>=80)?"B":"C";

Java Operator Precedence


When a calculation contains more than one operator, Java follows order of operations rules to decide which part to calculate first.

Order of Operations
Here are some common operators, from highest to lowest priority:
• () - Parentheses
• *, /, % - Multiplication, Division, Modulus
• +, - - Addition, Subtraction
• >, <, >=, <= - Comparison
• ==, != - Equality
• && - Logical AND
• || - Logical OR
• = - Assignment

Java Math
The Java Math class has many methods that allows you to perform mathematical tasks
on numbers.

[Link](x,y)
The [Link](x,y) method can be used to find the highest value of x and y

[Link](x,y)
The [Link](x,y) method can be used to find the lowest value of x and y

[Link](x)
The [Link](x) method returns the square root of x

[Link](x)
The [Link](x) method returns the absolute (positive) value of x

[Link](x, y)
The [Link](x, y) method returns the value of x raised to the power of y

java Page 7
Rounding Methods
Java has several methods for rounding numbers:
• [Link](x) - rounds to the nearest integer
• [Link](x) - rounds up (returns the smallest integer greater than or equal to x)
• [Link](x) - rounds down (returns the largest integer less than or equal to x)

Random Numbers
[Link]() returns a random number between 0.0 (inclusive), and 1.0 (exclusive)

To get more control over the random number, for example, if you only want a random number
between 0 and 100, you can use the following formula:

Example
int randomNum = (int)([Link]() * 635); // 0 to 635

Note: [Link]() returns a double. To get an integer, you need to cast it with (int).

Java Conditions and If Statements


Conditions and if statements let you control the flow of your program - deciding which code runs, and which code is skipped.
Think of it like real life: If it rains, take an umbrella. Otherwise, do nothing.
Every if statement needs a condition that results in true or false.

Most often, conditions are created using comparison operators, like the ones below:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to: a == b
• Not equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement
The if statement specifies a block of code to be executed if a condition is true:

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Example
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
[Link]("Both lines are part of the if");
}
// Some code outside if
[Link]("I am outside if, not part of if!");

java Page 8
OUTPUT
x is greater than y
Both lines are part of the if
I am outside if, not part of if!

The else Statement


The else statement lets you run a block of code when the condition in the if statement is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Think of it like real life: If it rains, bring an umbrella. Otherwise (else), go outside without one:

Example
boolean isRaining = false;
if (isRaining) {
[Link]("Bring an umbrella!");
} else {
[Link]("No rain today, no need for an umbrella!");
}

Notes
• else does not have a condition - it runs when the if condition is false.
• Do not put a semicolon right after if (condition). That would end the statement early and
make else behave unexpectedly.

The else if Statement


Use the else if statement to specify a new condition to test if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if condition1 is false and condition2 is true
} else {
// block of code to be executed if both conditions are false
}
Think of it like real life: If it rains, bring an umbrella. Else if it is sunny, wear sunglasses. Else, just go outside normally.

Example
int weather = 2; // 1 = raining, 2 = sunny, 3 = cloudy
if (weather == 1) {
[Link]("Bring an umbrella.");
} else if (weather == 2) {
[Link]("Wear sunglasses.");
} else {
[Link]("Just go outside normally.");
}
// Outputs "Wear sunglasses."

java Page 9
Short Hand if...else
There is also a short-hand if…else. which is known as the ternary operator because it consists of three operands.
It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Example

int time = 20;


String result = (time < 18) ? "Good day." : "Good evening.";
[Link](result);

Nested Ternary (Optional)


You can nest ternary operators to handle more than two possible outcomes, but this can make your code harder to read:

Example
int time = 22;
String message = (time < 12) ? "Good morning."
: (time < 18) ? "Good afternoon."
: "Good evening.";
[Link](message);

Nested If
You can also place an if statement inside another if. This is called a nested if statement.
A nested if lets you check for a condition only if another condition is already true.

Syntax
if (condition1) {
// code to run if condition1 is true
if (condition2) {
// code to run if both condition1 and condition2 are true
}
}

Example
In this example, we first check if x is greater than 10. If it is, we then check if y is greater than 20:
int x = 15;
int y = 25;
if (x > 10) {
[Link]("x is greater than 10");

// Nested if
if (y > 20) {
[Link]("y is also greater than 20");
}
}
Result:
x is greater than 10
y is also greater than 20

java Page 10
Java Switch Statements
Instead of writing many if..else statements, you can use the switch statement.
Think of it like ordering food in a restaurant: If you choose number 1, you get Pizza. If you choose 2, you get a Burger. If you choose 3, you
get Pasta. Otherwise, you get nothing.
The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
• The switch expression is evaluated once.
• The result is compared with each case value.
• If there is a match, the matching block of code runs.
• The break statement stops the switch after the matching case has run.
• The default statement runs if there is no match.
The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
// Outputs "Thursday" (day 4)

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

java Page 11
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;
switch (day){
case 6:
[Link]("Today is Saturday");
break;
case 7:
[Link]("Today is Sunday");
break;
default:
[Link]("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
Note that if the default statement is used as the last statement in a switch block, it does not need a break.

Loops
Loops can execute a block of code as long as a specified condition is true.
Loops are handy because they save time, reduce errors, and they make code more
readable.

Java While Loop


The while loop repeats a block of code as long as the specified condition is true:

Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run again and again, as long as a
variable (i) is less than 5:

Example
int i = 0;
while (i < 5) {
[Link](i);
i++;
}

Note: Do not forget to increase the variable used in the condition (i++),
otherwise the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true. Then it will repeat the loop as
long as the condition is true.

Syntax
do {
// code block to be executed
}

java Page 12
}
while (condition);
Note: The semicolon ; after the while condition is required!

Do/While Example
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed before
the condition is tested:

Example
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);

Condition is False from the Start


In the while loop chapter, we saw that if the condition is false at the beginning,
the loop never runs at all.
The do/while loop is different: it will always run the code block at least once,
even if the condition is false from the start.
In the example below, the variable i starts at 10, so i < 5 is false immediately.
Still, the loop runs once before checking the condition:

Example
int i = 10;
do {
[Link]("i is " + i);
i++;
} while (i < 5);
Summary: A do/while loop always runs at least once, even if the condition is false
at the start. This is the key difference from a while loop, which would skip the
code block completely in the same situation.
This behavior makes do/while useful when you want something to happen at least
once, such as showing a message or asking the user for input.

Java For Loop


When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

Print Numbers
The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {
[Link](i);

java Page 13
[Link](i);
}

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
// Outer loop
for (int i = 1; i <= 2; i++) {
[Link]("Outer: " + i); // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times (2 * 3)
}
}

The for-each Loop


There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):

Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The for-each loop is simpler and more readable than a regular for loop, since you don't need a counter (like i
< [Link]).
The following example prints all elements in the cars array:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
[Link](car);
}
Here is a similar example with numbers. We create an array of integers and use a for-each loop to print each value:

Example
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
[Link](num);
}

Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
[Link](i);
}

OUTPUT
0

java Page 14
0
1
2
3

Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
[Link](i);
}

OUTPUT
0
1
2
3
5
6
7
8
9

java Page 15

You might also like