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

CUCS1004_Module1_Introduction_to_Java

Module 1 of the Java Programming course covers the fundamentals of Java, including its history, features, and setup of the development environment. It introduces key concepts such as tokens, variables, data types, operators, control statements, and arrays, along with practical coding examples. The module consists of 15 hours of instruction and includes 8 experiments and practice problems.

Uploaded by

Lakshmana Rowthu
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 views48 pages

CUCS1004_Module1_Introduction_to_Java

Module 1 of the Java Programming course covers the fundamentals of Java, including its history, features, and setup of the development environment. It introduces key concepts such as tokens, variables, data types, operators, control statements, and arrays, along with practical coding examples. The module consists of 15 hours of instruction and includes 8 experiments and practice problems.

Uploaded by

Lakshmana Rowthu
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

Introduction to Java Programming

Module 1: Tokens, Variables, Data Types, Operators, Control Statements & Arrays

CUCS1004 | Java Programming | Module 1 | 15 Hours


Module 1 Overview
• History and Features of Java
• Setting up JDK and IDE
• Basic Syntax: Tokens, Keywords, Identifiers
• Variables and Data Types (Primitive & Non-Primitive)
• Operators: Arithmetic, Relational, Logical, Bitwise, Assignment
• Control Statements: if-else, switch, loops (for, while, do-while)
• Jump Statements: break, continue, return
• Arrays: 1D, 2D, 3D and Multidimensional
• String Operations and Basic I/O

Note: Total Duration: 15 Hours | 8 Experiments + Practice Problems


01
Java Fundamentals
Duration: 2 Hours
What is Java?
• Java is a high-level, class-based, object-oriented programming language
• Developed by James Gosling at Sun Microsystems (1995)
• Designed to have as few implementation dependencies as possible
• Write Once, Run Anywhere (WORA) - Platform independent via JVM
• Robust, secure, and portable across different operating systems
• Widely used for web, mobile, enterprise, and cloud applications

Note: Java is both compiled and interpreted language


Key Features of Java
• Object-Oriented: Everything is an object (except primitives)
• Platform Independent: Bytecode runs on any JVM
• Simple & Familiar: Syntax similar to C/C++, no pointers/complex features
• Robust: Strong memory management, exception handling, type checking
• Secure: No explicit pointers, bytecode verifier, sandbox model
• Multithreaded: Built-in support for concurrent programming
• Distributed: Supports RMI, EJB, and web services
• Dynamic: Loads classes on demand, supports dynamic compilation
• High Performance: JIT compiler converts bytecode to native code
Setting Up Java Development Environment
Java Code

• JDK (Java Development Kit): Contains JRE + Development


// First Java Program - [Link]
Tools (javac, java, javadoc)
public class HelloWorld {
public static void main(String[] args) {
• JRE (Java Runtime Environment): JVM + Core Libraries
[Link]("Hello, World!");
for running Java programs }
}
• JVM (Java Virtual Machine): Executes bytecode, provides
platform independence // Compile: javac [Link]
// Run: java HelloWorld
• IDE Options: IntelliJ IDEA, Eclipse, NetBeans, VS Code
with Java extensions
• Environment Variables: JAVA_HOME and PATH
configuration
• Verify Installation: java -version and javac -version
commands

Note: File name must match class name ([Link])


02
Java Tokens & Syntax
Duration: 3 Hours
Java Tokens: Building Blocks of Programs
Java Code

• Tokens are the smallest individual units in a Java


class HelloToken {
program
public static void main(String[] args) {
[Link]("Hello!");
• The compiler breaks down source code into tokens
}
during lexical analysis }

• Five main categories of tokens in Java // Tokens identified:


// class, HelloToken, {, public, static,
• Tokens are separated by delimiters (whitespace, // void, main, (, String, args, [, ], ),
operators, special symbols) // System, ., out, ., println, "Hello!", ;, }

• Example: class HelloToken { public static void main(...) }


contains 15+ tokens

Note: Understanding tokens helps in debugging syntax errors


Keywords in Java
Java Code

• Reserved words with predefined meanings to the


// VALID keyword usage
compiler
int score; // int is a keyword
for(int i=0; i<5; i++) { }
• Cannot be used as identifiers (variable names, class
names, method names) // INVALID - keywords as identifiers
int float; // ERROR: float is keyword
• Case-sensitive and always written in lowercase String class; // ERROR: class is keyword
boolean true; // ERROR: true is literal
• Java has 50+ reserved keywords (abstract, assert,
boolean, break, byte...)
• Special literals: true, false, null (cannot be used as
identifiers)
• Unused reserved: const, goto (from C/C++ for
compatibility)

Note: Memorize common keywords: class, public, static, void, int, if, else, for, while, return
Identifiers: Naming Rules & Conventions
Java Code

• Names given to variables, classes, methods, interfaces,


// VALID identifiers
packages
score, level, highestScore
number1, convertToString
• Cannot be a keyword or reserved word
$price, _value, MAX_SIZE
• Must begin with a letter (A-Z, a-z), $, or _ (underscore)
// INVALID identifiers
class // keyword
• First character cannot be a digit (0-9)
1number // starts with digit
highest Score // contains space
• Can contain letters, digits, $, and _ after the first
@pple // contains @
character
• Case-sensitive: myVar and myvar are different identifiers
• No whitespace or special characters (@, #, %) allowed

Note: Convention: camelCase for variables/methods, PascalCase for classes, UPPER_CASE for constants
Literals (Constants) in Java
Java Code

• Fixed values that appear directly in the source code


// Integer literals
• Integer Literals: decimal (34), binary (0b10010), octal int dec = 34;
int bin = 0b10010;
(027), hex (0x2F)
int oct = 027;
int hex = 0x2F;
• Floating-point Literals: 3.4, 3.4f, 3.445e2 (scientific
notation) // Floating-point
double d = 3.4;
• Character Literals: 'a', '9', ' float f = 3.4f;
', ' ' (single quotes, Unicode) double sci = 3.445e2; // 344.5

• String Literals: "Hello World" (double quotes, sequence // Character & String
of characters) char c = 'A';
String s = "Java";
• Boolean Literals: true, false (only two possible values) boolean flag = true;

Note: Use 'L' suffix for long, 'f/F' for float literals
Special Symbols, Operators & Separators
Java Code

• Special Symbols (Punctuators): [] {} () , ; = *


// Special symbols usage
• Brackets []: Array declaration and element access int[] arr = new int[5]; // [] brackets
class Demo { } // {} braces
• Braces {}: Code blocks, class bodies, method bodies method(a, b); // () parenthesis, , comma
int x = 10; // = assignment, ; semicolon
• Parenthesis (): Method calls, parameter lists, expressions
// Operators
• Comma ,: Separates variables, parameters, array int sum = a + b; // arithmetic
boolean eq = (a == b); // relational
elements
boolean res = (a>0 && b>0); // logical
• Semicolon ;: Statement terminator (end of statement)
• Assignment =: Assigns value to variable
• Operators: Arithmetic (+,-,*,/,%), Relational (==,!=,>,<),
Logical (&&,||,!)

Note: Every statement in Java must end with a semicolon


Comments in Java
Java Code

• Single-line Comments: // comment text (ignored by


// This is a single-line comment
compiler)
/* This is a
• Multi-line Comments: /* comment text spanning
multi-line comment
multiple lines */ spanning several lines */

• JavaDoc Comments: /** documentation for API /**


generation */ * This is JavaDoc comment
* @param args command line arguments
• Comments improve code readability and maintainability * @author Student Name
*/
• JavaDoc comments are processed by javadoc tool to public class Demo {
generate HTML docs // code here
}
• Comments are completely ignored during compilation

Note: Good practice: Comment complex logic, not obvious code


03
Variables & Data Types
Duration: 3 Hours
Variables in Java
Java Code

• A variable is a named memory location used to store


// Declaration and initialization
data
int speedLimit = 80;
• Java is statically-typed: all variables must be declared
// Separate declaration and assignment
before use int speedLimit;
speedLimit = 80;
• Declaration: dataType variableName;
// Changing value
• Initialization: variableName = value; (or combined: speedLimit = 90; // valid
dataType var = value;)
// INVALID - cannot change type
• Variable values can be changed during program int speedLimit = 80;
execution float speedLimit; // ERROR: duplicate declaration

• Scope determines where a variable is accessible in the


program

Note: Variable scope: local, instance, static (class) variables


Primitive Data Types in Java
Type Size Range Default Value Example

byte 8-bit -128 to 127 0 byte b = 124;

short 16-bit -32,768 to 32,767 0 short s = -200;

int 32-bit -2^31 to 2^31-1 0 int i = 2147483647;

long 64-bit -2^63 to 2^63-1 0L long l =


9223372036854775807L;
float 32-bit ~7 decimal digits 0.0f float f = 3.14f;

double 64-bit ~15 decimal digits 0.0d double d = 3.14159;

char 16-bit '\u0000' to '\uffff' '\u0000' char c = 'A';

boolean 1-bit true or false false boolean flag = true;


Non-Primitive (Reference) Data Types
Java Code

• String: Sequence of characters, stored as objects


// String (non-primitive)
([Link])
String name = "Java Programming";
• Arrays: Collection of similar data types (int[], String[],
// Arrays
double[][]) int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[10];
• Classes: User-defined types with fields and methods
// Class object
• Interfaces: Abstract types that define method signatures Scanner input = new Scanner([Link]);

• All non-primitive types are created using the 'new' // Default values
keyword String str; // null
int[] arr; // null
• Default value is null (unlike primitives which have Object obj; // null
specific defaults)

Note: String is the most commonly used non-primitive type in Java


04
Operators in Java
Duration: 2 Hours
Arithmetic & Assignment Operators
Arithmetic Operators Assignment Operators
▸ + Addition: a + b ▸ = Simple assignment: a = b
▸ - Subtraction: a - b ▸ += Add and assign: a += b (a = a + b)
▸ * Multiplication: a * b ▸ -= Subtract and assign: a -= b
▸ / Division: a / b (integer division for ints) ▸ *= Multiply and assign: a *= b
▸ % Modulo (Remainder): a % b ▸ /= Divide and assign: a /= b
▸ %= Modulo and assign: a %= b
Relational & Logical Operators
Relational Operators (Return boolean) Logical Operators
▸ == Equal to: a == b ▸ && Logical AND: true if BOTH are true
▸ != Not equal to: a != b ▸ || Logical OR: true if EITHER is true
▸ > Greater than: a > b ▸ ! Logical NOT: inverts boolean value
▸ < Less than: a < b ▸
▸ >= Greater than or equal: a >= b ▸ Example: (a > 0) && (b > 0) → true only if both positive
▸ <= Less than or equal: a <= b ▸ Example: (a > 0) || (b > 0) → true if at least one positive
Unary & Bitwise Operators
Unary Operators (Single operand) Bitwise Operators
▸ + Unary plus (rarely used) ▸ & Bitwise AND
▸ - Unary minus: negates value ▸ | Bitwise OR
▸ ++ Increment: adds 1 (prefix ++a, postfix a++) ▸ ^ Bitwise XOR
▸ -- Decrement: subtracts 1 (prefix --a, postfix a--) ▸ ~ Bitwise complement (NOT)
▸ ! Logical complement: !true = false ▸ << Left shift
▸ >> Right shift
▸ >>> Unsigned right shift
Operator Precedence & Associativity
Precedence Operators Associativity

1 (Highest) () [] . Left to Right

2 ++ -- (postfix) Left to Right

3 ++ -- + - ! ~ (prefix) Right to Left

4 */% Left to Right

5 +- Left to Right

6 << >> >>> Left to Right

7 < > <= >= instanceof Left to Right

8 == != Left to Right

9 & Left to Right

10 ^ Left to Right

11 | Left to Right
Ternary & instanceof Operators
Java Code

• Ternary Operator: Shorthand for if-else statement


// Ternary operator
• Syntax: condition ? expression1 : expression2 int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
• If condition is true → expression1 executes, else →
String result = (marks > 40) ? "Pass" : "Fail";
expression2
// Nested ternary (not recommended)
• instanceof Operator: Checks if object is instance of a
int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b :
class c);

• Returns boolean: true if object is instance, false // instanceof operator


otherwise String str = "Hello";
boolean isString = str instanceof String; // true
• Useful for type checking before casting objects Object obj = str;
boolean isStr = obj instanceof String; // true

Note: Ternary operator improves readability for simple conditions; avoid nesting
05
Control Statements
Duration: 4 Hours
Control Statements: Program Flow Control
• Selection (Decision-Making): if, if-else, if-else-if, switch
• Iteration (Looping): for, while, do-while, for-each (enhanced for)
• Jump (Branching): break, continue, return
• Control statements determine the order of execution of statements
• Essential for implementing algorithms and business logic
• Proper use of control statements improves code efficiency and readability

Note: Control statements are the foundation of all programming logic


if, if-else & if-else-if Ladder
Java Code

• if statement: Executes block only if condition is true


// if statement
• if-else: Executes one block if true, another if false if (number > 0) {
[Link]("Positive");
• if-else-if ladder: Checks multiple conditions sequentially }

• Nested if-else: if-else inside another if-else block // if-else


if (number > 0) {
• Conditions must evaluate to boolean (true/false) [Link]("Positive");
} else {
• Curly braces {} are optional for single statements but [Link]("Not Positive");
}
recommended
// if-else-if ladder
if (number > 0) {
[Link]("Positive");
} else if (number < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
}

Note: Always use braces {} to avoid dangling else problems


switch Statement
Java Code

• Executes one block among many alternatives based on


switch (day) {
expression value
case 1:
[Link]("Monday");
• Expression can be: byte, short, int, char, String (Java 7+),
break;
enum case 2:
[Link]("Tuesday");
• case labels must be constant values (literals or final break;
variables) case 3:
[Link]("Wednesday");
• break statement prevents fall-through to next case break;
default:
• default case executes when no case matches [Link]("Invalid day");
break;
• Nested switch statements supported for complex }
decision trees
// Without break - FALL THROUGH
// case 2 executes case 3 and default too!

Note: Always include break in each case to prevent unintended fall-through


for Loop & for-each Loop
Java Code

• for loop: Used when number of iterations is known in


// Standard for loop
advance
for (int i = 1; i <= 5; i++) {
[Link](i);
• Syntax: for (init; condition; update) { body }
}
• Initialization executes once; condition checked before
// Reverse for loop
each iteration for (int i = 5; i >= 1; i--) {
[Link](i);
• Update executes after each iteration; loop ends when }
condition is false
// for-each loop
• for-each loop (enhanced): Iterates over arrays and int[] numbers = {3, 7, 5, -5};
collections for (int num : numbers) {
[Link](num);
• Syntax: for (Type element : collection) { body } }

// Infinite for loop (AVOID!)


for (;;) { } // or for (int i=1; i<=10; i--) { }

Note: for-each loop is cleaner for arrays/collections but cannot modify elements
while vs do-while Loop
while Loop (Entry-controlled) do-while Loop (Exit-controlled)
▸ Condition checked BEFORE entering loop ▸ Condition checked AFTER executing body
▸ May not execute at all if condition is false initially ▸ Executes at least once guaranteed
▸ Syntax: while (condition) { body } ▸ Syntax: do { body } while (condition);
▸ Use when iterations are unknown beforehand ▸ Note the semicolon after while condition
▸ Example: Reading user input until valid ▸ Use when at least one execution is required
while & do-while: Examples
Java Code

• while loop: Sum of positive numbers entered by user


// while loop example
• do-while loop: Menu-driven program that shows menu int sum = 0, number = 0;
Scanner input = new Scanner([Link]);
at least once
while (number >= 0) {
sum += number;
• Both loops require updating loop variable to avoid
number = [Link]();
infinite loops }

• while(true) creates intentional infinite loop (use break to // do-while example


exit) int choice;
do {
• Nested loops: One loop inside another for multi- [Link]("1. Add 2. Subtract 3. Exit");
dimensional processing choice = [Link]();
// process choice
} while (choice != 3);

Note: while: check-then-act | do-while: act-then-check


Nested Loops & Pattern Printing
Java Code

• Nested loop: One loop inside another loop


// Half pyramid pattern
• Outer loop controls rows, inner loop controls columns for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
• Inner loop completes ALL iterations for each outer loop [Link](j + " ");
}
iteration
[Link]();
}
• Common applications: Matrix operations, pattern
// Output:
printing, 2D array traversal // 1
// 1 2
• Can mix loop types: for inside while, do-while inside for, // 1 2 3
etc. // 1 2 3 4
// 1 2 3 4 5
• Be careful with complexity: nested loops increase time
complexity // Matrix traversal
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](matrix[i][j] + " ");
}
}

Note: Pattern printing is excellent for understanding nested loop control flow
Jump Statements: break, continue, return
Java Code

• break: Exits the current loop or switch statement


// break example
immediately
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
• continue: Skips remaining code in current iteration,
[Link](i); // prints 1,2,3,4
proceeds to next }

• return: Exits current method and optionally returns a // continue example


value for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
• break with labels: Can break out of nested loops (labeled [Link](i); // prints odd numbers only
break) }

• continue with labels: Skips to next iteration of labeled // return example


loop public int add(int a, int b) {
return a + b; // exits method with result
• return type must match method's declared return type }

Note: break exits the loop; continue skips to next iteration; return exits the method
06
Arrays in Java
Duration: 3 Hours
Arrays: Introduction & Declaration
Java Code

• Array: Collection of similar data types stored in


// Declaration methods
contiguous memory
int[] numbers;
double data[];
• Fixed size: Size must be specified at creation and cannot
change // Memory allocation
numbers = new int[10]; // 10 integers
• Index-based access: First element at index 0, last at index
(length-1) // Combined declaration and allocation
int[] age = new int[5];
• Declaration: dataType[] arrayName; or dataType
arrayName[]; // Declaration with initialization
int[] scores = {85, 90, 78, 92, 88};
• Memory allocation: arrayName = new dataType[size];
// Index-based initialization
• Combined: dataType[] arrayName = new dataType[size]; age[0] = 12;
age[1] = 4;
age[2] = 5;

Note: Array indices always start at 0; accessing index[-1] or index[length] causes ArrayIndexOutOfBoundsException
Array Operations: Access, Modify, Length
Java Code

• Access elements using array[index] notation


int[] numbers = {1, 2, 3, 4, 5};
• Modify elements by assigning new value to specific index
// Access
• length property returns number of elements (not a [Link](numbers[0]); // 1
[Link](numbers[2]); // 3
method!)
// Modify
• Loop through arrays using for loop or for-each loop
numbers[2] = 10; // {1, 2, 10, 4, 5}
• [Link]() for quick printing of array contents
// Length
[Link]([Link]); // 5
• [Link] class provides sorting, searching, filling
utilities // Loop through
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

// for-each loop
for (int num : numbers) {
[Link](num);
}

Note: length is a property (not method), so no parentheses: [Link] not [Link]()


[Link] Class Utilities
Java Code

• [Link](array): Sorts array in ascending order


import [Link];
• [Link](array, key): Searches sorted array
int[] nums = {5, 2, 8, 1, 9};
(returns index or negative)
// Sort
• [Link](array, newLength): Creates copy with
[Link](nums); // {1, 2, 5, 8, 9}
specified length
// Search
• [Link](array, value): Fills entire array with given value int index = [Link](nums, 5); // 2

• [Link](array1, array2): Checks element-by- // Copy


element equality int[] copy = [Link](nums, [Link]);

• [Link](array): Returns string representation of // Fill


array [Link](nums, 0); // {0, 0, 0, 0, 0}

• [Link]() and [Link]() for multi- // Compare


dimensional arrays boolean equal = [Link](nums, copy);

// Print
[Link]([Link](nums));

Note: Always import [Link] to use these utility methods


Two-Dimensional Arrays (Matrices)
Java Code

• 2D Array: Array of arrays - represents tabular data (rows


// 2D Array declaration
× columns)
int[][] matrix = new int[3][3];
• Declaration: dataType[][] arrayName = new
// Initialization
dataType[rows][cols]; int[][] matrix = {
{1, 2, 3},
• Jagged arrays: Each row can have different number of {4, 5, 6},
columns {7, 8, 9}
};
• Access: arrayName[rowIndex][colIndex] (both 0-based)
// Jagged array (different row lengths)
• Nested loops used for traversal and processing int[][] jagged = {
{1, 2, 3},
• Common operations: Matrix addition, multiplication, {4, 5},
transpose {6}
};

// Access and traverse


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
Note: [Link] = number of rows | matrix[i].length = columns in row i
3D & Multi-dimensional Arrays
Java Code

• 3D Array: Array of 2D arrays - visualized as cube (depth ×


// 3D Array declaration
rows × columns)
int[][][] cube = new int[2][3][4];
• Declaration: dataType[][][] arrayName = new
// Initialization
dataType[depth][rows][cols]; int[][][] data = {
{
• Access requires three indices: array[depth][row][col] {1, -2, 3},
{2, 3, 4}
• Three nested loops required for complete traversal },
{
• Used in 3D graphics, scientific computing, complex data {-4, -5, 6, 9},
modeling {1},
{2, 3}
• Memory footprint increases exponentially with each }
dimension };

// Traverse with nested loops


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < data[i].length; j++) {
for (int k = 0; k < data[i][j].length; k++) {
[Link](data[i][j][k] + " ");
}
[Link]();
}
Note: Higher dimensions follow same pattern: array of (n-1) dimensional arrays
}
Matrix Operations: Addition & Multiplication
Java Code

• Matrix Addition: Corresponding elements added (same


// Matrix Addition
dimensions required)
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
• Matrix Multiplication: Row × Column dot product
sum[i][j] = a[i][j] + b[i][j];
}
• Multiplication condition: cols of first = rows of second
}
• Result dimensions: (r1 × c1) × (r2 × c2) = (r1 × c2) where
// Matrix Multiplication
c1 = r2 for(int i = 0; i < r1; i++) {
for(int j = 0; j < c2; j++) {
• Transpose: Swap rows and columns (matrix[i][j] → for(int k = 0; k < c1; k++) {
transpose[j][i]) product[i][j] += a[i][k] * b[k][j];
}
• These operations are fundamental in graphics, ML, and }
scientific computing }

// Transpose
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
transpose[j][i] = matrix[i][j];
}
}

Note: Matrix multiplication uses three nested loops; addition uses two nested loops
07
Basic Input & Output
Duration: 1 Hour
Java Output: print, println, printf
Java Code

• [Link](): Prints text without newline


// print vs println
• [Link](): Prints text with newline at end [Link]("Hello ");
[Link]("World"); // Hello World
• [Link](): Formatted output (C-style
[Link]("Hello");
formatting)
[Link]("World"); // Hello\nWorld\n
• System is a class, out is a static PrintStream field
// printf formatting
int age = 20;
• String concatenation using + operator for mixed output
double pi = 3.14159;
String name = "Java";
• Format specifiers: %d (int), %f (float), %s (string), %c
(char), %n (newline) [Link]("Name: %s, Age: %d, PI: %.2f%n",
name, age, pi);
// Output: Name: Java, Age: 20, PI: 3.14

// Concatenation
[Link]("Number = " + number);

Note: Use printf for formatted output; println for simple line output
Java Input: Scanner Class
Java Code

• Scanner class in [Link] package for reading user input


import [Link];
• Create Scanner object: Scanner input = new
Scanner input = new Scanner([Link]);
Scanner([Link]);
// Reading different types
• Methods: nextInt(), nextDouble(), nextFloat(),
[Link]("Enter integer: ");
nextLong(), next() int num = [Link]();

• nextLine(): Reads entire line including spaces [Link]("Enter decimal: ");


double decimal = [Link]();
• next(): Reads single token (stops at whitespace)
[Link]("Enter text: ");
• Always close Scanner: [Link]() to prevent resource String text = [Link]();
leaks
[Link]("Enter line: ");
[Link](); // consume newline
String line = [Link]();

[Link](); // close scanner

Note: Call nextLine() after nextInt()/nextDouble() to consume leftover newline


Syllabus Experiments: Module 1 Practice
• Experiment 1.1: Hello World program - Basic syntax and output
• Experiment 1.2: Variables and Data Types - Declaration, initialization, types
• Experiment 1.3: Arithmetic Operations - Using all arithmetic operators
• Experiment 1.4: Conditional Statements - if-else, switch implementations
• Experiment 1.5: Loops - for, while, do-while, nested loops
• Experiment 1.6: String Operations - String class methods and manipulation
• Experiment 1.7: Arrays - 1D arrays, traversal, basic operations
• Experiment 1.8: Matrix Operations - 2D arrays, addition, multiplication, transpose

Note: Each experiment should include problem statement, algorithm, code, output, and conclusion
Practice Problems: Decision Making (if-else)
• 1. Find maximum between two/three numbers
• 2. Check if number is positive, negative, or zero
• 3. Check divisibility by 5 and 11
• 4. Check even or odd number
• 5. Check leap year
• 6. Check if character is alphabet, vowel, consonant, digit, or special char
• 7. Input week/month number and print corresponding name
• 8. Calculate grade based on percentage (A, B, C, D, E, F)
• 9. Calculate gross salary based on basic salary with HRA and DA rules
• 10. Calculate electricity bill with slab rates and surcharge

Note: 40+ practice problems available in course material for skill building
Practice Problems: Loops & Arrays
• Loop Problems: Sum of natural numbers, factorial, Fibonacci series
• Pattern Printing: Half pyramid, full pyramid, inverted pyramid, diamond
• Number Problems: Prime check, palindrome, Armstrong number, reverse digits
• Array Problems: Find largest/smallest, search element, count occurrences
• Array Operations: Insert, delete, merge two arrays
• Matrix Problems: Add, multiply, transpose, find diagonal sum
• Sorting: Bubble sort, selection sort on arrays
• Searching: Linear search, binary search implementation

Note: Practice is essential for mastering control structures and array manipulation
Module 1: Course Outcomes (CO1)
• CO1: Recall the features and basic syntax of Java (Remembering Level)
• Understand Java tokens: keywords, identifiers, literals, operators, separators
• Apply variables and data types correctly in programs
• Use all categories of operators with proper precedence understanding
• Implement selection statements (if-else, switch) for decision making
• Implement iteration statements (for, while, do-while) for repetition
• Use jump statements (break, continue, return) for flow control
• Declare, initialize, and manipulate 1D, 2D, and 3D arrays
• Perform basic input/output operations using Scanner and [Link]

Note: CO1 maps to PO1 (Engineering Knowledge), PO2 (Problem Analysis), PSO1 (Programming Fundamentals)
Key Takeaways: Module 1
• Java is platform-independent through JVM and bytecode
• Tokens are the smallest units: keywords, identifiers, literals, operators, separators
• 8 primitive data types + non-primitive types (String, arrays, classes)
• Operators: Arithmetic, Assignment, Relational, Logical, Unary, Bitwise, Ternary
• Control Statements: if-else (decision), switch (multi-way), loops (repetition)
• Arrays store homogeneous data: 1D (list), 2D (matrix), 3D (cube)
• Scanner class for input; [Link] for output
• Practice 40+ problems to build strong programming foundation

Note: Strong foundation in Module 1 is essential for OOP concepts in Module 2


Thank You
Questions & Discussion | Next: Module 2 - Object-Oriented Programming in Java

CUCS1004 | Java Programming | Module 1 | 15 Hours

You might also like