0% found this document useful (0 votes)
7 views18 pages

Day1-6 Java

The document provides an introduction to Java, covering its features, basic programming concepts, and flow control structures. It explains Java's platform independence, variable declaration, data types, operators, and user input handling, along with conditional statements and loops. Additionally, it includes example programs to illustrate these concepts.

Uploaded by

yashjain2112
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)
7 views18 pages

Day1-6 Java

The document provides an introduction to Java, covering its features, basic programming concepts, and flow control structures. It explains Java's platform independence, variable declaration, data types, operators, and user input handling, along with conditional statements and loops. Additionally, it includes example programs to illustrate these concepts.

Uploaded by

yashjain2112
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
You are on page 1/ 18

Lecture 1 : Introduction

1. Introduction and features of Java


1.1. What is Java ?

Java is a high-level, general-purpose programming language originally developed by


Sun Microsystems (now owned by Oracle Corporation). It was first released in 1995
and has since become one of the most popular and widely used programming
languages in the world. Java is known for its platform independence, which means
that Java applications can run on various operating systems without modification.
This is achieved through the use of the Java Virtual Machine (JVM), which interprets
Java bytecode, allowing it to be executed on different platforms.

1.2. Features of C++


• Objectoriented: Supports objectoriented programming, allowing for efficient
organization of code through classes and objects.
• Platform Independence: Java applications are "write once, run anywhere"
due to the JVM. This allows developers to create software that can run on
different platforms without major modifications.
• Robust: Java includes features like strong type checking, exception handling,
and automatic memory management (garbage collection) to create robust and
reliable applications.
• Portability: Code can be compiled and executed across different platforms
with minimal modifications, ensuring widespread usability.
• Multithreading: Supports procedural, object oriented, and generic
programming, allowing flexibility in coding styles.
• Exception Handling: Offers robust mechanisms for handling errors and
exceptions, ensuring the reliability of programs.
• Dynamic: Boasts a large and active developer community, providing ample
resources and support for learning and problemsolving.
2. First Program “Hello Word”
2.1. The code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
2.2. Tokens

Tokens are essential elements of a program, representing the smallest meaningful


symbols to the compiler. Our code demonstrates all six types of tokens, excluding
typical operators.

Token type Description/Purpose Examples


Keywords Words with special int, double, for, auto
meaning to the compiler
Identifiers Names of things that are cout, std, x, myFunction
not built into the language
Literals Basic constant values "Hello, world!", 24.3, 0, ’c’
whose value is specified
directly in the source code
Operators Mathematical or logical +, , &&, %, <<
operations
Punctuation/Separators Punctuation defining the {}(),;
structure of a program
Whitespace Spaces of various sorts; Spaces, tabs, newlines,
ignored by the compiler comments

2.3. Escape sequence

Escape sequences are combinations of characters, starting with a backslash,


representing special meanings in strings or characters, like newline (\n) or tab
(\t).
Escape Sequence Represented Character
\a System bell (beep sound)
\b Backspace
\f Formfeed (page break)
\n Newline (line break)
\r “Carriage return” (returns cursor to start
of line)
\t Tab
\\ Backslash
\’ Single quote character
\" Double quote character
3. Basic of Java
3.1. Variables

In Java, a variable is a named storage for data. It has a specific type (like int or
double) and must be declared before use. Variables store different kinds of values,
allowing data manipulation in programs.

3.1.1. Variable Program


public class VariableDeclaration {
public static void main(String[] args) {
// Variable declarations
int myInteger; // Declaration of an integer variable

// Variable initialization
myInteger = 42; // Initialize the integer variable

// Display the values of the initialized variables


System.out.println("myInteger: " + myInteger);
}
}

3.2. Data Types

A data type is an attribute associated with a piece of data that tells a computer system
how to interpret its value.
3.2.1. Data Types Program

public class DataTypesExample {

public static void main(String[] args) {

// Primitive data types

int myInt = 42; // Integer

double myDouble = 3.14159; // Double-precision floating-point

char myChar = 'A'; // Character

boolean myBoolean = true; // Boolean

3.3. Operators
An operator is a symbol that operates on a value to perform specific mathematical or
logical computations.

3.3.1. Types of Operators


• Arithmetic: `+`, `-`, `*`, `/`, `%`
• Comparison: `==`, `!=`, `<`, `>`, `<=`, `>=`
• Logical: `&&`, `||`, `!`
• Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`
• Assignment: `=`, `+=`, `-=` etc.
• Increment/Decrement: `++`, `--`
3.3.2. Operators Program

public class OperatorsExample {

public static void main(String[] args) {

// Arithmetic operators

int num1 = 10;

int num2 = 5;

int sum = num1 + num2;

int difference = num1 - num2;

int product = num1 * num2;

int quotient = num1 / num2;

int remainder = num1 % num2;

// Comparison operators

boolean isEqual = num1 == num2;

boolean isNotEqual = num1 != num2;

boolean isGreaterThan = num1 > num2;

boolean isLessThan = num1 < num2;

boolean isGreaterOrEqual = num1 >= num2;


boolean isLessOrEqual = num1 <= num2;

// Logical operators

boolean condition1 = true;

boolean condition2 = false;

boolean logicalAnd = condition1 && condition2;

boolean logicalOr = condition1 || condition2;

boolean logicalNot = !condition1;

3.4. Input

In Java, you can take user input from the command line using the Scanner
class, which is part of the java.util package. Here's a basic example of how
to take user input in Java:

Input Program

import java.util.Scanner;

public class InputExample {

public static void main(String[] args) {

// Create a Scanner object to read user input

Scanner scanner = new Scanner(System.in);

// Prompt the user for input

System.out.print("Enter your name: ");

// Read a line of text input from the user

String name = scanner.nextLine();


// Display the user's input

System.out.println("Hello, " + name + "!");

// Close the Scanner to release resources (optional but good practice)

scanner.close();

}
Lecture 2 : Flow of Control

1. Conditional Statements
A conditional statement in programming refers to a construct that allows you to execute
different blocks of code based on the evaluation of a condition. Conditional statements enable
you to make decisions in your programs, making them dynamic and responsive to different
situations.

1.1. if Statement:
The if statement evaluates a condition. If the condition is true, the code inside the if
block is executed.

1.1.1. if Statement Syntax:


if (condition) {

// Code to be executed if the condition is true

1.2. if-else Statement:


The if-else statement evaluates a condition. If the condition is true, the code inside the
if block is executed. If the condition is false, the code inside the else block is
executed.

1.2.1. if-else Statement Syntax:


if (condition) {

// Code to be executed if the condition is true

} else {

// Code to be executed if the condition is false

}
1.3. else-if Statement:
The else-if statement allows you to evaluate multiple conditions in sequence. If the
previous conditions are false, it checks the next condition.

1.3.1. else-if Syntax:


if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition2 is true and condition1 is false

} else {

// Code to be executed if both condition1 and condition2 are false

1.4. Switch-Case
The switch statement in Java is another way to make decisions based on the value of a
variable or expression. It provides an alternative to the if-else if-else ladder for
handling multiple conditions. Here's the basic syntax of the switch statement:

1.4.1. Switch-Case Syntax


switch (expression) {

case value1:

// Code to be executed if expression equals value1

break;

case value2:

// Code to be executed if expression equals value2

break;

// ... more cases ...


default:

// Code to be executed if expression doesn't match any case

1.4.2. Switch-Case Program


import java.util.Scanner;

public class SwitchCaseExample {

public static void main(String[] args) {

// Create a Scanner object to read user input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number (1-5): ");

int number = scanner.nextInt();

// Use a switch statement to perform different actions based on the input

switch (number) {

case 1:

System.out.println("You entered 'One'.");

break;

case 2:

System.out.println("You entered 'Two'.");

break;

case 3:

System.out.println("You entered 'Three'.");

break;

case 4:
System.out.println("You entered 'Four'.");

break;

case 5:

System.out.println("You entered 'Five'.");

break;

default:

System.out.println("Invalid input. Please enter a number between 1 and


5.");

1.5. If-elseIf-else Program


import java.util.Scanner;

public class SwitchCaseExample {

public static void main(String[] args) {

// Create a Scanner object to read user input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number (1-5): ");

int number = scanner.nextInt();

// Use a switch statement to perform different actions based on the input

switch (number) {

case 1:

System.out.println("You entered 'One'.");


break;

case 2:

System.out.println("You entered 'Two'.");

break;

case 3:

System.out.println("You entered 'Three'.");

break;

case 4:

System.out.println("You entered 'Four'.");

break;

case 5:

System.out.println("You entered 'Five'.");

break;

default:

System.out.println("Invalid input. Please enter a number between 1 and


5.");

}}

1.6. Break and Continue


The break statement is used inside a loop to immediately exit the loop's body and
terminate the loop. When a break statement is encountered, the program control exits
the loop, and the code following the loop is executed.

The continue statement is used inside a loop to skip the rest of the loop's body for the
current iteration and move to the next iteration of the loop. When a continue
statement is encountered, the program control jumps to the loop's
increment/decrement expression (in for loops) or the loop condition check (in while
and do-while loops).

1.6.1. Break and Continue Program


import java.util.Scanner;

public class BreakAndContinueExample {

public static void main(String[] args) {

// Create a Scanner object to read user input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a positive number: ");

int number = scanner.nextInt();

// Use a loop to find and display the first even number in a range

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

if (i % 2 == 0) {

System.out.println("The first even number in the range is: " + i);

break; // Exit the loop when the first even number is found

// Use a loop to skip and not display multiples of 3 in a range

System.out.println("Multiples of 3 in the range:");

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

if (i % 3 == 0) {

continue; // Skip this iteration and move to the next number


}

System.out.println(i);

}}}

2. Loops
In Java, loops are used to execute a block of code repeatedly as long as a specified condition
is met. There are several types of loops in Java: for, while, and do-while loops. Here's an
overview of each:

2.1. For Loop


The for loop is used when you know beforehand how many times you want to
execute the loop.

2.1.1. For Loop Syntax


for (initialization; condition; update) {

// Code to be executed

2.1.2. For loop Program


public class ForLoopExample {
public static void main(String[] args) {
// Use a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}}

2.2. While Loop


The while loop is used when you want to execute a block of code as long as a
condition is true.

2.2.1. While Loop syntax


while (condition) {

// Code to be executed

2.2.2. While Loop Program


public class WhileLoopExample {

public static void main(String[] args) {

// Initialize a variable for the loop control

int i = 1;

// Use a while loop to print numbers from 1 to 10

while (i <= 10) {

System.out.println(i);

i++; // Increment the loop control variable

}}

2.3. Do-While Loop


The do-while loop is similar to the while loop, but it guarantees that the code inside
the loop is executed at least once before checking the condition.

2.3.1. Do-while Loop Syntax


do {

// Code to be executed

} while (condition);

2.3.2. Do-While Loop Program


public class DoWhileLoopExample {

public static void main(String[] args) {


int i = 1;

// Use a do-while loop to print numbers from 1 to 10

do {

System.out.println(i);

i++;

} while (i <= 10);

You might also like