Partial preview of the text
Download Basics of Java programming part 2 and more Lecture notes Computer science in PDF only on Docsity!
Chapter 2: Basics of Java Programming 2.1 Tokens in Java A token is the smallest element of a program. Java tokens are: 1. Keywords — Reserved words (cannot be used as identifiers). Example: class, public, static, int, if, else, for, while + Java has 50+ keywords. 2. Identifiers - Names given to classes, methods, variables, etc. Rules: © Must begin with a letter, _, or $ ° Cannot use keywords © Case-sensitive 3. Literals — Fixed values: ° Integer literals: 10, -25 © Floating-point: 3.14, 2.5e3 o Character: 'A', '9' © String: "Hello Java" © Boolean: true, false 4. Operators — Symbols to perform operations (explained in 2.3). 5. Separators-; , . [] {} () 2.2 Variables in Java A variable is a named memory location used to store data. Declaration: Java int age = 20; String name = "Pranav"; Types of Variables: 1. Local Variable - Declared inside a method, accessible only within it. 2. Instance Variable — Declared inside a class but outside any method. Each object has its own copy. 3. Static Variable - Declared with static keyword. Shared among all objects. Non-Primitive Data Types: ¢ String e Arrays * Classes ¢ Interfaces 2.4 Type Casting Converting one data type into another. 1. Widening (Implicit Casting) — Smaller to larger data type. Java int x = 10; double y = x; // int = double 7. Ternary Operator - condition ? expr1 : expr2 Java int max = (a >b)? a: b; 2.6 Control Statements in Java Control flow decides how instructions are executed. (A) Decision-Making Statements 1. if statement Java if(age >= 18){ System.out.println("Eligible to vote"); } 2. if-else Java if(marks >= 40){ System.out.println("Pass"); } else { System.out.println("Fail"); } 3. if-else-if ladder Java if(marks >= 90) System.out.println("Grade A"); else if(marks >= 75) System.out.println("Grade B"); else if(marks >= 50) System.out.println("Grade C"); else System.out.println¢("Fail"); 2. while loop Java int i=1; whileci<=5){ System.out.println(i); i++; 3. do-while loop Java int i=1; do{ System.out.println(i); itt; } while(i<=5); (C) Jump Statements ¢ break — Exit loop/switch * continue — Skip current iteration * return — Exit from method 2.7 Example Program (using all basics) Java class Basics { public static void main(String[] args) { int num = 10; if(num % 2 == O){ System.out.println(num + " is Even"); } else { System.out.println¢(num + " is. Odd"); } ForCiet dT) is-8i Let System.out.printci + " "); }