Basic Java Lectures
Basic Java Lectures
Lecture 1
1. Install Java
a. Install JDK (https://www.oracle.com/in/java/technologies/javase-downloads.html)
b. Install IntelliJ (https://www.jetbrains.com/idea/download/#section=mac)
OR
b. Install Visual Studio Code (VS Code) - Prefer THIS
(https://code.visualstudio.com/download)
2. Sample Code
Functions
A function is a block of code which takes some input, performs some operations
and returns some output.
The functions stored inside classes are called methods.
The function we have used is called main.
Class
A class is a group of objects which have common properties. A class can have
some properties and functions (called methods).
The class we have used is Main.
Apna College
Java - Introduction to Programming
Lecture 2
1. Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).
package com.apnacollege;
2. Data Types
Data types are declarations for variables. This determines the type and size of
data associated with variables which is essential to know since different data
types occupy different sizes of memory.
Apna College
Data Type Meaning Size Range
(in Bytes)
char Character 2 a, b, c ..
A, B, C ..
@, #, $ ..
Eg : String, Arrays
3. Constants
A constant is a variable in Java which has a fixed value i.e. it cannot be assigned
a different value once assigned.
Apna College
package com.apnacollege;
Homework Problems
1. Try to declare meaningful variables of each type. Eg - a variable
named age should be a numeric type (int or float) not byte.
(HINT - You will have to write 10 lines for this but as we proceed in
the course you will be studying about ‘LOOPS’ that will simplify
your work A LOT!)
Apna College
Java - Introduction to Programming
Lecture 3
int n = 1;
switch(n) {
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
default :
System.out.println("Sunday");
}
Apna College
Homework Problems
1. Make a Calculator. Take 2 numbers (a & b) from the user and an
operation as follows :
1 : + (Addition) a + b
● 2 : - (Subtraction) a - b
● 3 : * (Multiplication) a * b
● 4 : / (Division) a / b
● 5 : % (Modulo or remainder) a % b
2. Ask the user to enter the number of the month & print the name
of the month. For eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ &
so on.
Apna College
Java - Introduction to Programming
Lecture 4
Loops
A loop is used for executing a block of statements repeatedly until a particular
condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.
For Loop
The syntax of the for loop is :
While Loop
The syntax for while loop is :
while(condition) {
// body of the loop
}
int i = 0;
while(i<=20) {
System.out.println(i);
i++;
}
Do-While Loop
The syntax for the do-while loop is :
do {
// body of loop;
}
while (condition);
int i = 0;
do {
System.out.println(i);
Apna College
i++;
} while(i<=20);
Homework Problems
1. Print all even numbers till n.
2. Run
for(; ;) {
System.out.println("Apna College");
loop on your system and analyze what happens. Try to think of the reason for
the output produced.
3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.
If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).
BONUS
[In this problem you will learn how to check if a number is prime or not]
Apna College
Homework Solution (Lecture 3)
import java.util.*;
/**
* 1 -> +
* 2 -> -
* 3 -> *
* 4 -> /
* 5 -> %
*/
switch(operator) {
case 1 : System.out.println(a+b);
break;
case 2 : System.out.println(a-b);
break;
case 3 : System.out.println(a*b);
break;
case 4 : if(b == 0) {
System.out.println("Invalid Division");
} else {
System.out.println(a/b);
}
break;
case 5 : if(b == 0) {
System.out.println("Invalid Division");
} else {
System.out.println(a%b);
}
break;
default : System.out.println("Invalid Operator");
}
}
Apna College
}
Apna College
Java - Introduction to Programming
Lecture 5
Patterns - Part 1
1.
import java.util.*;
Apna College
2.
import java.util.*;
Apna College
3.
import java.util.*;
Apna College
4.
import java.util.*;
Apna College
5.
import java.util.*;
Apna College
6.
import java.util.*;
Apna College
7.
import java.util.*;
Apna College
8.
import java.util.*;
Apna College
9.
import java.util.*;
Apna College
Homework Problems (Solutions in next Lecture’s Video)
1. Print a solid rhombus.
Apna College
Homework Solution (Lecture 4)
3. int n = 25;
4.
6. if(i % 2 == 0) {
7. System.out.println(i);
8. }
9. }
10. }
11. }
12.
3. Make a menu driven program. The user can enter 2 numbers, either 1 or 0.
If the user enters 1 then keep taking input from the user for a student’s
marks(out of 100).
Apna College
(Hint : use do-while loop but think & understand why)
import java.util.*;
do {
int marks = sc.nextInt();
if(marks >= 90 && marks <= 100) {
System.out.println("This is Good");
} else if(marks >= 60 && marks <= 89) {
System.out.println("This is also Good");
} else if(marks >= 0 && marks <= 59) {
System.out.println("This is Good as well");
} else {
System.out.println("Invalid");
}
} while(input == 1);
}
}
[In this problem you will learn how to check if a number is prime or not]
import java.util.*;
Apna College
if(n % i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
if(n == 1) {
System.out.println("This is neither prime not composite");
} else {
System.out.println("This is a prime number");
}
} else {
System.out.println("This is not a prime number");
}
}
}
Apna College
Java - Introduction to Programming
Lecture 6
Patterns - Part 2
1.
import java.util.*;
//upper part
for(int i=1; i<=n; i++) {
for(int j=1; j<=i; j++) {
System.out.print("*");
}
Apna College
//lower part
for(int i=n; i>=1; i--) {
for(int j=1; j<=i; j++) {
System.out.print("*");
}
2.
import java.util.*;
Apna College
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
System.out.print(" ");
}
//stars
for(int j=1; j<=n; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Apna College
3.
import java.util.*;
//numbers
for(int j=1; j<=i; j++) {
System.out.print(i+" ");
}
System.out.println();
}
}
}
Apna College
4.
import java.util.*;
//first part
for(int j=i; j>=1; j--) {
System.out.print(j);
}
//second part
for(int j=2; j<=i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Apna College
5.
import java.util.*;
//upper part
for(int i=1; i<=n; i++) {
//spaces
for(int j=1; j<=n-i; j++) {
System.out.print(" ");
}
for(int j=1; j<=2*i-1; j++) {
System.out.print("*");
}
System.out.println();
}
//lower part
for(int i=n; i>=1; i--) {
//spaces
for(int j=1; j<=n-i; j++) {
System.out.print(" ");
}
for(int j=1; j<=2*i-1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Apna College
Homework Problems
1. Print a hollow Butterfly.
*****
* *
* *
* *
*****
11
121
1331
14641
Apna College
12
123
1234
12345
11111
222
33
Apna College
Java - Introduction to Programming
Lecture 7
Methods/Functions
A function is a block of code that performs a specific task.
Why are functions used?
a. If some functionality is performed at multiple places in software, then
rather than writing the same code, again and again, we create a function
and call it everywhere. This helps reduce code redundancy.
b. Functions make maintenance of code easy as we have to change at one
place if we make future changes to the functionality.
c. Functions make the code more readable and easy to understand.
The return type of a function is the data type of the variable that that function
returns.
For eg - If we write a function that adds 2 integers and returns their sum then
the return type of this function will be ‘int’ as we will return a sum that is an
integer value.
When a function does not return any value, in that case the return type of the
function is ‘void’.
function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used.
Parameters
A function can take some parameters as inputs. These parameters are specified
along with their data types.
For eg- if we are writing a function to add 2 integers, the parameters would be
passed like –
int add (int num1, int num2)
Apna College
main function
The main function is a special function as the computer starts running the code
from the beginning of the main function. Main function serves as the entry point
for the program.
Example :
package com.apnacollege;
}
}
import java.util.*;
//Multiply 2 numbers
return a*b;
Apna College
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(result);
import java.util.*;
System.out.println(factorial);
return;
}
Apna College
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
printFactorial(n);
}
}
// int sum = a + b;
// return sum;
// }
return a * b;
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(calculateProduct(a, b));
Apna College
Homework Problems
1. Make a function to check if a number is prime or not.
2. Make a function to check if a given number n is even or not.
3. Make a function to print the table of a given number n.
4. Read about Recursion.
Apna College
Java - Introduction to Programming
Exercise 1
Questions
1. Enter 3 numbers from the user & make a function to print their average.
2. Write a function to print the sum of all odd numbers from 1 to n.
3. Write a function which takes in 2 numbers and returns the greater of those
two.
4. Write a function that takes in the radius as input and returns the
circumference of a circle.
5. Write a function that takes in age as input and returns if that person is eligible
to vote or not. A person of age > 18 is eligible to vote.
6. Write an infinite loop using do while condition.
7. Write a program to enter the numbers till the user wants and at the end it
should display the count of positive, negative and zeros entered.
8. Two numbers are entered by the user, x and n. Write a function to find
𝑛
the value of one number raised to the power of another i.e. 𝑥 .
9. Write a function that calculates the Greatest Common Divisor of 2 numbers.
(BONUS)
10. Write a program to print Fibonacci series of n terms where n is input
by user :
0 1 1 2 3 5 8 13 21 .....
In the Fibonacci series, a number is the sum of the previous 2 numbers that
came before it.
(BONUS)
Apna College
Java - Introduction to Programming
Exercise 1 SOLUTIONS
1. Enter 3 numbers from the user & make a function to print their average.
//Try to convert it into a function on your own.
import java.util.*;
int average = (a + b + c) / 3;
System.out.println(average);
}
}
System.out.println(sum);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
printSum(n);
}
}
3. Write a function which takes in 2 numbers and returns the greater of those
two.
import java.util.*;
4. Write a function that takes in the radius as input and returns the
circumference of a circle.
import java.util.*;
} while(true);
}
}
7. Write a program to enter the numbers till the user wants and at the end it
should display the count of positive, negative and zeros entered.
import java.util.*;
8. Two numbers are entered by the user, x and n. Write a function to find
𝑛
the value of one number raised to the power of another i.e. 𝑥 .
//Try to convert it into a function on your own.
import java.util.*;
int result = 1;
//Please see that n is not too large or else result will exceed the size
of int
for(int i=0; i<n; i++) {
result = result * x;
}
while(n1 != n2) {
if(n1>n2) {
n1 = n1 - n2;
} else {
n2 = n2 - n1;
}
}
System.out.println("GCD is : "+ n2);
}
}
int a = 0, b = 1;
System.out.print(a+" ");
if(n > 1) {
//find nth term
for(int i=2; i<=n; i++) {
System.out.print(b+" ");
//the concept below is called swapping
int temp = b;
b = a + b;
a = temp;
}
System.out.println();
}
}
}
Java - Introduction to Programming
Lecture 10
Arrays In Java
Arrays in Java are like a list of elements of the same type i.e. a list of integers, a list of
booleans etc.
a. Creating an Array (method 1) - with new keyword
int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
Apna College
Homework Problems
1. Take an array of names as input from the user and print them on the screen.
import java.util.*;
//input
names[i] = sc.next();
//output
Apna College
[HINT : Read about Integer.MIN_VALUE & Integer.MAX_VALUE in Java]
import java.util.*;
//input
numbers[i] = sc.nextInt();
min = numbers[i];
max = numbers[i];
Apna College
System.out.println("Largest number is : " + max);
//input
numbers[i] = sc.nextInt();
Apna College
for(int i=0; i<numbers.length-1; i++) { // NOTICE numbers.length - 1 as
termination condition
isAscending = false;
if(isAscending) {
} else {
Apna College
Java - Introduction to Programming
Lecture 11
2D Arrays In Java
//input
//rows
for(int i=0; i<rows; i++) {
//columns
for(int j=0; j<cols; j++) {
numbers[i][j] = sc.nextInt();
}
}
Apna College
}
//input
//rows
for(int i=0; i<rows; i++) {
//columns
for(int j=0; j<cols; j++) {
numbers[i][j] = sc.nextInt();
}
}
int x = sc.nextInt();
}
}
Apna College
Homework Problems
1. Print the spiral order matrix as output for a given matrix of numbers.
[Difficult for Beginners]
APPROACH :
Apna College
to column_end and we will increase the row_start with 1 as we have
import java.util.*;
int n = sc.nextInt();
int m = sc.nextInt();
matrix[i][j] = sc.nextInt();
int rowStart = 0;
Apna College
int rowEnd = n-1;
int colStart = 0;
//1
rowStart++;
//2
colEnd--;
//3
rowEnd--;
//4
Apna College
System.out.print(matrix[row][colStart] + " ");
colStart++;
System.out.println();
int n = sc.nextInt();
int m = sc.nextInt();
matrix[i][j] = sc.nextInt();
Apna College
System.out.println("The transpose is : ");
System.out.print(matrix[i][j]+" ");
System.out.println();
Apna College
Java - Introduction to Programming
Lecture 12
Strings
Declaration
String name = "Tony";
Taking Input
Scanner sc = new Scanner(System.in);
String name = sc.next();
Apna College
Compare 2 strings
import java.util.*;
if(name1.equals(name2)) {
System.out.println("They are the same string");
} else {
System.out.println("They are different strings");
}
}
}
Substring
The substring of a string is a subpart of it.
public class Strings {
public static void main(String args[]) {
String name = "TonyStark";
System.out.println(name.substring(0, 4));
Apna College
}
}
}
}
}
}
Apna College
Homework Problems
1. Take an array of Strings input from the user & find the cumulative (combined)
length of all those strings.
import java.util.*;
int totLength = 0;
array[i] = sc.next();
totLength += array[i].length();
System.out.println(totLength);
2. Input a string from the user. Create a new string called ‘result’ in which you
will replace the letter ‘e’ in the original string with letter ‘i’.
Example :
Apna College
import java.util.*;
if(str.charAt(i) == 'e') {
result += 'i';
} else {
result += str.charAt(i);
System.out.println(result);
3. Input an email from the user. You have to create a username from the email
by deleting the part that comes after ‘@’. Display that username to the user.
Example :
Apna College
import java.util.*;
if(email.charAt(i) == '@') {
break;
} else {
userName += email.charAt(i);
System.out.println(userName);
Apna College
Java - Introduction to Programming
Lecture 13
String Builder
Declaration
StringBuilder sb = new StringBuilder("Apna College");
System.out.println(sb);
Apna College
Delete char at some Index
import java.util.*;
//delete char
sb.delete(0, 1);
System.out.println(sb);
}
}
Append a char
Append means to add something at the end.
import java.util.*;
System.out.println(sb.length());
}
}
Apna College
Reverse a String (using StringBuilder class)
import java.util.*;
sb.setCharAt(front, backChar);
sb.setCharAt(back, frontChar);
}
System.out.println(sb);
}
}
Homework Problems
Try Solving all the String questions with StringBuilder.
Apna College
Java - Introduction to Programming
Lecture 14
Bit Manipulation
Get Bit
import java.util.*;
if((bitMask & n) == 0) {
System.out.println("bit was zero");
} else {
System.out.println("bit was one");
}
}
}
Set Bit
import java.util.*;
Apna College
Clear Bit
import java.util.*;
public class Bits {
public static void main(String args[]) {
int n = 5; //0101
int pos = 2;
int bitMask = 1<<pos;
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
System.out.println(newNumber);
}
}
Update Bit
import java.util.*;
}
}
Apna College
Homework Problems
1. Write a program to find if a number is a power of 2 or not.
2. Write a program to toggle a bit a position = “pos” in a number “n”.
3. Write a program to count the number of 1’s in a binary representation
of the number.
4. Write 2 functions => decimalToBinary() & binaryToDecimal() to convert
a number from one number system to another. [BONUS]
Apna College