[Go to site: main page, start]

0% found this document useful (0 votes)
4 views32 pages

Java

Java is a programming language developed by Sun Microsystems, created by James Gosling in 1991. It is known for its platform independence, strong object-orientation, and extensive ecosystem, making it suitable for various applications like enterprise backends and Android development. The document also covers Java's basic syntax, control flow, data types, and practical examples of programming problems.
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)
4 views32 pages

Java

Java is a programming language developed by Sun Microsystems, created by James Gosling in 1991. It is known for its platform independence, strong object-orientation, and extensive ecosystem, making it suitable for various applications like enterprise backends and Android development. The document also covers Java's basic syntax, control flow, data types, and practical examples of programming problems.
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 HISTORY

Java is a totally computer based programming language developed by SUN MICROSYSTEM


Creator - James Gosling
In the year of 1991 James Gosling & his friend Start a project (TEAM NAME- GREEN TEAM )

James Gosling --- greentalk (first name of java)


Extension --- .gt
Changed - greentalk oak (new name )
OAK

OAK technology (this name has been


National tree
registered already by an Company
(USA, France etc…

OAK JAVA (1995)


WHAT IS JAVA?

Imagine you want to give instructions to a computer. Computers only understand binary (0s and 1s), but writing in
binary is impossible for humans. So we use programming languages like Java. Java acts as a bridge between human
thinking and machine execution

Why Java?
Platform independence – “Write Once, Run Anywhere”.
Strong object-orientation.
Large ecosystem and community.
Used in enterprise backends, Android development, and big data.
JDK, JRE A N D JVM

JDK – Jdk stands for java development kit, it internally contains JRE & JVM Where JRE stands for Java Runtime
Environment AND JVM stands for Java virtual machine. JDK provides all the tools to work with java language .

JRE - JRE Stands for Java runtime environment , its provide an environment to execute the java program. It its
internally contains JVM which is responsible to execute a Java program.

JVM – JVM stands for Java virtual machine, it is the software in the form of interpreter Written in ‘C’ language
through which we can execute our java programs.
F I R S T JAVA P R O G R A M

public class HelloWorld {


public static void main(String[] args)
public static void main(String[] args) {
[Link]("Hello, World!"); This is the starting point of the program
public
} JVM must access it
If not public → program won’t run
}
The main method must be public so the JVM can call
public class HelloWorld – it.“
class → Every Java program is written inside a class
HelloWord → Name of the class (must match file name) static – allows the JVM to call it without creating an
object of the class.
Why public? void – it doesn’t return any value.
public means accessible from anywhere
JVM needs to access this class to run the program. String[] args – a parameter that can receive
command-line arguments (as an array of strings).
In Java, everything is inside a class, and public allows the
JVM to access it.
• [Link]() - Used to print output on the screen

System - System is a predefined class in Java.“

Out - out is used to send output to the screen."

• Println - Print + move to next line The main Method – Entry Point
Difference: • Purpose: The starting point of any Java application. When you run
the program, the Java Virtual Machine (JVM) calls the main method
• print() → stays on same line first.

• println() → moves to next line


• "println prints the text and moves to the next line."

Compile: javac [Link]


Run: java HelloWorld

Basic Syntax

Definition:
• Variables are containers for storing data values. In Java, every variable has a data type that defines the type of
data it can hold.

• Syntax:
• dataType variableName = value;
Int a = 20; a= 20 , b=30
a and b are the variable which holds the value of 20 and 30

Ex- 2*(a+b)
In Java, a literal is a fixed, constant value that is directly written in the code and assigned to a variable.

2 is a literals . a and b is a variable (change the value )


IDENTIFIRES
A name in java program are consider as Identifier can be a Class name, method name or Variable name

Rules for defining Java Identifires

Allowed Characters
Can contain:
Letters (A–Z, a–z)
Digits (0–9)
Underscore (_)
Dollar sign ($)
Cannot contain spaces or special characters like @, #, %, etc.
If we use any other character then compile time error

Ex- 1. total_number
2. total#
3. 123total
4. Int
RESERVED WORDS

• In Java, reserved words are predefined identifiers that have a special meaning in the language syntax.
They cannot be used as variable names, method names, class names, or any other identifiers.

In java 53 Reserved words

Used Keywords - if ,else , switch… etc.


In java unused Keywords
1. Goto
2. Const

C• onst – is basically defined for constant value but in java FINAL Keywords is already there so, we can’t use
const .

Goto - Created Several problems in more languages .

NOTE - All 53 reserved words contains only lower case alphabets Symbols .

KEYWORDS FOR DATATYPE - 8 keywords for data types (byte, short, int, long, float, double, Boolean and
char.)

KEYWORDS FOR FLOW CONTROL – 11 keywords for flow control (if, else, switch, case, default, while, do,
for, break, continue and return).

KEYWORDS FOR MODIFIERS – keywords for modifiers


( public , private , protected, static, final, abstract, synchronized, native, strictfp, volatile. )

KEYWORDS FOR EXCEPTION HANDLING - 6 keywords for exception handling


(try, catch, finally, throw, throws, assert).

CLASS RELATED KEYWORDS – Class, Interface, extends , Implements, Package, import.

RETURN TYPE KEYWORDS - VOID

NOTE - In java return type is mandatory . If a method wasn’t return anything then we have to declare
the method with void return type .

But in c language return type is optional . And the default return type is int .
DATA TYPES

In Java, data types define the kind of data a variable can hold and how much memory it will use.
They are broadly classified into Primitive and Non-Primitive types.

1. Primitive Data Types - These are the most basic data types built into Java. They store simple values directly in
memory.
Operators
Definition:
Operators are symbols that perform operations on variables and values. Java supports various operators like
arithmetic, relational, logical, and assignment operators.
Relational Operators:
Syntax:
boolean isEqual = a == b;
Arithmetic Operators: boolean isNotEqual = a != b;
boolean isGreater = a > b;
int sum = a + b; boolean isLess = a < b;
int difference = a - b; boolean isGreaterOrEqual = a >= b;
int product = a * b; boolean isLessOrEqual = a <= b;
int quotient = a / b;
Assignment Operators:
int remainder = a % b;
int a = 5;
Logical Operators: a += 3; // equivalent to a = a + 3;
a -= 2; // equivalent to a = a - 2;
boolean and = (a > b) && (a < c);
a *= 4; // equivalent to a = a * 4;
boolean or = (a > b) || (a < c);
a /= 2; // equivalent to a = a / 2;
boolean not = !(a > b);
a %= 3; // equivalent to a = a % 3;
SCANNER IN JAVA

In Java, the Scanner class is a utility class in the [Link] package that is used to read input from various
sources such as:
• Keyboard ([Link])
• Files
• Strings
• nextLine(), nextInt(), and nextDouble() for reading different types of input.

nextLine() – Reads an entire line including spaces.


• next() – Reads a single word (stops at whitespace).
• nextInt(), nextDouble(), nextFloat(), nextLong() – Read numeric values.
• nextBoolean() – Reads a boolean value.
Practical Examples and Problems on
Java Basics
Problem 1: Sum of Two Numbers Problem 2: Even or Odd

import [Link];
import [Link];

public class EvenOdd {


public class sum_of_two_number {
public static void main(String[] args) {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Scanner sc = new Scanner([Link]); [Link]("Enter an integer: "); int
[Link]("Enter first number: "); num = [Link]();
int a = [Link](); if (num % 2 == 0) {
[Link]("Enter second number: "); [Link](num + " is even.");
int b = [Link](); } else {
int sum = a + b; [Link](num + " is odd.");
[Link]("Sum = " + sum); }
[Link](); [Link]();
} }
} }
Check Voting Eligibility
Largest of Two Numbers
import [Link];
import [Link];
public class VotingEligibility {
public static void main(String[] args) {
public class LargestOfTwo {
Scanner sc = new Scanner([Link]);
public static void main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter your age: ");
[Link]("Enter first number: "); int age = [Link]();
int a = [Link](); if (age >= 18) {
[Link]("Enter second number: "); [Link]("You are eligible to vote.");
int b = [Link](); } else {
int max = (a > b) ? a : b; [Link]("You are not eligible to vote.");
[Link]("Largest = " + max); }
[Link](); [Link]();
} }
} }
Control Flow

Control flow determines the order in which statements are executed.


Three types of control flow:

Sequential – default, statements executed line by line.


Selection – choose between different paths (if, switch).
Iteration – repeat a block of code (for, while, do-while).

Without control flow, programs would be linear and unable to make decisions or
repeat tasks.

if Statement

int age = 20;


if (age >= 18) {
[Link]("You are eligible to vote.");
}
if-else Statement
Definition: The if-else statement is used to
execute different blocks of code based on
whether a specific condition is true or false.

int marks = 65;


if (marks >= 40) {
[Link]("Pas
s");
} else {
[Link]("Fail");
}
else-if Ladder (Multiple Conditions)

if (condition1) { int score = 85;


// block 1 if (score >= 90) {
[Link]("Grade A");
} else if (condition2) {
} else if (score >= 80) {
// block 2 [Link]("Grade B");
} else if (condition3) {
} else if (score >= 70) {
[Link]("Grade C");
// block 3
} else if (score >= 60) {
} else { [Link]("Grade D");
// default block } else {
} [Link]("Grade F");
}
• Problem : Largest of Three Numbers

• import [Link];
int largest;
• public class LargestOfThree { if (a >= b && a >= c) {
largest = a;
• public static void main(String[] args) {
} else if (b >= a && b >= c) {
• Scanner sc = new Scanner([Link]); largest = b;
} else {
• [Link]("Enter three numbers: ");
largest = c;
• int a = [Link](); }
• int b = [Link]();
[Link]("The largest number is " + largest + ".");
• int c = [Link](); [Link]();
• }
}
Why Loops?

Loops allow us to execute a block of code multiple times without writing it again.
They are essential for:

Processing arrays and collections


Repeating tasks until a condition changes.

Common loop types in Java:

for – when number of iterations is known


while – when condition is checked before the loop
do-while – when the body must execute at least once
for Loop

Definition: The for loop is used for iterating over a


range of values or elements, executing a block of
code multiple times.

The for Loop – Syntax & Flow

for (initialization; condition; update) {


// body
}
Example – print numbers 1 to 5:

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


[Link](i);
}

Using a variable for condition (e.g., array length):

int[] arr = {10, 20, 30};


for (int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
while Loop

Definition: The while loop repeatedly


executes a block of code as long as a
specified condition remains true.

print numbers 1 to 5:

int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
DO-WHILE LOOP

Definition: The do-while loop is similar to the


while loop but guarantees that the code block
is executed at least once before the condition is
checked.

Syntax:
do {
// body
} while (condition);

Body is executed at least once, then condition


is checked.
switch Case

Definition: The switch statement allows a


variable to be tested against multiple values
(cases) and executes the block of code
corresponding to the matching value.
Break and Continue Keywords

Break: The break statement is used to exit


a loop or a switch statement immediately.

Continue: The continue statement skips the


current iteration of a loop and continues
with the next iteration.
Syntax: Example – days of week:

switch (expression) { int day = 3;


case value1: switch (day) {
// code case 1:
break; [Link]("Monday");
case value2: break;
// code case 2:
break; [Link]("Tuesday");
default: break;
// code (optional) case 3:
} [Link]("Wednesday");
break;
expression can default:
be byte, short, int, char, String, [Link]("Other day");
}
Practical Examples
and Problems on
Conditional Loops
Problem:
Write a program that takes an integer n from the user and prints the sum of all natural
numbers from 1 to n using a for loop.

Write a program that prints all numbers from 1 to 10, each on a new line, using
a for loop.

Problem:
Take an integer input (1–7) representing the day of the week (1 = Monday, 2 = Tuesday,
…, 7 = Sunday). Use a switch statement to print the full name of the day. If the number
is outside 1–7, print "Invalid day".

Problem:
Write a program that prints numbers from 1 to 10, but skips the number 5 using
the continue statement.
Hint:
Use a for loop. Inside the loop, if the number is 5, use continue; to jump to the next
iteration without printing.

You might also like