LEARN JAVA WITH JOY
Introduction of java
(Java was developed by the e ort of 5great people James Gosling, Patrick Naughton Chriswarth , Mike
sheridhan and Ed Frank. Team also called as green team)
Java is also called as “Oak” (1995)
Slogan “write once run anywhere”
Java: Java is a high-level, class-based, object-oriented programming
language and computing platform,
Features of java:
java is a simple: Java is simple because it removes complex C++
features like explicit pointers and multiple inheritance while providing
a Garbage Collector to manage memory automatically. Its clean
syntax and massive standard libraries allow developers to focus on logic
rather than low-level system management.
Java is object oriented : Java treats everything as an "object" that
combines data and actions, just like real-world [Link] has all the
features of oops such as abstraction ,encapsulation ,inheritance ,and
polymorphism.
1
LEARN JAVA WITH JOY
Java is platform independent: this means that code written in java can be
executed on di erent o/s without any modification .this feature is often
re erd to as write once run anywhere(WORA)
Java is secure: it is the first language to consider security [Link] raduse
the risk of security compromise, loss of data and program integrity, and
damage to system user.
Java is Robust: Robust means strong . A robust program is one does not
[Link] programs are strong and they do not easily crash like ac or c ++.
Architecture Natural: java program do not depend on any system
architecture. It runs consistently across di erent hardware configurations.
Compalie and interpreted: java is both complied and interpreted. The java
virtual machine (JVM) executes the bytes code.
(byte code : it is set of machine instructions that are not specific to any
one processor pr os. Java programs are converted into byte code)
Multi threaded: java supports multi treads running at the same [Link]
improves the program e iciency and performance.
Distributed language : java supports network based [Link]
provides built in supports for TCP/IP communication. It allows file sharing
over networks.
Dynamic and extensible : java can dynamically load classes ,methods,
And object at the runtime ,making at flexible
Portable: java program can run on any system with a java virtual machine
(JVM), it does not required system specific changes.
Feature C Programming Java Programming
1. Paradigm Procedural: Focuses on functions Object-Oriented: Focuses on
and steps. classes and objects.
2
LEARN JAVA WITH JOY
2. Portability Platform-dependent: Code must be Platform-independent: "Write
recompiled for each OS. Once, Run Anywhere" via JVM.
3. Memory Manual: Programmer Automatic: Handled by Garbage
uses malloc and free. Collection.
4. Compilation Compiled directly to machine code. Compiled to bytecode, then
interpreted/JIT compiled.
5. Pointers Supports direct pointer Does not support explicit pointers
manipulation. (for security).
6. Speed Faster: Low-level with direct Slower: Overhead from JVM and
hardware access. garbage collection.
7. Errors No built-in exception handling (uses Robust built-in exception
error codes). handling (try-catch).
8. Threads No native support; requires external Built-in support for multi-
libraries. threading.
9. Approach Top-down: Breaks down into smaller Bottom-up: Builds systems from
functions. individual objects.
10. Storage Supports structs and unions for data. Uses classes; does not support
structs or unions.
The Java Development Kit (JDK) is the complete software toolkit containing a compiler and debugger used to write and build Java applications. Components of java:
java [Link] is a compiler it converts source code into byte code.
[Link]: is the java application [Link] runs the program by executing the byte code .
[Link]: is an [Link] packages java files for distribution.
[Link] is a documentation [Link] creates HTML based documentation form java source code.
It includes the Java Runtime Environment (JRE), which provides the necessary engine and libraries to actually execute and run those programs.
java application programming interface: it is a collection of predefined classes ,method , and interface that comes with the
jdk
3
LEARN JAVA WITH JOY
TYPES OF JAVA PROGRAM
1) Standalone applications
2) Applet programs
1)standalone applications:
it is a independent programs that run on a local computer
this application do not need a browser or internet connection to
function.
They are complied using [Link] and executed using [Link]
interpreter
Example: A calculator
2)applet program:
Applet programs are small java applications that run within a web
browser.
They are embedded in html
commonly used in games games, animations ,and online forms .
They are complied using [Link] and executed java enabled web
browser .
Example :a stock market ticker applet that updates stock prices
dynamically on webpages.
Structure of a java program:
Documentation section:
This section consists of comments that describe the name of the program,
the author name, the date it was created, and its purpose .comments do
not a ect the execution of the programs but severs as a useful
documentation.
Package statements :
Declaring a package in java means specifying a namespace for a group a
related classes. This helps in organizing the code systematically, avoiding
name conflicts , and improving reusability.
4
LEARN JAVA WITH JOY
Example: package animal ;
Class dog
{
…………………
}
Import statement:
The import statements in java similar to the #include statements in c . if a
programmer wants to us a method from a specific class, that class must be
import into the program.
Example :
import java .util .date;
now all methods of the date class can be used in the program
class and interfaces definitions :
after import statements , the next step is defining classes or interfaces .a
java program can contain multiple classes and each classes may have
one or more instance variables and methods .
an interface is similar to the class but contains only unimplemented
methods (abstract method) and public static final fields . calss are provide
the structure for objects while interfaces establish a contract that classes
must follow .
5
LEARN JAVA WITH JOY
java tokens :
6
LEARN JAVA WITH JOY
1)key words : the key words are reserved words in java that have
predefined meanings and connot be used as identifiers . they appers
in lower case.
The keywords const and goto reserved but not used in java . they exist
prevent errors from c/c++ programmers mistakenly using them.
The keywords true , false , and , and null might look like keywords ,
but they are actually literals ; we connot use them as identifiers in
the program.
Example : public , class , void static ,,,,
Literals (constants)
A literals is a constant value that appears in the java program . it
represents fixed numerical (integer or floating point ),character,
Boolean ,or string values.
Example :
Integer literals : 33 0 -99
Separators:
Is also called as panctuators . The java program utilise the separator
to divide the code into meaningful segments.
Example : java provides six di erent types of curly braces
( ): the parentheses can be used to contain a parameter list for
methods being called or declared .example :
Public void calc()
{
Int a=3*(2+1);
Return a;
}
[ ]: brackets represents the index of an [Link] used parentheses
for arrays so that they are not confused with [Link] [] myArray
=new int[10];
{}:curly braces begin and end a block of code statements.
Example : public void display()
{
System. Out .println(“Hello World”);
}
7
LEARN JAVA WITH JOY
; : semicolons are delimiters that mark end of the statements.
Example:
System . out . println(“Hello World”);
Int a ,b ,c;
, : commas are used to separate the parts of a list
. : periods are used as decimal points and as delimiters to link or
conctatenated method calls and separate them from class names.
Example : double d=3.14;
Comments : a
Comments : is a non executable part of a program used for documentation
since comments are do not contain executable instructions, they are
ignored by the complier . their primary purpose is to improve the code
readability and help programmers understand the program more easily.
Example : java supports three types of comments :
Single line comments : double slashes (\\) are used to tell the complier to
everything from the slashes to the end of the line as comment.
\\ single line comments: a very simple example
public class exampleprogram{
public static void main(string myargs[]){
system .out .println(“single line comments”);
}
}
Multiline comments :
Here we can use c style comments (/* */)to enclose one or more lines of
code to be treated as comments.
Example : this is simple program to print a message */
public class exampleprogram {
public static void main(string myargs[]){
8
LEARN JAVA WITH JOY
system .out . println(“I am a simple program”);
}
}
Javadoc comments : to generate documentation for our programs we
should use the doc comments (/* /) . the javadoc is a tool locates the doc
comments embedded in source files and uses those comments to
generate API documentation.
Example :
/
*this class displays a text string at the console */
Public class exampleprogram{
Public static void main(string myargs[]){
System .out. println(“I am a simple program “);
}
}
Identifier:
An identifier is a user-defined name given to various elements in a
program, such as variables, functions, classes, and arrays, to uniquely
identify them during execution
Allowed Characters: Must consist of a combination of letters (A-Z, a-
z), digits (0-9), and the underscore character (_).
First Character: Must start with either a letter or an underscore.
It cannot start with a digit.
No Special Symbols: Characters such as @ , $ , # , % , or hyphens ( - ) are
generally not allowed (exceptions exist, such as $ being valid in Java).
No Whitespace: Blank spaces or commas are strictly prohibited within an
identifier name.
9
LEARN JAVA WITH JOY
Case Sensitivity: Identifiers are usually case-sensitive,
meaning Total , total , and TOTAL are treated as three distinct names.
Reserved Keywords: Predefined keywords (like int, if, while, or return)
cannot be used as identifiers because they have a fixed meaning for the compiler or interpretor
Operators are the special symbols used in expressions to manipulate the
values and veriables .
Arithmetic operators + Addictive operator (used to for string connection)
_ Subtraction operator
* Multiplication operator
/ Division operator
% Reminder operator
Unary operator + Unary plus operator
_ Unary minus operator
++ Unary increment
__ Unary decrement
(post and pre )
Relational operator == Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Logical operator && And
|| Or
! Not
Assignment operator =
Conditional operator ?: Ternary operator (short hand if then else
statement
Short hand assignment +=, -=,*=,/=,&=,|=,^=.
operators
Type comparison The instance of operator compares an
operator (instance of object to a specified type
operator)
10
LEARN JAVA WITH JOY
Bitwise operator ~ Unary bitwise compliment
<< Signed left shift
>> Signed right shift
<<< Unsigned right shift & bitwise AND
^ Bitwise exclusive OR
! Bitwise inclusive OR
11
LEARN JAVA WITH JOY
>= checks if the value of left operand is greater than or equal to the right
operand if yes then condition becomes true .
12
LEARN JAVA WITH JOY
If(a>=b) is not true
<= checks if the values of left hand operand is less than or equal to the right
hand operator if yes then condition becomes true
If(a<=b) Is true
Logical operator
13
LEARN JAVA WITH JOY
MISCELANEOUS OPERATORS
There are few other operators supported by Java Language:
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator
consists of three operands and is
used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to
the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
instance Of Operator
This is only for documentation purposes.
This operator is used only for object reference variables. The operator
checks whether the object is of a
particular type(class type or interface type). The instance Of operator is
written as:
( Object reference variable ) instance Of (class/interface type)
If the object referred by the variable on the left side of the operator passes
the IS-A check for the
class/interface type on the right side, then the result will be true.
EXAMPLE
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
14
LEARN JAVA WITH JOY
Vehicle a = new Car();
boolean result = a instance of Car;
System .out .println( result);
}
}
This would produce the following result:
true
Data types :
It is a fundamental building block of data handling .it determines the
amount of memory requires to store that value a variable can hold .
Integers types: it holds byte, short ,int ,and long .
Floating point type :it include float and double .
Character type: it includes a char .
Boolean type :which includes Boolean represents true or false values.
Variables : it is container that holds values .it allows the program to
reference and manipulate the data as needed.
Declaring the variable <datatype><variable name>;
Example: public class variables
{
Public static void main(string[] args)
{
Int accountno ,balance ;
}}
Initializing variables: assigning the value to the variable at the time of
declaration is called initialization (it is done by using = assignment operator
15
LEARN JAVA WITH JOY
<datatype><variable name>=value;
Int count=10;
16
LEARN JAVA WITH JOY
Control structure
The order in which statement are executed in a program is called
flow of control
1)selection statement
2)looping constructs (iteration)
3)Jump statement
1} selection statement( decision making)
2 types: 1)if statement
2)switch statement
Simple if statement: one way branching statement
When the condition of if is true then only it executes the true
statements if it is false the block is skipped derictly
Syntax: if(test expression)
17
LEARN JAVA WITH JOY
Syntax: if(test expression)
{
Statement 1;
Statement n;
}
Example: if (x<y)
Sytem .out .println(“x is smaller then y”);
If else statement : i an if-else statement is a "decision-making"
tool that allows a program to execute di erent blocks of code
based on whether a condition is true or false.
Flow chart:
if (condition) {
// block of code to be executed if the condition is true
} else {
18
LEARN JAVA WITH JOY
// block of code to be executed if the condition is false
}
Example:
if (number >= 0) {
System. Out .println("The number is positive.");
} else {
System .out .println("The number is negative.");
Nested if statement: of a nested if statement is an if statement
that is placed inside the body of another if or else statement ,
This structure creates a hierarchical "decision within a decision,"
allowing you to check for a second (inner) condition only if the
first (outer) condition is true.
if (outer Condition) {
// This runs if outerCondition is true
if (innerCondition) {
// This runs ONLY if BOTH outer and inner are true
} else {
// This runs if outer is true BUT inner is false
}
} else {
19
LEARN JAVA WITH JOY
// This runs if outerCondition is false
}
Example : if (age >= 18) {
System .out .println("Age requirement met.");
// Nested if statement
if (annualIncome >= 30000) {
System .out .println("You are eligible for a loan.");
} else {
System .out .println("Income is too low for a loan.");
}
} else {
System .out .println("You must be at least 18 years old.");
20
LEARN JAVA WITH JOY
If else ladder (multi way branching):
An else if ladder is a control flow structure used to test multiple
conditions sequentially until one evaluates to true.
Syntax:
if (condition1) {
statement;
}
else if (condition2) {
// Runs if condition1 was false AND condition2 is true
}
else if (condition3) {
// Runs if all above were false AND condition3 is true
}
else {
// Runs only if EVERY condition above was false
}
Example:
if (temperature > 30) {
System .out .println("It's hot! Wear a T-shirt and shorts.");
}
else if (temperature > 20) {
// This runs only if temperature is NOT > 30, but IS > 20
System .out .println("It's warm. A light shirt is fine.");
21
LEARN JAVA WITH JOY
}
else if (temperature > 10) {
System .out .println("It's a bit chilly. Wear a jacket.");
}
else {
// This runs if none of the above are true (10 or below)
System. out. println("It's cold! Wear a heavy coat.");
}
22
LEARN JAVA WITH JOY
Switch:( Multi-way Branch Statement)( Selection Control
Structure)( Case Statement)( Switch-Case)
a control flow mechanism used to execute one block of code
among many based on the value of a single expression. It is a
cleaner and more organized alternative to a long chain of if-else
if statements.
Syntax :
switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any case
}
Example:
int day = 3;
String dayName;
switch (day) {
23
LEARN JAVA WITH JOY
case 1:
dayName = "Monday";
break; // Stops execution here
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default: // Catch-all for any value not matched above
dayName = "Invalid day";
break;
}
System .out .println(dayName); // Output: Wednesday
24
LEARN JAVA WITH JOY
Loop or iteration statement: a control flow structure that allows a
block of code to be executed repeatedly as long as a specific
condition is met.
While condition:
A while statement is a control flow structure that creates a loop.
It repeatedly executes a block of code as long as a specified
boolean condition remains true.
It is often called an entry-controlled loop because the condition
is checked before the code block runs. If the condition is false at
the very beginning, the code inside the loop will never execute
even once.
while (condition) {
// Code to be executed repeatedly
// (Must include a way to change the condition!)
}
int count = 1; // Initialization
while (count <= 5) { // Condition
System .out .println("Count is: " + count);
count++; // Update (Crucial to avoid an infinite loop!)
}
System .out .println("Loop finished!");
25
LEARN JAVA WITH JOY
For loop: In Java, a for loop is a control flow statement that allows you to
execute a block of code repeatedly for a fixed number of times. It is
an entry-controlled loop, meaning the condition is checked before any
code in the loop body is executed.
The standard for loop consists of three main parts separated by
semicolons inside the parentheses
Initialization
Condition:
Update
Example: public static void main(String[] args) {
// Initialization: i starts at 1
// Condition: loop while i is less than or equal to 5
// Update: increase i by 1 after each step
for (int i = 1; i <= 5; i++) {
[Link]("Number: " + i);
26
LEARN JAVA WITH JOY
Syntax: for (initialization; condition; update) {
// block of code to be executed
}
Break statement: break statement is a control flow tool used to
exit a loop or a switch-case block prematurely. When the program
encounters a break, it immediately terminates the current block
and transfers control to the next line of code outside that block.
It is also jump statement .
The break statement is primarily used in three scenarios:
In Loops (for, while, do-while):
In switch Statements:
In Labeled Blocks : for each loop;
Example: for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Stops the loop entirely when i is 5
}
[Link](i);
}
27
LEARN JAVA WITH JOY
// Output: 1, 2, 3, 4
Syntax: break;
The continue statement:
The continue statement is used to skip the current iteration of a
loop and jump immediately to the next one. Unlike break, it
does not stop the loop; it just tells Java, "Stop what you're doing in
this specific round and move to the next."
Syntax: continue;
Example: for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the rest of the code for i = 3
}
[Link](i);
Labelled loop: A label is a user-defined identifier followed by a
colon (:) placed before a loop statement. It allows
the break and continue statements to target an outer loop rather
than just the default innermost one.
labelName: // The label definition
for (initialization; condition; increment) {
// Nested loop
for (initialization; condition; increment) {
if (someCondition) {
break labelName; // Terminates the loop labeled
'labelName'
// OR
28
LEARN JAVA WITH JOY
continue labelName; // Skips to the next iteration of
'labelName'
}
public class LabeledLoopExample {
public static void main(String[] args) {
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
[Link]("Breaking the outer loop at i=2, j=2");
break outerLoop; // Exits BOTH loops entirely
}
[Link]("i = " + i + ", j = " + j);
}
[Link]("Execution continues here.");
29