Java Programming Basics: Lecture - 2
Prepared by Amey Pugaonkar: ameypugaonkar7@gmail.com
1. Java Program Structure
Java programs are made up of classes and methods. They follow a very specific structure:
• Statements: Instructions written inside methods.
• Semicolons (;): Used to terminate statements.
• Indentation: Proper indentation is important for readability, though Java does not
enforce it.
• Comments: Used to describe the code and ignored by the compiler.
Example:
public class HelloWorld { // Class declaration
public static void main(String[] args) { // Method declaration
// This is a single-line comment
System.out.println("Hello, World!"); // Statement ending with a semicolon
Assignment Problems:
• Write a program that prints your name.
• Write a program to print a short bio-data.
• Write a program to add two numbers and display the result.
2. Java Program (Basic Template)
A Java program typically consists of:
• Package definition
• Import statement
• Class definition
• main method (starting point)
• Statements inside the main method
Example:
package java_basics;
import java.util.Scanner;
public class FirstProgram {
public static void main(String[] args) {
System.out.println("Learning Java!");
Assignment Problems:
• Write a Java program to print "Welcome to Java Programming!".
• Write a Java program to print three paragraphs.
3. How Java Programs Run - Compilation and Execution
Steps:
1. Write Java code in .java file.
2. Compile it using javac filename.java.
3. Compiler generates a .class file (Bytecode).
4. Run it using java classname.
Important Terms:
• javac: Java compiler
• .class file: Contains bytecode
• java: Java interpreter to run the bytecode
Example:
javac HelloWorld.java
java HelloWorld
Assignment Problems:
• Write and compile a Java program that prints "Java Compilation Successful".
• Compile and run a Java program that prints the reminder of two numbers.
4. Bytecode
• Bytecode is a set of instructions generated after Java code compilation.
• It is platform independent.
• It is executed by the Java Virtual Machine (JVM).
Example: After compiling HelloWorld.java, HelloWorld.class is created, containing bytecode.
5. Platform Independence
• Java programs are "write once, run anywhere".
• The bytecode can run on any system having a JVM.
Why?
• Because JVM converts bytecode to machine code according to the operating system.
Example: If you compile code on Windows, you can run the same .class file on Linux without
any changes.
6. Variables
• Variables are used to store data.
• Each variable must have a type.
Syntax:
<datatype> <variable_name> = <value>;
Example:
int age = 20;
float salary = 50000.75f;
String name = "Amey";
Assignment Problems:
• Create variables to store your name, age, and height.
• Create a program to swap two numbers using a temporary variable.
7. Binary to Decimal and Decimal to Binary Conversion
Binary to Decimal
Binary Number: Only uses 0 and 1.
Conversion: Multiply each bit with 2 raised to the position number (starting from right = 0).
Example: Binary: 1011
Decimal = 1*(2^3) + 0*(2^2) + 1*(2^1) + 1*(2^0) Decimal = 8 + 0 + 2 + 1 = 11
Decimal to Binary
Steps:
1. Divide the number by 2.
2. Note down the remainder.
3. Repeat division until the quotient is 0.
4. Read remainders from bottom to top.
Example: Decimal: 13
13/2 = 6 remainder 1
6/2 = 3 remainder 0
3/2 = 1 remainder 1
1/2 = 0 remainder 1
Binary = 1101
Assignment Problems:
• Manually convert: 1101 to decimal, and 45 to binary.
8. Input/Output (I/O)
Input: Accept data from user. Output: Display data to user.
Using Scanner for Input:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
Assignment Problems:
• Input marks for 5 subjects and calculate the total marks and average.
• Input radius of a circle and calculate its area and circumference.
9. Operator
9.1 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
• Addition (+)
o Adds two numbers.
o Example: int sum = 5 + 3; // sum = 8
• Subtraction (-)
o Subtracts the right operand from the left.
o Example: int diff = 5 - 3; // diff = 2
• Multiplication (*)
o Multiplies two numbers.
o Example: int product = 5 * 3; // product = 15
• Division (/)
o Divides the left operand by the right.
o If both operands are integers, the result is an integer (the decimal part is
truncated).
o Example: int quotient = 5 / 2; // quotient = 2
o Note: To get a precise result with decimals, at least one operand must be a
floating-point number
double result = 5.0 / 2; // result = 2.5
• Modulus (%)
o Returns the remainder when one number is divided by another.
o Example: int remainder = 5 % 2; // remainder = 1
Example Program:
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
9.2 Relational Operators
Relational operators are used to compare two values or expressions. They return a boolean
result (true or false).
• Equal to (==)
o Returns true if both operands are equal.
o Example: 5 == 5 returns true.
• Not equal to (!=)
o Returns true if both operands are not equal.
o Example: 5 != 3 returns true.
• Greater than (>)
o Returns true if the left operand is greater than the right operand.
o Example: 5 > 3 returns true.
• Less than (<)
o Returns true if the left operand is less than the right operand.
o Example: 5 < 3 returns false.
• Greater than or equal to (>=)
o Returns true if the left operand is greater than or equal to the right operand.
o Example: 5 >= 5 returns true.
• Less than or equal to (<=)
o Returns true if the left operand is less than or equal to the right operand.
o Example: 5 <= 3 returns false.
Example Program:
public class RelationalOperators {
public static void main(String[] args) {
int a = 5, b = 3;
System.out.println("a == b: " + (a == b)); // false
System.out.println("a != b: " + (a != b)); // true
System.out.println("a > b: " + (a > b)); // true
System.out.println("a < b: " + (a < b)); // false
System.out.println("a >= b: " + (a >= b)); // true
System.out.println("a <= b: " + (a <= b)); // false
}
}
9.3 Logical Operators
Logical operators are used to combine multiple conditions or expressions.
• AND (&&)
o Returns true if both conditions are true.
o Example: (5 > 3 && 8 > 4) returns true.
• OR (||)
o Returns true if at least one condition is true.
o Example: (5 > 3 || 2 > 8) returns true.
• NOT (!)
o Reverses the result of the condition. If the condition is true, it returns false, and
vice versa.
o Example: !(5 > 3) returns false.
Example Program:
public class LogicalOperators {
public static void main(String[] args) {
int a = 5, b = 3, c = 8;
System.out.println("a > b && c > b: " + (a > b && c > b)); // true
System.out.println("a > b || c < b: " + (a > b || c < b)); // true
System.out.println("!(a < b): " + !(a < b)); // true
}
}
9.4 Assignment Operators
Assignment operators are used to assign values to variables.
• Assignment (=)
o Assigns the value on the right to the variable on the left.
o Example: int a = 5;
• Add and assign (+=)
o Adds the right operand to the left operand and assigns the result to the left
operand.
o Example: a += 3; is equivalent to a = a + 3;.
• Subtract and assign (-=)
o Subtracts the right operand from the left operand and assigns the result to the
left operand.
o Example: a -= 2; is equivalent to a = a - 2;.
• Multiply and assign (*=)
o Multiplies the left operand by the right operand and assigns the result to the left
operand.
o Example: a *= 2; is equivalent to a = a * 2;.
• Divide and assign (/=)
o Divides the left operand by the right operand and assigns the result to the left
operand.
o Example: a /= 2; is equivalent to a = a / 2;.
• Modulus and assign (%=)
o Takes the modulus of the left operand by the right operand and assigns the
result to the left operand.
o Example: a %= 3; is equivalent to a = a % 3;.
Example Program:
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
a += 5; // a = a + 5
System.out.println("a += 5: " + a); // 15
a -= 3; // a = a - 3
System.out.println("a -= 3: " + a); // 12
a *= 2; // a = a * 2
System.out.println("a *= 2: " + a); // 24
a /= 4; // a = a / 4
System.out.println("a /= 4: " + a); // 6
a %= 4; // a = a % 4
System.out.println("a %= 4: " + a); // 2
}
}
9.5 Unary Operators
Unary operators are used to operate on a single operand.
• Increment (++)
o Increases the value of the operand by 1.
o Example: a++ or ++a.
• Decrement (--)
o Decreases the value of the operand by 1.
o Example: a-- or --a.
• Negation (-)
o Negates the value (changes the sign).
o Example: -a.
• Logical NOT (!)
o Reverses the logical state of a boolean.
o Example: !true returns false.
Example Program:
public class UnaryOperators {
public static void main(String[] args) {
int a = 5;
System.out.println("a++: " + a++); // 5 (post-increment)
System.out.println("++a: " + ++a); // 7 (pre-increment)
a--;
System.out.println("a--: " + a); // 6 (post-decrement)
System.out.println("--a: " + --a); // 5 (pre-decrement)
boolean isTrue = true;
System.out.println("!isTrue: " + !isTrue); // false
}
}
Assignment Problems :
1. Arithmetic Problem: Write a program to calculate the area of a rectangle and perimeter using
arithmetic operators.
2. Relational Problem: Write a program that checks if a given year is a leap year or not using relational
operators.
3. Logical Problem: Write a program that checks whether a given number is positive, negative, or zero
using logical operators.
4. Assignment Problem: Write a program that demonstrates the use of the assignment operators by
performing cumulative operations on a number.
5. Unary Problem: Write a program that increments a number twice and decrements it once. Show the
results before and after the increments and decrements.
10. Control Flow - If-Else
Control flow is used to make decisions in Java programs.
Syntax:
if (condition) {
// code if true
} else {
// code if false
Example:
int number = 20;
if (number > 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
Assignment Problems:
• Write a Java program to check if a number is even or odd.
• Write a Java program to check whether a person is eligible to vote (age >= 18).
• Write a Java program to find the largest of two numbers.
Prepared by Amey Pugaonkar : ameypugaonkar7@gmail.com