0% found this document useful (0 votes)
10 views16 pages

Knowledge Base

The document provides an overview of fundamental Java programming concepts, including history, syntax, variables, operators, conditionals, loops, arrays, methods, classes, and object-oriented programming principles. Key topics include the compilation process, debugging techniques, data types, and the use of Java's standard library. Additionally, it covers advanced topics like inheritance, polymorphism, and immutability, along with practical examples and quizzes for reinforcement.

Uploaded by

vkfmvp777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Knowledge Base

The document provides an overview of fundamental Java programming concepts, including history, syntax, variables, operators, conditionals, loops, arrays, methods, classes, and object-oriented programming principles. Key topics include the compilation process, debugging techniques, data types, and the use of Java's standard library. Additionally, it covers advanced topics like inheritance, polymorphism, and immutability, along with practical examples and quizzes for reinforcement.

Uploaded by

vkfmvp777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 1: Computer Programming

Key Concepts:

 History and Purpose:


Initially, programs were written in low-level code hardwired to the
computer’s processor instructions. High-level languages like Java make
programs easier to write, read, and maintain. Java’s “write once, run
anywhere” philosophy is achieved through the JVM (Java Virtual
Machine).

 Hello World & Compilation Process:

public class Hello {

public static void main(String[] args) {

System.out.println("Hello, World!");

How It Works:

1. Save in Hello.java.

2. javac Hello.java compiles source code into Hello.class bytecode.

3. java Hello runs the bytecode on the JVM, printing "Hello, World!".

 Basic Syntax:
Every Java program has at least one class, and to run it, that class
must have a main method. Each statement ends with ;. Curly braces
define blocks of code (classes, methods, loops, etc.).

 Escape Sequences:
\n for newline, \t for tab, etc. If you do:

System.out.println("Line 1\nLine 2\tIndented");

This prints:

mathematica

Line 1

Line 2 Indented
 Debugging Techniques: If you see a compile error like ; expected,
you forgot a semicolon. If you see cannot find symbol, maybe you
spelled a variable name incorrectly.

Quizzes & Kahoot Reinforcement:

 Q: What is the entry point of a Java program? A: The main method:


public static void main(String[] args).

 Q: If System.out.println("Hello") is missing a semicolon, what happens?


A: The compiler gives a syntax error. You must add the missing
semicolon.

Example Explanation:

 If we write:

System.out.println("Hello\tWorld\nNew line here");

It prints "Hello World" (with a tab space) on one line, then "New line here" on
the next line. The \t adds a horizontal tab space, \n moves to the next line.

Chapter 2: Variables and Operators


Key Concepts:

 Variables and Data Types:

int age = 20; // integer

double price = 19.99; // floating-point number

boolean isActive = true; // boolean true/false

String name = "Alice"; // string of characters

 Arithmetic Operators:
+ addition, - subtraction, * multiplication, / division, % remainder.
Integer division truncates decimals. For example, 5/2 is 2, not 2.5. To
get a decimal, cast one operand to double: (double)5/2 = 2.5.

 Floating-Point Precision: Double variables can have tiny rounding


errors:

double x = 0.1 + 0.2;


System.out.println(x); // might print 0.30000000000000004 instead of 0.3

This is normal for floating-point arithmetic. Just be aware.

 String Operations:

String greeting = "Hello, " + name; // concatenation

If name = "Alice", greeting = "Hello, Alice".

Quizzes & Kahoot Reinforcement:

 Q: int followers=1000; followers+=500; followers now? A: 1500.

 Q: int a=5,b=2; System.out.println(a/b); prints what? A: 2 (integer


division).

 Q: How to force floating division? A: (double)a/b; → (double)5/2 = 2.5.

Example Explanation:

 Consider:

int x=5,y=2;

System.out.println(x/y); // prints 2

System.out.println((double)x/y); // prints 2.5 because we cast x to double

Casting changes the type of one operand, thus performing floating-point


division.

More on Arithmetic, Type Casting, and I/O (Ch.1-3, Intro to Ch.4)

Type Casting:

int n=7;

double result=(double)n/2; // without casting, 7/2=3, with casting=3.5

Scanner and I/O (Chapter 3): Use Scanner to read user input:

Scanner sc = new Scanner(System.in);

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

int age = sc.nextInt(); // reads an integer

sc.nextLine(); // consume leftover newline before reading a line


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

String name = sc.nextLine(); // reads a full line, including spaces

Literals & Constants:

final int MAX_SCORE=100; // cannot change MAX_SCORE later

Quizzes & Kahoot Reinforcement:

 Q: After reading an int with nextInt(), what to do before nextLine()? A:


Call sc.nextLine() to clear the leftover newline.

 Q: How do you ensure a decimal result if dividing two ints? A: Cast one
to double, e.g. (double)5/2.

Example Explanation:

 Suppose:

System.out.print("Enter count: ");

int count=sc.nextInt();

sc.nextLine(); // now sc is ready for next line reading.

System.out.print("Enter a sentence: ");

String sentence=sc.nextLine();

Here, count is read as an int. nextLine() afterwards ensures the next full line
read is cleanly captured, not just the leftover newline.

Conditionals and Loops (Ch.5 & Ch.6)


if (score >= 90) System.out.println("A");

else if (score >= 80) System.out.println("B");

else System.out.println("C or below");

This checks score ranges in order. The first true condition executes.

switch:

switch(day) {

case 1: System.out.println("Monday"); break;


case 2: System.out.println("Tuesday"); break;

default: System.out.println("Other day");

switch is cleaner than multiple if-else for known discrete values.

Boolean Logic & De Morgan’s:

 !(A && B) = (!A || !B). This can simplify conditions.

Loops (Ch.6):

 while loop: Repeat until condition fails.

int i=0;

while(i<5){

System.out.println(i);

i++;

 for loop: For known iteration counts.

for(int j=0;j<5;j++){

System.out.println(j);

 do-while loop: Executes body once before checking condition.

int input;

do {

input=sc.nextInt();

} while(input<=0);

String Methods:

 s.charAt(i) returns character at index i.

 s.substring(start,end) returns portion of string from start to end-1.

 s.indexOf('a') gives first occurrence of 'a'.

Quizzes & Kahoot Reinforcement:


 Q: Validate input until >0. Which loop? A: do-while or while:

int num;

do {

num=sc.nextInt();

} while(num<=0);

 Q: How to print odd numbers from 10 down to 1? A: Use a for loop:

for(int k=10;k>0;k--){

if(k%2!=0) System.out.println(k+" is odd.");

Example Explanation:

 Suppose you want to read a positive number:

int num;

do {

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

num=sc.nextInt();

} while(num<=0);

If user enters -5 first, loop repeats. Once a positive number is given, the loop
exits.

Arrays (Ch.7)
Key Concepts:

 Array Creation:

int[] arr=new int[5];

arr[0]=10; arr[1]=20; ...

 Traversing Arrays:

for(int val:arr) System.out.println(val);

Prints each element.


 Common Tasks: Summation:

int sum=0; for(int val:arr) sum+=val;

double avg=(double)sum/arr.length;

 Arrays are Reference Types: If you do int[] x={1,2}; int[] y=x;


changes via y reflect in x.

Quizzes & Kahoot Reinforcement:

 Q: How to find max in an array? A:

int max=arr[0];

for(int val:arr) if(val>max) max=val;

 Q: Avoiding IndexOutOfBounds? A: Use conditions i<array.length.

Example Explanation:

 Counting how many numbers >50:

int count=0;

for (int val: arr) {

if(val>50) count++;

This loop checks each element and increments count if it’s greater than 50.

Javadoc & Java API (Appendix B)


Key Concepts:

 Reading JavaDocs:
The Java standard library documentation shows you what methods are
available, their parameters, and return types.

 Writing Javadoc:

/**

* Computes area of circle.

* @param r radius
* @return area as double

*/

public static double area(double r){return Math.PI*r*r;}

Quizzes & Kahoot Reinforcement:

 Q: Why Javadoc? A: To produce easy-to-read documentation for users


of your code.

Example Explanation:

 Using Arrays.toString():

int[] arr={3,1,4};

System.out.println(Arrays.toString(arr));

// Outputs: [3, 1, 4]

This is useful for debugging array contents.

Methods and Recursion (Ch.4 & Ch.8)


Methods with Returns:

 Example:

public static int add(int a,int b){

return a+b;

Calling int sum=add(3,4); sum becomes 7.

Testing Methods: Test add() with known values: add(2,2)=4, add(-1,1)=0. If


results match expectations, the method works.

Recursion (Ch.8):

 Factorial example:

public static int factorial(int n){

if(n<=1)return 1;

return n*factorial(n-1);
}

How it works: factorial(3) → checks 3<=1? no → returns 3*factorial(2) →


factorial(2) returns 2*factorial(1) which returns 1 → so total 3*2*1=6.

Quizzes & Kahoot Reinforcement:

 Q: Difference between void and return methods? A: void methods


don't return values, return methods must provide a result.

 Q: Identify base case in recursion? A: The simplest case that returns


without recursion. For factorial, if(n<=1)return 1;

Example Explanation:

 Summation via recursion:

public static int sumArray(int[] arr,int idx){

if(idx==arr.length) return 0; // base case: no more elements

return arr[idx] + sumArray(arr,idx+1); // add current element + recurse

If arr=[1,2,3], sumArray(arr,0) → 1+sumArray(arr,1) →


1+(2+sumArray(arr,2)) → 1+(2+(3+sumArray(arr,3))) → 1+2+(3+0)=6.

Programmer-Defined Classes (Ch.10)


Key Concepts:

 Class Design:
A class groups variables (fields) and methods that logically belong
together.

 Constructors:

public class Astronaut {

private String name;

private int health;

public Astronaut(String name){

this.name=name;
this.health=100;

public String getName(){return name;}

public int getHealth(){return health;}

public void setHealth(int h){

if(h>=0&&h<=100)this.health=h;

Encapsulation: Keeping fields private and using getters/setters ensures no


invalid data is set.

Quizzes & Kahoot Reinforcement:

 Q: If you define a constructor with parameters, do you get a no-arg


constructor? A: No, you must define it yourself if needed.

 Q: Why private fields? A: To control changes through setters,


maintaining class invariants.

Example Explanation:

 If you try to do astronaut.health=200; directly, you can't since health is


private. Instead use astronaut.setHealth(200); which won't set it
because it fails the condition, preserving valid state.

More Methods & Classes (Ch. 8 & 10


revisited)
Key Concepts:

 Method Overloading:

public int add(int a,int b){return a+b;}

public double add(double a,double b){return a+b;}

Same method name, different parameter types for flexibility.


 Refining Classes: Add utility methods as needed. If a class does
multiple unrelated tasks, split it into separate classes.

Quizzes & Kahoot Reinforcement:

 Q: Overloading vs. Overriding? A: Overloading: same class, different


params. Overriding: subclass changes inherited method from
superclass.

Example Explanation:

 Overloaded print method:

public void print(int x){System.out.println("int: "+x);}

public void print(String s){System.out.println("String: "+s);}

If you call print(5), it calls the int version. If you call print("Hi"), it calls the
string version.

OOP & Immutable Objects (Ch.9) + Big O


Notation
Immutable Objects:

 String is Immutable:

String s="cat";

s.replace('c','b'); // returns "bat" but s still "cat"

s=s.replace('c','b'); // now s="bat"

 Advantages of Immutability: Less complex reasoning, no accidental


changes, safer with concurrency.

Wrapper Classes & Immutability: Integer, Double are also immutable. If


you do Integer i=5; i=i+1;, you’re actually creating new Integer objects.

Big O Notation: Just know O(n) means linear growth, O(n^2) means
quadratic growth.

Quizzes & Kahoot Reinforcement:

 Q: After String s="hello"; s.toUpperCase(); what's s? A: Still "hello"


because toUpperCase() returns a new String.
 Q: Why immutability helps in multi-threading? A: Because no thread
can alter the object's state, reducing complexity in synchronization.

Example Explanation:

 If you have:

String s="Hello";

String upper=s.toUpperCase();

upper = "HELLO", s still "Hello". Two separate strings now exist.

Inheritance (Ch.11)
Key Concepts:

 Inheritance Basics:

public class Person {

protected String name;

public Person(String name){this.name=name;}

public String getName(){return name;}

public class Student extends Person {

private int grade;

public Student(String name,int grade){

super(name); // calls Person(name)

this.grade=grade;

@Override

public String getName(){

return "Student: "+super.getName();

}
}

Here, Student is a Person plus extra attributes.

 Polymorphism:
Person p=new Student("Bob",90);

System.out.println(p.getName()); // calls Student’s overridden getName

 Method Overriding: Match signature exactly to change behavior in


subclass.

 Null Pointers: If Person p=null; p.getName(); causes


NullPointerException because p references no object.

Quizzes & Kahoot Reinforcement:

 Q: Are private fields accessible in subclass? A: No, you must use


getters/setters or protected fields.

 Q: Can Java have multiple class inheritance? A: No, only single


inheritance. But a class can implement multiple interfaces.

Example Explanation:

 Overriding equals:

@Override

public boolean equals(Object o){

if(!(o instanceof Student)) return false;

Student other=(Student)o;

return this.getName().equals(other.getName()) &&


this.grade==other.grade;

This ensures two Students are equal if they have same name and grade.

Wrapper Classes (Ch.9 revisited)


Key Concepts:

 Autoboxing/Unboxing:
Integer obj=10; // autobox int to Integer

int x=obj; // unbox Integer to int

 Why Wrappers? Needed when working with collections (e.g.,


ArrayList<Integer>).

Quizzes & Kahoot Reinforcement:

 Q: Difference between int x=10; and Integer y=10;? A: x is a primitive,


y is an object. y can be null, x cannot.

Example Explanation:

 Using Integer in an ArrayList:

ArrayList<Integer> list=new ArrayList<>();

list.add(5); // autoboxes 5 to Integer(5)

int num=list.get(0); // unboxes to int

Additional Quizzes & Kahoot Questions Integrated

 Q: If System.out.println("Hello "+5+3); what prints? A: "Hello 53".


String concatenation turns 5+3 into string "5" followed by "3".

 Q: Validate user input:

int value;

do {

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

value=sc.nextInt();

} while(value<=0);

This ensures one attempt minimum and re-prompts if invalid.

 Q: Overriding vs Overloading:

o Overloading: same name, different parameters.

o Overriding: same signature, different class (subclass overrides


superclass method).
 Q: Encapsulation: Keep fields private, provide getters/setters to control
how fields are changed.

 Q: Abstract classes?

o Can have constructors and concrete methods.

o Cannot instantiate directly.

 Q: equals method must accept Object to properly override equals from


Object class.

Putting It All Together (Integrated Example):

Scenario: You need to:

1. Prompt user for N (positive integer).

2. Read N salaries into an int array.

3. Calculate average using a method calculateAverage(int[] arr).

4. Count how many salaries are above average using countAbove(int[]


arr, float avg).

5. Use a class Rational to represent the fraction of how many salaries are
above average compared to total.

Step-by-Step:

 Input and validation:

int N;

do {

System.out.print("Enter howymany salaries: ");

N=sc.nextInt();

} while(N<=0);

 Read array:

int[] salaries=new int[N];

for(int i=0;i<N;i++){

System.out.print("Salary "+(i+1)+": ");


salaries[i]=sc.nextInt();

 Calculate average:

float avg=calculateAverage(salaries);

System.out.println("Average: "+avg);

 Count above average:

int above = countAbove(salaries, avg);

System.out.println("Salaries above average: "+above);

 Rational class could store fractions like (above/N). If above=2, N=5,


fraction is 2/5.

Rational ratio=new Rational(above,N);

System.out.println("Ratio of above avg: "+ratio);

This scenario uses input validation (loops, conditionals), arrays, methods


returning values, possibly classes for rational representation, and all learned
concepts.

Final Exam Note

 Trace Execution:
For code snippets, run through them line by line. Keep track of variable
values.

 Check Loop Boundaries:


Off-by-one errors are common. If you have an array of length 5, valid
indices are 0 to 4 only.

 Review Overloading vs Overriding: Overloading: same method


name in same class, different parameters.
Overriding: subclass changes the behavior of a method inherited from
a superclass.

 Understand NullPointerException: If a reference is null, calling


methods on it causes an error. Always initialize objects before use.

You might also like