-
- Introduction to Java
- First Java Application
- Escape sequences
- Types of Comments
- Java program's Phases
- Variable & Data types
- Format specifiers
- Getting user inputs
- Operators, Operands, Expression
- Control Statement
- Control Statement
- Arrays and ArrayList
- String Manipulation
- Object Oriented Programming
- Object Oriented Programming
-
Intermediate
-
All assignments
- Assignment 1 (Print User Information)
- Assignment 2 (Variable and Data type)
- Assignment 3 (User Input)
- Assignment 4 (installment amount for per month)
- Assignment 5 (valid voter using if else)
- Assignment 6 (Digit spelling using if else)
- Assignment 7 (logical OR operators and if else)
- Assignment 8 (Logical AND assignment and if-else)
- Assignment 9 (Call center using switch)
- Assignment 10 (find sum of 1-10 using for loop)
- Assignment 11 (find factorial of n)
- Assignment 12 (print sum of odd numbers from m-n)
- Assignment 13 (find nth fibonacci number)
- Assignment 14 (Palindrome number)
- Assignment 15 (Armstrong number)
- Assignment 16 (find nth fibonacci number)
- Assignment 17 (Pattern program)
- Assignment 18 (Print the day name)
-
Operators
- calculator programs - area, temperature
- days to time converter program: 10 days = seconds?
-
Control statement
-
conditional control statement: if, else if, else, switch
- Even/odd program
- Pass/Fail program
- valid voter program
- Positive/Negative/Zero program
- Digit spelling program
- Large/small program
- Leap year program
- Vowel/Consonant program
- small/capital letter
- assignments
-
Loop control statement: for, while, do while
-
Jump control statement: break, continue, return
- print 1-100 using for, while, do while loop
- print a-z
- print 2,4,...100 / even numbers from 1-100
- print 1,3,...99 / odd numbers from 1-100
- print sum of 1-n numbers
- print sum of even numbers from 1-100
- print sum of odd numbers from 1-100
- factorial of n
- series related program: 1+2+3+ ... + n
- series related program: 1^2+2^2+3^2+ ... + n^2
- Fibonacci series
- multiplication table
- nested related problems
- prime numbers
- prime numbers from 1 to n
- sum of digits
- reverse a number
- palindrome number
- Armstrong number
- user is valid or not by checking username,password
- Pattern related program
-
-
Data structure
- Array
- introduction to array
- sum and average
- maximum and minimum
- for each in array
- 2d array
- array matrix
- sum of diagonal, upper triangle, lower triangle elements of a matrix
- array output test
- array sorting
- ArrayList
- LinkedList
- HashMap
- HashSet
- Array
-
String
- String
- StringBuffer
- StringBuilder
-
Date & Time
-
What is Java?
- Java is a high level; OOP (Object Oriented Programming) language originally developed by sun microsystem but currenly owned by Oracle.
-
Why Should we learn Java / Features of Java?
- Platform Independent - WORA (Write Once Run Anywhere)
- Object Oriented
- Support web based application
- Robust (example - exception handling)
- Multi-threaded
-
What does platform independent means?
- Test.java -> javac -> Test.class (ByteCode) -> Any JVM in any OS can run the ByteCode
-
History of Java
- C++ was not platform independent and could not support netwrok programming so sun microsystem took a project called "green project" in 1990 to sort out this issue.
- James Gosling (Father of Java), Patrick Naughton and Mike Sheridan was working in this project.
- At first it was names as Oak programming language but in 1994 they named it as Java.
- Java was officially released in 1995.
-
Environment Setup
-
JDK: Java Development Kit is a software development environment used for developinh java applications and applets. It includes Java Runtimne Environment (JRE), an interpreter / loader (java), a compiler (javac), a document generator (javadoc) and other toold needed in java development. Check JDK is installed or not by using this command
java -version
in your terminal -
IDE: Integrated Development Environment. An Integrated Development Environment (IDE) is a software application that provides comprehensive tools and features to facilitate software development. Examples of IDE's: Eclipse, NetBeans, Visual Studio Code, JDeveloper, IntelliJ IDEA, Programiz Java Compiler. Here are some reasons why developers use IDEs:
-
Code Editing: IDEs offer advanced code editing capabilities such as syntax highlighting, code completion, and error checking. These features help developers write code more efficiently and with fewer mistakes.
-
Debugging: IDEs provide debugging tools that allow developers to step through their code, set breakpoints, and inspect variables. Debugging tools help identify and fix issues in the code during development.
-
Build and Compilation: IDEs integrate with build systems and compilers, making it easier to build, compile, and run the code. They can automate repetitive tasks such as compiling, packaging, and deploying the application.
-
Project Management: IDEs provide project management features that help organize and manage code files, libraries, and resources. They offer features like code navigation, search, and refactoring tools, making it easier to work with large codebases.
-
Version Control Integration: IDEs often have built-in support for version control systems like Git. They provide features to commit, update, and manage code changes, making collaboration with other developers smoother.
-
Code Templates and Snippets: IDEs offer code templates and snippets that help speed up development by providing predefined code structures or commonly used code snippets.
-
Testing and Profiling: IDEs may include tools for writing and running tests, as well as performance profiling to identify bottlenecks in the code and optimize performance.
-
Integration with Frameworks and Libraries: Many IDEs provide integration with popular frameworks and libraries, offering features like code generation, automated configuration, and easy access to documentation.
-
-
- File Extension .java
- Every java application must have a class. class name must start with a capital letter.
- A package is a folder which holds collection of classes and interfaces. package names are typically written in lowercase letters.
// A program to print your info
// Understand the program flow
// keywords in Java - Keywords are reserved words and also in small letters
// How to create a class, function
// How to print in Java - use System.out.Println() or print()
// what is string? printing string in quotation
// printing numeric value does not require double quotation
class Program1 {
public static void main(String[] args) {
System.out.print("Product Infos");
System.out.println("Product: iphone 14");
System.out.println("Price: $1300");
System.out.println("Quantity: 14");
}
}
// Escape sequence - a special character followed by backslash. sometimes it is called as backshalsh character
// example -> \b, \t, \n, \", \', \\
class Test {
public static void main(String[] args) {
System.out.print("\"Product Infos\"\n");
System.out.println("Product:\t iphone 14");
System.out.println("Price:\t\t $1300");
System.out.println("Quantity:\t 14");
}
}
-
Comments are used to add explanatory notes or annotations within the source code. It is good practice to add meaningful comments to your code to enhance its understandability and maintainability. Comments can help you and other developers understand the purpose of the code, clarify complex logic, or provide reminders for future modifications. Java supports three types of comments:
- Single-line comments: Single-line comments begin with two forward slashes (
//
) and extend to the end of the line. They are used for short comments or explanations on a single line.
// This is a single-line comment int age = 25; // Variable representing the age
- Multi-line comments: Multi-line comments, also known as block comments, begin with a forward slash followed by an asterisk (
/*
) and end with an asterisk followed by a forward slash (*/
). They can span multiple lines and are often used for longer explanations or comment blocks.
/* This is a multi-line comment It can span multiple lines Used for longer explanations or comment blocks */
- Javadoc comments: Javadoc comments are a special type of comment used for generating documentation from the source code. They begin with a forward slash followed by two asterisks (
/**
) and end with an asterisk followed by a forward slash (*/
). Javadoc comments are used to describe classes, methods, and fields and can include tags for specifying parameters, return values, exceptions, and more.
/** * This is a Javadoc comment. * It can be used to generate documentation. * @param name the name of the person * @return a greeting message */ public String greet(String name) { return "Hello, " + name + "!"; }
- Single-line comments: Single-line comments begin with two forward slashes (
- A variable is a container for storing data. When declaring variables in Java, there are certain rules and conventions to follow. syntax: data-type variable-name; Here are the key rules for variable declarations:
-
Variable Names:
- Must start with a letter, underscore (_), or dollar sign ($).
- Can include letters, digits, underscores, and dollar signs.
- Cannot be a reserved word (e.g., keywords like "int", "class", "public").
- Follow camelCase convention (start with a lowercase letter, capitalize each subsequent word).
-
Initialization:
- Variables can be initialized at the time of declaration or later in the code.
- Uninitialized local variables cannot be used until they are assigned a value.
-
Scope:
- Variables have different scopes, such as local scope, method scope, or class scope.
- Local variables are declared within a block of code and are only accessible within that block.
- Class variables (also known as static variables) are shared across instances of a class.
- Instance variables belong to a specific instance of a class.
-
Constants:
- Constants are declared using the
final
keyword to indicate that their value cannot be changed. - Constant variable names are typically written in uppercase with underscores for word separation (e.g., final int MAX_VALUE = 100).
- Constants are declared using the
-
Naming Conventions:
- Use meaningful and descriptive names for variables.
- Follow camelCase convention for variable names (e.g., firstName, numItems).
- Avoid using single-character variable names (except for loop counters or temporary variables).
- Choose names that are easy to understand and maintain.
-
Declaration and Assignment:
- Declare variables before using them in the code.
- Variables should be assigned values appropriate to their data type.
- Variables can be assigned new values using the assignment operator (=).
Here's an example that illustrates these rules:
class Test {
public static void main(String[] args) {
String productName = "iphone 14";
double productPrice = 1300;
int productQuantity = 14;
final double PRODUCT_DISCOUNT = 10.133;
System.out.println("Product Infos");
System.out.println("Product: " + productName);
System.out.println("Price: $" + productPrice);
System.out.println("Quantity: " + productQuantity);
System.out.println("Discount: " + PRODUCT_DISCOUNT);
}
}
/*
* Learning outcomes
* variable declaration
* variable initalization
* dynamic initialization
* data types
*/
public class Program4 {
public static void main(String[] args) {
// declaring variables for a student
String name;
int id, age;
double gpa;
boolean isRegisted;
// initializing variables for a student
name = "Anisul Islam";
id = 1302020017;
age = 25;
gpa = 3.92;
isRegisted = true;
// printing variables
System.out.println("Student Information");
System.out.println("--------------------");
System.out.println("Name: "+name);
System.out.println("ID: "+id);
System.out.println("Age: "+age);
System.out.println("GPA: "+gpa);
System.out.println("Registered: "+isRegisted);
}
}
By following these rules and conventions, you can write clean, readable, and maintainable code in Java.
/*
* Assignment-2 (Variable and Data type)
* step 1: create a class called Product
* step 2: create a main method
* step 3: declare variables: id, title, price, description, category
* step 4: assign the following data in main method
101,iphone15,1895 euros,perfect product with best image quality, phone,
* step 5: print the data
*/
- Format specifiers in Java are used to control the formatting of values when outputting them using methods like System.out.printf() or String.format(). They provide a way to specify how a value should be displayed, including its width, precision, alignment, and data type.
/*
* Learning outcomes
* format specifiers
*/
public class Program5 {
public static void main(String[] args) {
// declaring variables for a student
String name;
int id, age;
double gpa;
boolean isRegisted;
// initializing variables for a student
name = "Anisul Islam";
id = 1302020017;
age = 25;
gpa = 3.92;
isRegisted = true;
// printing variables
System.out.println("Student Information");
System.out.println("--------------------");
System.out.printf("Name: "+name);
System.out.printf("Name: %s\n",name);
System.out.printf("ID : %d: \n",id);
System.out.printf("Age: %d\n",age);
System.out.printf("GPA: %.2f\n",gpa);
System.out.printf("Registered: %b\n",isRegisted);
}
}
import java.util.Scanner;
class Test {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
// String productName = input.next(); // does not count anything after space
System.out.print("Enter Product Name: ");
String productName = input.nextLine();
System.out.print("Enter Product Price: ");
double productPrice = input.nextDouble();
System.out.print("Enter Product Quantity: ");
int productQuantity = input.nextInt();
final double PRODUCT_DISCOUNT = 10.133;
System.out.println("Product Infos");
System.out.println("Product: " + productName);
System.out.println("Price: $" + productPrice);
System.out.println("Quantity: " + productQuantity);
System.out.println("Discount: " + PRODUCT_DISCOUNT);
}
}
}
/*
Learning outcome
how to get user input
Read a byte - nextByte()
Read a short - nextShort()
Read an int - nextInt()
Read a long - nextLong()
Read a float - nextFloat()
Read a double - nextDouble()
Read a boolean - nextBoolean()
Read a complete line - nextLine()
Read a word - next()
*/
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// declaring variables for a student
String name;
int id, age;
double gpa;
boolean isRegisted;
// getting inputs for a student
System.out.print("Enter student name: ");
name = input.nextLine();
System.out.print("Enter student id: ");
id = input.nextInt();
System.out.print("Enter student age: ");
age = input.nextInt();
System.out.print("Enter student gpa: ");
gpa = input.nextDouble();
System.out.print("Enter student is isregistered? true/false : ");
isRegisted = input.nextBoolean();
// printing variables
System.out.println("Student Information");
System.out.println("--------------------");
System.out.println("Name: "+name);
System.out.println("ID: "+id);
System.out.println("Age: "+age);
System.out.println("GPA: "+gpa);
System.out.println("Registered: "+isRegisted);
}
}
/*
* Assignment-3 (User Input)
* step 1: create a class called Product
* step 2: create a main method
* step 3: declare variables: id, title, price, description, category
* step 4: get user input for each variables
* step 5: print the variables
*/
- In Java, operators are symbols or characters that perform specific operations on operands (variables, literals, or expressions). They are used to manipulate and process data within expressions and statements. Here are the different types of operators in Java:
-
Arithmetic Operators:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Modulus (remainder):
%
- Increment:
++
- Decrement:
--
// Example of Arithmetic operators import java.util.Scanner; public class Program7 { public static void main(String[] args) { int number1, number2, result; Scanner input = new Scanner(System.in); System.out.print("number1 = "); number1 = input.nextInt(); System.out.print("number2 = "); number2 = input.nextInt(); result = number1 + number2; System.out.println(number1 +" + "+number2 + " = "+result); result = number1 - number2; System.out.println(number1 +" - "+number2 + " = "+result); result = number1 * number2; System.out.println(number1 +" * "+number2 + " = "+result); // type casting double result2 = (double)number1 / number2; System.out.println(number1 +" / "+number2 + " = "+result2); result = number1 % number2; System.out.println(number1 +" % "+number2 + " = "+result); } }
// Example of Unary Operators /* * Unary Operator * Unary Plus, minus * increment -> prefix increment, postfix increment * decrement -> prefix decrement, postfix decrement */ public class Program10 { public static void main(String[] args) { int x = 10; System.out.println(+x); System.out.println(-x); System.out.println(x++); System.out.println(++x); System.out.println(x); System.out.println(x--); System.out.println(--x); } }
- Addition:
-
Assignment Operators:
- Assignment:
=
- Addition assignment:
+=
- Subtraction assignment:
-=
- Multiplication assignment:
*=
- Division assignment:
/=
- Modulus assignment:
%=
// Example of Assignment operators public class Program8 { public static void main(String[] args) { int x = 10; x += 1; System.out.println("x = "+x); x -= 1; System.out.println("x = "+x); x *= 1; System.out.println("x = "+x); x /= 1; System.out.println("x = "+x); x %= 1; System.out.println("x = "+x); } }
- Assignment:
-
Comparison Operators:
- Equal to:
==
- Not equal to:
!=
- Greater than:
>
- Less than:
<
- Greater than or equal to:
>=
- Less than or equal to:
<=
- Equal to:
-
Logical Operators:
- Logical AND:
&&
- Logical OR:
||
- Logical NOT:
!
- Logical AND:
-
Bitwise Operators:
- Bitwise AND:
&
- Bitwise OR:
|
- Bitwise XOR:
^
- Bitwise NOT:
~
- Left shift:
<<
- Right shift:
>>
- Unsigned right shift:
>>>
// Example of bitwise operators
- Bitwise AND:
-
Conditional (Ternary) Operator:
- The conditional operator (
?:
) is used to assign a value based on a condition. It has the formcondition ? expression1 : expression2
. If the condition is true,expression1
is evaluated and assigned; otherwise,expression2
is evaluated and assigned.
// ternary/conditional operator exp1 ? exp2 : exp3 public class Program16 { public static void main(String[] args) { int number = 20; String result = number%2==0 ? "even" : "odd"; System.out.println(result); } }
- The conditional operator (
-
Instanceof Operator:
- The instanceof operator is used to check if an object belongs to a particular class or implements an interface. It has the form
object instanceof type
.
- The instanceof operator is used to check if an object belongs to a particular class or implements an interface. It has the form
-
Other Operators:
- Dot Operator (
.
): Used to access members of a class or object. - Comma Operator (
,
): Used to separate expressions in a statement. - Parentheses (
()
): Used to group expressions and specify evaluation order. - Square Brackets (
[]
): Used for array indexing. - New Operator: Used to create objects with the
new
keyword.
- Dot Operator (
import java.util.Scanner;
// Create a program to calculate installment amount for per month
public class Assignment4 {
public static void main(String[] args) {
(Scanner input = new Scanner(System.in)) {
int phonePrice = 1800; // 1800 euros
int numberOfInstallment, installmentPerMonth;
System.out.print("Number of installments? ");
// get number of installments from user
// calculate installment amount for per month
System.out.println("Monthly installment Amount: "+installmentPerMonth + " euros");
}
}
}
// Area of Triangle Program
import java.util.Scanner;
public class Program9 {
public static void main(String[] args) {
double base, height, area;
Scanner input = new Scanner(System.in);
System.out.print("Enter Base = ");
base = input.nextInt();
System.out.print("Enter Height = ");
height = input.nextInt();
area = 0.5 * base * height;
System.out.println("Area of Triangle = "+area);
}
}
// Temperature convert
// F = 9/5 C + 32
import java.util.Scanner;
class Test {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Enter Celsisu : ");
double celsius = input.nextDouble();
double fahrenheit = 9 / 5.0 * celsius + 32;
System.out.println("Fahrenheit: " + fahrenheit);
}
}
}
- There are 3 types of control statements: Conditional, loop, jump control statements.
-
if Statement: It executes a block of code if a certain condition is true.
-
if-else Statement: It executes one block of code if the condition is true and another block if the condition is false.
-
if-else-if Ladder: It allows multiple conditions to be checked one after another, and the corresponding block of code is executed based on the first condition that evaluates to true.
-
switch Statement: It checks a variable against multiple possible values and executes the code block associated with the matching value.
-
Positive, Negative Program - if, else if, else
// Positive, Negative Program - if, else if, else public class Program12 { public static void main(String[] args) { int number = 12; if(number>0){ System.out.println("Positive"); }else if(number<0){ System.out.println("Negative"); }else{ System.out.println("Zero"); } } }
-
Switch: Day of week
// Switch: Day of week public class Program12 { public static void main(String[] args) { int dayOfWeek = 3; switch (dayOfWeek) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Unknown day"); } } }
- vowel or consonant program
// vowel or consonant program import java.util.Scanner; public class Program13 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a letter: "); char ch = input.next().charAt(0); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { System.out.println("Vowel"); } else { System.out.println("Consonant"); } } } }
- small /capital letter
// small /capital letter import java.util.Scanner; public class Program14 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a letter: "); char ch = input.next().charAt(0); if (ch >= 'a' && ch <= 'z') { System.out.println("Small letter"); } else if (ch >= 'A' && ch <= 'Z') { System.out.println("Capital letter"); } else { System.out.println("Not a letter"); } } } }
-
/*
* valid voter program using if,else
* step 1: ask for a person age
* step 2: if age is equal or more than 18 than print valid voter
* step 3: else print invalid voter
*/
public class Assignment5 {
public static void main(String[] args) {
}
}
/*
* Digit spelling program using if,else if, else
* step 1: ask for a digit between 0-9
* step 2: check the digit and print it by spelling. example if user input is 0 then print Zero
* step 3: if the digit is not among 0-9 then print Invalid digit
*/
public class Assignment6 {
public static void main(String[] args) {
}
}
// Logical or assignment
// step 1: Print "Do you love java? "
// step 2: take user input y / Y / n / N
// step 3: if user input y / Y then print you are a java lover
// step 4: if user input n / N then print you are not a java lover
public class Assignment7 {
public static void main(String[] args) {
}
}
// Logical AND assignment
// Check eligible candidate
// Step 1: Ask the candidate have you completed your masters? y/n
// Step 2: Ask the candidate are you fulent in English? y/n
// Step 3: if the candidate has passed masters and also have fluent english skill then print you are eligible to for the job interview
// Step 4: else print Sorry. you are not eligible to for the job interview
public class Assignment8 {
public static void main(String[] args) {
}
}
// switch assignment: call center
// if user select option 1 then set language bengali
// if user select option 2 then set language hindi
// if user select option 3 then set language urdu
// for any other option set language english
public class Assignment9 {
public static void main(String[] args) {
// get the OPTION from user
// use switch, case, break and default
// Selected language is Bengali
// Selected language is Hindi
// Selected language is Urdu
// Selected language is English
}
}
-
while Loop: It repeatedly executes a block of code as long as a condition is true.
-
do-while Loop: It executes a block of code at least once and then repeatedly executes it as long as a condition is true.
-
for Loop: It allows you to specify the initialization, condition, and iteration in a single line and repeatedly executes a block of code based on the condition.
-
for-each Loop: It is used to iterate over elements of an array or a collection.
- Example of for, while, do while, for each loop
// print 1-10 using loop control statements System.out.println("Using for loop:"); for (int i = 1; i <= 10; i++) { System.out.println(i); } System.out.println("Using while loop:"); int i = 1; while (i <= 10) { System.out.println(i); i++; } System.out.println("Using do-while loop:"); int i = 1; do { System.out.println(i); i++; } while (i <= 10); System.out.println("Using for-each loop:"); int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int number : numbers) { System.out.println(number); }
- Sum of digits Program
import java.util.Scanner; class Test { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a number: "); int number = input.nextInt(); int temp = number; int remainder, sum = 0; while (temp != 0) { remainder = temp % 10; sum = sum + remainder; temp = temp / 10; } System.out.println("The sum of digits of " + number + " = " + sum); } catch (Exception e) { System.out.println(e); } } }
- Reverse number Program
import java.util.Scanner; class Test { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a number: "); int number = input.nextInt(); int temp = number; int remainder, reverse = 0; while (temp != 0) { remainder = temp % 10; reverse = (reverse * 10) + remainder; temp = temp / 10; } System.out.println("The reverse of " + number + " = " + reverse); } catch (Exception e) { System.out.println(e); } } }
- Palindrome number Program
import java.util.Scanner; class Test { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a number: "); int number = input.nextInt(); int temp = number; int remainder, reverse = 0; while (temp != 0) { remainder = temp % 10; reverse = (reverse * 10) + remainder; temp = temp / 10; } if (number == reverse) { System.out.println(number + " is a Palindrome number"); } else { System.out.println(number + " is not a Palindrome number"); } } catch (Exception e) { System.out.println(e); } } }
- Armstrong number Program
import java.util.Scanner; public class Program30 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter any postive integer: "); int number = input.nextInt(); int temp = number; int sum = 0; while(temp!=0){ int r = temp % 10; sum = sum + r*r*r; temp = temp / 10; } if(number == sum){ System.out.println("Armstrong number"); } else{ System.out.println("Not a Armstrong number"); } } } }
- Series program 1+2+3+ ... + n
- Fibonacci series Program 0 1 1 2 3 5 ... n
import java.util.Scanner; public class Program26 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("How many fibonacci numbers? "); int n = input.nextInt(); int first = 0; int second = 1; for(int i=1; i<=n; i++){ if(i<=2){ System.out.print(" "+ (i-1)); }else{ int fibo = first + second; System.out.print(" "+fibo); first = second; second = fibo; } } } } }
- Lucas series Program 2 1 3 4 7 ... n
public class LucasSeries { public static void main(String[] args) { int limit = 10; // Define the limit of the Lucas series System.out.println("Lucas series up to " + limit + ":"); generateLucasSeries(limit); } public static void generateLucasSeries(int limit) { int first = 2; // First number in the Lucas series int second = 1; // Second number in the Lucas series // Print the first two numbers System.out.print(first + " " + second + " "); // Generate subsequent numbers in the Lucas series for (int i = 3; i <= limit; i++) { int next = first + second; System.out.print(next + " "); // Update values for the next iteration first = second; second = next; } System.out.println(); // Print a new line after the series } }
- Pattern related program
// 1 // 1 2 // 1 2 3 import java.util.Scanner; public class Program31 { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter n = "); int n= input.nextInt(); for(int row=1; row<=n; row++){ for (int col=1; col<=row; col++){ System.out.print(" "+col); } System.out.println(); } } } }
// find sum of 1-10 using for loop
public class Assignment10 {
public static void main(String[] args) {
}
}
// find factorial of n
public class Assignment11 {
public static void main(String[] args) {
}
}
// print sum of odd numbers from m-n
public class Assignment12 {
public static void main(String[] args) {
}
}
// find nth fibonacci number
import java.util.Scanner;
public class Assignment13 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("which fibonacci number you want to see? ");
int n = input.nextInt();
}
}
}
// 1. generate and print palindrome numbers from m-n
// 2. count and print number of palindrome numbers
import java.util.Scanner;
public class Assignment14 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("start number: ");
int m = input.nextInt();
System.out.print("end number: ");
int n = input.nextInt();
int totalPalindromeNumber=0;
System.out.println("Total Palindrome numbers : "+totalPalindromeNumber);
}
}
}
// 1. generate and print armstrong numbers from m-n
// 2. count and print number of armstrong numbers
import java.util.Scanner;
public class Assignment15 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("start number: ");
int m = input.nextInt();
System.out.print("end number: ");
int n = input.nextInt();
int totalArmstrongNumber=0;
System.out.println("Total armstrong numbers : "+totalArmstrongNumber);
}
}
}
// Create a pattern like following one if n=4
/*
1
1 0
1 0 1
1 0 1 0
*/
public class Assignment17 {
public static void main(String[] args) {
}
}
-
break Statement: It terminates the current loop or switch statement and transfers control to the statement following the loop or switch.
-
continue Statement: It skips the rest of the current iteration of a loop and moves to the next iteration.
-
return Statement: It terminates the execution of a method and returns control to the caller.
-
throw Statement: It is used to explicitly throw an exception to handle exceptional situations.
-
break and continue example
// break Statement for (int i = 0; i < 5; i++) { if (i == 3) { break; } System.out.println("i: " + i); } // continue Statement for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.println("i: " + i); }
-
Prime number Program
import java.util.Scanner; public class Test { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a positive integer: "); int number = input.nextInt(); int count = 0; if (number < 2) { System.out.println("Not Prime number"); } else { for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { count++; break; } } if (count == 0) { System.out.println("Prime number"); } else { System.out.println("Not Prime number"); } } } catch (Exception e) { System.out.println("Invalid input"); } } }
- Prime number Program using function
import java.util.Scanner; public class PrimeProgram { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { System.out.print("Enter a positive integer: "); int number = input.nextInt(); if (isPrime(number)) { System.out.println("Prime number"); } else { System.out.println("Not Prime number"); } } catch (Exception e) { System.out.println("Invalid input"); } } private static boolean isPrime(int number) { if (number < 2) { return false; } for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { return false; } } return true; } }
- Total Prime number from m to n program
import java.util.Scanner; class Program25 { public static void main(String args[]) { try (Scanner input = new Scanner(System.in)) { int m, n; int count = 0; int totalprime = 0; System.out.print("Enter initial number:"); m = input.nextInt(); System.out.print("Enter last number: "); n = input.nextInt(); for (int i = m; i <= n; i++) { if (i < 2) { continue; } else { for (int j = 2; j < i; j++) { if (i % j == 0) { count++; break; } } if (count == 0) { System.out.println(i); totalprime++; } count = 0; } } System.out.println("total prime:" + totalprime); } } }
-
// validate user based on username and password
// input username and password until username=="anis" and password=="123456"
// if username and password does not match print "username/password is incorrect. Please try again"
// if username and password does not match print "welcome to the system"
- Array: In Java, an array is a data structure that allows you to store a fixed-size collection of elements of the same type. It provides a convenient way to work with groups of related data. Arrays provide a way to store and manipulate collections of elements in a concise and efficient manner. They are widely used in Java to represent lists of items, collections of data, and matrices. Understanding arrays is fundamental for many programming tasks and algorithms. Here's an explanation of arrays in Java:
-
Declaration and Initialization:
- To declare an array, you specify the type of elements it will hold, followed by square brackets
[]
, and then the name of the array. For example:int[] numbers;
- To initialize an array, you can assign it a new array object using the
new
keyword, followed by the type and the size of the array. For example:numbers = new int[5];
- Alternatively, you can declare and initialize an array in a single line:
int[] numbers = new int[5];
- To declare an array, you specify the type of elements it will hold, followed by square brackets
-
Accessing Elements:
- Array elements are accessed using an index, which starts at 0 for the first element. For example:
int firstElement = numbers[0];
- You can assign values to array elements using the index:
numbers[0] = 10;
- Array elements are accessed using an index, which starts at 0 for the first element. For example:
-
Length:
- The length of an array is determined by the number of elements it can hold. You can retrieve the length of an array using the
length
property:int size = numbers.length;
- The length of an array is determined by the number of elements it can hold. You can retrieve the length of an array using the
-
Iterating Over an Array:
-
You can use a loop, such as the
for
loop, to iterate over the elements of an array. For example:for (int i = 0; i < numbers.length; i++) { int element = numbers[i]; // Do something with the element }
-
-
Array Initialization with Values:
- You can initialize an array with values at the time of declaration using an initializer list. For example:
int[] numbers = {1, 2, 3, 4, 5};
- You can initialize an array with values at the time of declaration using an initializer list. For example:
-
Multidimensional Arrays:
- Java also supports multidimensional arrays, where each element is itself an array. For example:
int[][] matrix = new int[3][4];
- we can only assign row size and later the column.
int[][] numbers = new int[4][]; numbers[0] = new int[1]; numbers[1] = new int[2]; numbers[2] = new int[3]; numbers[3] = new int[4];
- Java also supports multidimensional arrays, where each element is itself an array. For example:
-
Array Copying:
- Java provides the
System.arraycopy()
method and theArrays.copyOf()
method to copy the elements of one array to another.
- Java provides the
- one dimensional array example
public class Program32 {
public static void main(String[] args) {
int[] numbers; // array declaration
numbers = new int[5]; //array creation
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
int sum=0;
for(int x=0; x<numbers.length;x++){
sum+=numbers[x];
}
int max=numbers[0];
int min=numbers[0];
for(int x=1;x<numbers.length; x++){
if(max<numbers[x]){
max=numbers[x];
}
if(min>numbers[x]){
min=numbers[x];
}
}
System.out.println("Sum of Array = "+sum);
System.out.println("Average of Array = "+((float)sum/numbers.length));
System.out.println("Maximum number of Array = "+max);
System.out.println("Minimum number of Array = "+min);
}
}
- one dimensional string array example
// for each or enhanched for loop
import java.util.Scanner;
public class Program33 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
String[] countries = {"Bangladesh", "Pakistan", "England", "India"};
for (String country : countries) {
System.out.println(country);
}
}
}
}
- Two dimensional array example
public class Program34 {
public static void main(String[] args) {
int [][] numbers = new int[3][3]; // 3 rows x 3 columns = 9 items
// first row
numbers[0][0] = 1;
numbers[0][1] = 2;
numbers[0][2] = 3;
// second row
numbers[1][0] = 4;
numbers[1][1] = 5;
numbers[1][2] = 6;
// third row
numbers[2][0] = 7;
numbers[2][1] = 8;
numbers[2][2] = 9;
// printing 2d array
for(int row=0; row<numbers.length; row++){
for(int col=0; col<numbers[row].length; col++){
System.out.print(numbers[row][col]);
}
System.out.println();
}
}
}
- Array Matrix Sum Example
import java.util.Scanner;
// Matrix Program
// A + B = ?
public class Program35 {
static void printMatrix(int[][] number) {
for (int row = 0; row < number.length; row++) {
for (int column = 0; column < number[row].length; column++) {
System.out.print(" " + number[row][column]);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] A = new int[2][3];
int[][] B = new int[2][3];
int[][] C = new int[2][3];
try (Scanner input = new Scanner(System.in)) {
System.out.println("Input for A Matrix");
for (int row = 0; row < A.length; row++) {
for (int column = 0; column < A[row].length; column++) {
System.out.printf("A[%d][%d] = ", row, column);
A[row][column] = input.nextInt();
}
}
System.out.println("Printing A Matrix");
printMatrix(A);
System.out.println("Input for B Matrix");
for (int row = 0; row < B.length; row++) {
for (int column = 0; column < B[row].length; column++) {
System.out.printf("B[%d][%d] = ", row, column);
B[row][column] = input.nextInt();
}
}
System.out.println("Printing B Matrix");
printMatrix(B);
// calculating C=A+B
for (int row = 0; row < B.length; row++) {
for (int column = 0; column < B[row].length; column++) {
C[row][column] = A[row][column] + B[row][column];
}
}
System.out.println("Printing C Matrix");
printMatrix(C);
}
}
}
- Array Matrix Multiplication Example
- Array Diagonal Matrix Example
- Create programs based on Array output examples
/**
* 0 1 2 3 4
* 5 6 7 8 9
* 10 11 12 13 14
* 15 16 17 18 19
*/
public class Test {
public static void main(String[] args) {
int[][] A = new int[4][5];
int count = 0;
// assign values to the 2d array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
A[i][j] = count++;
}
}
// print values to the 2d array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
}
/**
* 0
* 1 2
* 3 4 5
* 6 7 8 9
*/
public class Test {
public static void main(String[] args) {
int[][] A = new int[4][];
A[0] = new int[1];
A[1] = new int[2];
A[2] = new int[3];
A[3] = new int[4];
int count = 0;
// assign values to the 2d array
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < i + 1; j++) {
A[i][j] = count++;
}
}
// print values to the 2d array
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
}
- Array sorting (Ascending and descending)
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] numbers = { 10, 4, 32, 45, 99, 2 };
Arrays.sort(numbers);
System.out.print("Ascending order: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(" " + numbers[i]);
}
System.out.println();
System.out.print("Descending order: ");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(" " + numbers[i]);
}
System.out.println();
String[] names = { "Pinky", "Anisul", "Liton", "Sweety" };
Arrays.sort(names);
// we can sort the array just like last time
}
}
import java.util.Scanner;
/*
* Assigment 18 (Print the day name)
* declare an array of weekdays
* User will give a day number you have to print the equivalent day name
*
* Example 1
* input-> Enter day number (1-7) : 1
* output-> Monday
*
* Example 2
* input-> Enter day number (1-7) : 3
* output-> Wednesday
*/
public class Assignment18 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
}
}
}
- Assignment: Array Operations
Write a Java program that performs various operations on an array of integers. Your program should implement the following functionality:
-
Initialization: Initialize an array of integers with the following values: {5, 10, 15, 20, 25}.
-
Sum of Elements: Calculate and print the sum of all elements in the array.
-
Largest Element: Find and print the largest element in the array.
-
Smallest Element: Find and print the smallest element in the array.
-
Average: Calculate and print the average value of all elements in the array.
-
Search: Prompt the user to enter a number to search in the array. Check if the number exists in the array and print an appropriate message.
-
Reverse Order: Reverse the order of elements in the array and print the reversed array.
You can structure your program with appropriate methods for each operation and a main method to run the program. Make sure to provide clear output and handle any necessary user input.
Here's a skeleton code for the assignment:
import java.util.Scanner;
public class ArrayOperations {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
// Call the methods for each operation
int sum = calculateSum(numbers);
System.out.println("Sum of elements: " + sum);
int largest = findLargest(numbers);
System.out.println("Largest element: " + largest);
int smallest = findSmallest(numbers);
System.out.println("Smallest element: " + smallest);
double average = calculateAverage(numbers);
System.out.println("Average: " + average);
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to search: ");
int searchNumber = input.nextInt();
boolean found = searchNumber(numbers, searchNumber);
if (found) {
System.out.println(searchNumber + " exists in the array.");
} else {
System.out.println(searchNumber + " does not exist in the array.");
}
int[] reversed = reverseArray(numbers);
System.out.println("Reversed array: ");
for (int num : reversed) {
System.out.print(num + " ");
}
System.out.println();
}
public static int calculateSum(int[] arr) {
// Calculate the sum of elements
// Implement your logic here
}
public static int findLargest(int[] arr) {
// Find the largest element
// Implement your logic here
}
public static int findSmallest(int[] arr) {
// Find the smallest element
// Implement your logic here
}
public static double calculateAverage(int[] arr) {
// Calculate the average of elements
// Implement your logic here
}
public static boolean searchNumber(int[] arr, int target) {
// Search for the target number in the array
// Implement your logic here
}
public static int[] reverseArray(int[] arr) {
// Reverse the order of elements in the array
// Implement your logic here
}
}
You need to complete the implementation of each method by adding the appropriate logic to perform the operations. Once you have completed the code, you can run the program to see the results of each operation on the given array of integers.
Feel free to customize or extend the assignment according to your needs. Good luck!
-
ArrayList: Array is static or fixed where ArrayList is dynamic and resizeable. Array supports for and for each loop where ArrayList supports for each loop and iterator. Array is faster than ArrayList. Array.length vs ArrayList.size(). some common methods are - size(), add(), addAll(),remove(), set(), get(), clear(), isEmpty(), contains(), indexOf(), equals()
- Example of ArrayList
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; public class Test { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); // Add elements to the ArrayList fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add(3, "Mango"); // remove elements from the ArrayList fruits.remove(3); System.out.println("After removing: " + fruits); // fruits.removeAll(); // fruits.clear(); // set elements fruits.set(2, "Mango"); System.out.println("After setting new item: " + fruits); // Access elements System.out.println("First fruit: " + fruits.get(0)); // Iterate over elements for (String fruit : fruits) { System.out.println(fruit); } // Size of the ArrayList System.out.println("Size: " + fruits.size()); // Check the ArrayList is empty or not System.out.println("isEmpty: " + fruits.isEmpty()); // Check the ArrayList contains an item or not System.out.println("contains Mango: " + fruits.contains("Mango")); // Check the index of an item System.out.println("index of Mango: " + fruits.indexOf("Mango")); // print ArrayList using iterator Iterator itr = fruits.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); System.out.println(numbers); Collections.sort(numbers); System.out.println("After sorting in Ascending order: " + numbers); Collections.reverse(numbers); System.out.println("After sorting in Descending order: " + numbers); } }
In Java, the String
class is a built-in class that represents a sequence of characters. It is used to store and manipulate textual data. Strings in Java are immutable, meaning that their values cannot be changed once created. When you perform operations on strings, such as concatenation or substring extraction, new string objects are created.
The Java String class offers a wide range of methods and functionalities for working with strings efficiently. You can refer to the Java documentation for a comprehensive list of methods available in the String
class.
Here are some key features and operations related to strings in Java:
-
String Declaration and Initialization:
-
Strings can be declared and initialized using the
String
class. For example:String str1 = "Hello"; // Using string literal String str2 = new String("World"); // Using the constructor
-
-
String Concatenation:
-
Strings can be concatenated using the
+
operator or theconcat()
method. For example:String greeting = str1 + " " + str2; String fullGreeting = str1.concat(" ").concat(str2);
-
-
String Length:
-
The length of a string can be obtained using the
length()
method. For example:int length = greeting.length();
-
-
Accessing Characters:
-
Individual characters within a string can be accessed using the
charAt()
method. The index starts at 0. For example:char firstChar = greeting.charAt(0);
-
-
Substrings:
-
Substrings can be extracted from a string using the
substring()
method. For example:String substring = greeting.substring(6, 10); // Extracts "World"
-
-
String Comparison:
-
String equality can be checked using the
equals()
method or the==
operator. For example:boolean isEqual = str1.equals(str2); boolean isSameObject = str1 == str2;
-
-
String Manipulation:
- The
String
class provides various methods for manipulating strings, such as converting case (e.g.,toUpperCase()
,toLowerCase()
), removing whitespace (e.g.,trim()
), replacing characters or substrings (e.g.,replace()
,replaceAll()
), and more.
- The
-
Conversion between String and Primitive Data type:
// other types to String int number = 100; String s = Integer.toString(number); System.out.println(s); double number2 = 100; String s1 = Double.toString(number2); System.out.println(s1); boolean b = true; String s2 = Boolean.toString(b); System.out.println(s2); // String to other types String n = "32"; System.out.println(Integer.parseInt(n)); System.out.println(Double.parseDouble(n)); System.out.println(Double.valueOf(n));
-
Wrapper Class - Autoboxing, unboxing
Autoboxing and unboxing are features in Java that automatically convert between primitive types and their corresponding wrapper classes. These features were introduced to simplify the code and provide a more intuitive way of working with primitive types and their object counterparts.
-
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class. - When you assign a primitive value to a variable of the corresponding wrapper class, autoboxing automatically wraps the primitive value into an object of the wrapper class.
int number = 42; Integer wrappedNumber = number; // Autoboxing from int to Integer
-
Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive type.
-
When you assign a wrapper class object to a variable of the corresponding primitive type, unboxing automatically extracts the primitive value from the object.
-
Example:
Integer wrappedNumber = 42; int number = wrappedNumber; // Unboxing from Integer to int
-
-
Autoboxing and Unboxing in Expressions:
-
Autoboxing and unboxing also apply to expressions involving primitive types and their corresponding wrapper classes.
-
Example:
Integer a = 5; // Autoboxing Integer b = 10; int sum = a + b; // Unboxing, addition, and autoboxing
Autoboxing and unboxing provide a convenient way to work with both primitive types and their object counterparts without requiring explicit conversions. They simplify code readability and reduce the need for manual conversions between primitive types and wrapper classes.
However, it's important to note that autoboxing and unboxing can have performance implications in certain scenarios, as they involve object creation and method calls. Care should be taken when using autoboxing and unboxing in performance-critical code or in situations where memory usage needs to be optimized.
-
-
Random number generator
import java.util.Random;
public class RandomGeneratorExample {
public static void main(String[] args) {
Random random = new Random();
// Generating random integers
int randomInt = random.nextInt();
System.out.println("Random Integer: " + randomInt);
// Generating random integers within a specific range
int randomInRange = random.nextInt(100); // Generates integers from 0 to 99
System.out.println("Random Integer in Range: " + randomInRange);
// Generating random doubles
double randomDouble = random.nextDouble();
System.out.println("Random Double: " + randomDouble);
// Generating random booleans
boolean randomBoolean = random.nextBoolean();
System.out.println("Random Boolean: " + randomBoolean);
}
}
- Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which represent real-world entities. Java is an object-oriented programming language that fully supports OOP principles. OOP key concepts: Inheritance, Encapsulation, Abstraction, Polymorphism
-
Class: A class is a template from which individual object is created. A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have.
public class Car { // Properties String brand; String color; int year; // Behaviors void startEngine() { System.out.println("Engine started!"); } void drive() { System.out.println("Car is driving."); } }
-
Object: Any class type variable is known as object. An object is an instance of a class. It represents a specific entity based on the class blueprint. Objects are created using the new keyword and the class constructor.
public class Main { public static void main(String[] args) { // Create Car objects Car car1 = new Car(); Car car2 = new Car(); // Set object properties car1.brand = "Toyota"; car1.color = "Red"; car1.year = 2020; car2.brand = "Honda"; car2.color = "Blue"; car2.year = 2019; // Invoke object behaviors car1.startEngine(); car1.drive(); car2.startEngine(); car2.drive(); // priniting cars details System.out.println("Car1 details: "); System.out.println("Brand: " + car1.brand); System.out.println("Color: " + car1.color); System.out.println("Year: " + car1.year); System.out.println("Car2 details: "); System.out.println("Brand: " + car2.brand); System.out.println("Color: " + car2.color); System.out.println("Year: " + car2.year); } }
-
Introducing parametrized methods inside the car class
class Car { // properties String brand, color; int year; // behaviours void startEngine() { System.out.println("Engine started"); } void drive() { System.out.println("Car is driving"); } void setDetails(String brandName, String colorName, int manufactureYear) { brand = brandName; color = colorName; year = manufactureYear; } void printDetails() { System.out.println("Car details: "); System.out.println("---------------"); System.out.println("Brand: " + brand); System.out.println("Color: " + color); System.out.println("Year: " + year); System.out.println(); } } class Test { public static void main(String[] args) { // create Car objets Car car1 = new Car(); Car car2 = new Car(); // set object properties car1.setDetails("Toyota", "red", 2016); car2.setDetails("Honda", "blue", 2019); // priniting cars details car1.printDetails(); car2.printDetails(); // Invoke object behaviors car1.startEngine(); car1.drive(); car2.startEngine(); car2.drive(); } }
-
Constructor: Constructor is a special type of method which can help us to initialize object. Constructor does not need to be called. The constructor has the same name as the class it belongs to. It does not have a return type, not even void. types: default and parametrized constructor
- Constructor example
class Car { // properties String brand, color; int year; // constructor - same name as the class it belongs to and no return type not even void Car(String brand, String color, int year) { this.brand = brand; this.color = color; this.year = year; } // behaviours void startEngine() { System.out.println("Engine started"); } void drive() { System.out.println("Car is driving"); } void printDetails() { System.out.println("Car details: "); System.out.println("---------------"); System.out.println("Brand: " + brand); System.out.println("Color: " + color); System.out.println("Year: " + year); System.out.println(); } } class Test { public static void main(String[] args) { // create Car objets Car car1 = new Car("Toyota", "red", 2016); Car car2 = new Car("Honda", "blue", 2019); // priniting cars details car1.printDetails(); car2.printDetails(); // Invoke object behaviors car1.startEngine(); car1.drive(); car2.startEngine(); car2.drive(); } }
- Overloading Constructors where we have constructors with same name but the parameter numbers are different.
class Car { // properties String brand, color; int year; // constructor - same name as the class it belongs to and no return type not even void Car(String brand, String color, int year) { this.brand = brand; this.color = color; this.year = year; } // constructor overloading: same name different parameters Car(String brand, String color) { this.brand = brand; this.color = color; } Car() { System.out.println("Default constructor"); } // behaviours void startEngine() { System.out.println("Engine started"); } void drive() { System.out.println("Car is driving"); } void printDetails() { System.out.println("Car details: "); System.out.println("---------------"); System.out.println("Brand: " + brand); System.out.println("Color: " + color); System.out.println("Year: " + year); System.out.println(); } } class Test { public static void main(String[] args) { // create Car objets Car car1 = new Car("Toyota", "red", 2016); Car car2 = new Car("Honda", "blue", 2019); Car car3 = new Car("Peugeot", "black"); Car car4 = new Car(); // priniting cars details car1.printDetails(); car2.printDetails(); // Invoke object behaviors car1.startEngine(); car1.drive(); car2.startEngine(); car2.drive(); } }
-
Differences between the constructor and method
- static keyword is used for memory management. It saves memory by sharing variables with different objects. It's important to note that static members belong to the class and are not specific to any object. They can be accessed using the class name followed by the member name, such as
ClassName.staticMember
.
-
Static Variables:
-
Static variables, also known as class variables, are shared among all instances of a class. They are declared using the
static
keyword and have a single copy that is shared by all objects of the class. -
Example:
public class Counter { static int count; // Static variable public Counter() { count++; // Increment count in the constructor } }
-
-
Static Block:
-
A static block is a static initializer block that is used to initialize static variables or perform any other one-time initialization tasks for the class.
-
It is executed only once when the class is loaded into memory, before any object of that class is created or any static method is called. static block is called even before main method.
-
Example:
public class StaticBlockExample { static int id; static String name; static { // Static block id = 101; name = "Anisul"; System.out.println("Static block executed!"); } static void display(){ System.out.println("Id: "+id); System.out.println("Name: "+name); } public static void main(String[] args) { System.out.println("Main method executed!"); StaticBlockExample.display(); } }
-
-
Static Methods:
-
Static methods are associated with the class itself, rather than with individual objects of the class. They are declared using the
static
keyword and can be called directly using the class name, without creating an object. The main method is the most common example of static method. -
Static methods cannot access instance variables or call instance methods directly, as they are not associated with any specific object.
-
Example:
public class StaticMethod { public int add(int a, int b) { return a + b; } public static int multiply(int a, int b) { return a * b; } } public class Test{ public static void main(String[] args){ int result = StaticMethod.multiply(20,30); System.out.println(result); StaicMethod sm = new StaticMethod(); result = sm.add(20,30); System.out.println(result); } }
- static method can't use non static members. this and super can not be used.
public class StaticMethod { public int add(int a, int b) { return a + b; } public static int multiply(int a, int b) { int x = add(20,30); // error here return a * b; } }
-
- variable types: local (variable is decalred inside a method/constructor/block), instance variables (decalred inside class but outside the method and not decared as static) and class/static variable.
-
Encapsulation is the practice of bundling related properties and behaviors within a class and providing access to them through methods. It helps in data hiding and protects the internal state of objects. 4 types of access modifiers: private, default, protected, public.
public class Car { private String brand; private String color; private int year; // Getter methods public String getBrand() { return brand; } public String getColor() { return color; } public int getYear() { return year; } // Setter methods public void setBrand(String brand) { this.brand = brand; } public void setColor(String color) { this.color = color; } public void setYear(int year) { this.year = year; } }
-
Inheritance allows creating new classes (child classes / sub classes / dervied classes) based on existing classes (parent classes /super classes /base classes). Child classes inherit the properties and behaviors of their parent classes, enabling code reuse and creating a hierarchical structure. For method overriding and make parent child relationship we need inheritance.
public class ElectricCar extends Car { private int batteryCapacity; // Additional behavior void chargeBattery() { System.out.println("Battery is charging."); } }
- More simple inheritance example
// class Person { String name; int age; public void printDetails1() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } class Teacher extends Person { double salary; public void printDetails2() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("salary: " + salary); } } class Test { public static void main(String[] args) { Teacher t1 = new Teacher(); Teacher t2 = new Teacher(); t1.name = "Anisul Islam"; t1.age = 33; t1.salary = 4.500; t1.printDetails2(); t2.name = "Emraj Chowdhury"; t2.age = 29; t2.salary = 2.500; t2.printDetails2(); } }
- Inheriting private members is not possible but we can create public getter and setter methods to use private members of a class.
class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void printDetails1() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } class Teacher extends Person { private double salary; public void setSalary(double salary) { this.salary = salary; } public double getSalary() { return salary; } public void printDetails2() { System.out.println("Name: " + getName()); System.out.println("Age: " + getAge()); System.out.println("salary: " + getSalary()); } } class Test { public static void main(String[] args) { Person p = new Person(); Teacher t1 = new Teacher(); // instanceof operator System.out.println(p instanceof Person); System.out.println(p instanceof Teacher); t1.setName("Anisul Islam"); t1.setAge(33); t1.setSalary(4.500); t1.printDetails2(); Teacher t2 = new Teacher(); t2.setName("Anisul Islam"); t2.setAge(33); t2.setSalary(4.500); t2.printDetails2(); } }
- Types of Inheritance: Single Inheritane (A<- B), multilevel inheritance (A <- B <- C), Hierarchical Inheritance (A<-B, A<-C, A<-D multiple sub class is dervied from single subclass), Multiple Inheritance (dimand shape A<-B, A<-C, B<-D, C<-D one subclass trying to derive 2 superclasses)
-
method overriding
- method overriding is a process of declaring a method in subclass which is already present in superclass. It helps us to do code reuse.
class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void printDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } class Teacher extends Person { private double salary; public void setSalary(double salary) { this.salary = salary; } public double getSalary() { return salary; } public void printDetails() { System.out.println("Name: " + getName()); System.out.println("Age: " + getAge()); System.out.println("salary: " + getSalary()); } }
-
method overloading vs overriding
-
Can you override static method? No, cause static method bound to the class not to object.
-
Can you override java main method?: No, because main is a static method.
Overloading:
- Definition: Overloading occurs when multiple methods in the same class have the same name but different parameters (either different types or different numbers of parameters).
- Purpose: Overloading is used to provide multiple methods with the same name but different behaviors or functionalities.
- Occurrence: Overloading happens within the same class.
- Inheritance: Overloading is not related to inheritance.
- Signature: Overloaded methods must have a different method signature, which includes the method name and parameter list.
- Return Type: Overloaded methods may or may not have the same return type.
- Example:
public class Calculator { public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } }
Overriding:
- Definition: Overriding occurs when a subclass provides its own implementation of a method that is already defined in its superclass.
- Purpose: Overriding is used to modify or extend the behavior of an inherited method in a subclass.
- Occurrence: Overriding happens in a subclass that extends a superclass.
- Inheritance: Overriding is related to inheritance.
- Signature: Overridden methods must have the same method signature, including the method name, parameter list, and return type.
- Annotation: The
@Override
annotation is used to indicate that a method is intended to override a superclass method (optional but recommended). - Example:
public class Animal { public void makeSound() { System.out.println("Animal makes a sound."); } } public class Cat extends Animal { @Override public void makeSound() { System.out.println("Cat meows."); } }
In summary, overloading is about providing multiple methods with the same name but different parameters within the same class, while overriding is about providing a new implementation of an inherited method in a subclass. Overloading is determined at compile-time based on the method's signature, while overriding is determined at runtime based on the actual object type.
-
-
Why Java does not support multiple inheritance?
-
super keyword is used to access super class members such as properties, behaviours, constructors. super.variable, super.method(), super(param1,param2) for constructor. It has to be the first statement in method.
- super keyword example
class Animal { protected String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println("The animal is eating."); } } class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); // Calling the superclass constructor using super() this.breed = breed; } public void displayInfo() { System.out.println("Name: " + super.name); // Accessing the superclass variable using super super.eat(); // Invoking the superclass method using super System.out.println("Breed: " + this.breed); } } public class Main { public static void main(String[] args) { Dog dog = new Dog("Buddy", "Labrador"); dog.displayInfo(); } } // Another example class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void printDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } class Teacher extends Person { private double salary; public Teacher(String name, int age, double salary) { super(name, age); this.salary = salary; } public void setSalary(double salary) { this.salary = salary; } public double getSalary() { return salary; } public void printDetails() { super.printDetails(); System.out.println("salary: " + getSalary()); } } class Test { public static void main(String[] args) { Person p = new Person("Anisul Islam", 33); Teacher t1 = new Teacher("Anisul Islam", 33, 4.500); System.out.println(p instanceof Person); System.out.println(p instanceof Teacher); t1.setSalary(4.500); t1.printDetails(); Teacher t2 = new Teacher("Emraj", 30, 4200); t2.printDetails(); } }
-
this keyword: this keyword is a reference to the current instance of a class. It is primarily used to refer to the instance variables and methods of the current object. Here's an example to illustrate the usage of the this keyword:
- this keyword example
class Person { private String name; private int age; public Person(String name, int age) { this.name = name; // Assigning the name parameter to the instance variable using this this.age = age; // Assigning the age parameter to the instance variable using this } public void displayInfo() { System.out.println("Name: " + this.name); // Accessing the instance variable using this System.out.println("Age: " + this.age); // Accessing the instance variable using this this.sayHello(); // Invoking the instance method using this } public void sayHello() { System.out.println("Hello, I'm " + this.name); // Accessing the instance variable using this } } public class Main { public static void main(String[] args) { Person person = new Person("John", 25); person.displayInfo(); } }
-
final keyword: In Java, the
final
keyword is used to declare a variable, method, or class as unchangeable or unextendable, depending on its usage. Final variables maintain constant values, final methods cannot be overridden, and final classes cannot be subclassed. Here are examples of how thefinal
keyword can be used:-
Final Variables: In this example, the PI variable is declared as final, indicating that its value cannot be changed.
public class Circle { private final double PI = 3.14159; // Declaring a final variable public double calculateArea(double radius) { final double area = PI * radius * radius; // Using a final variable return area; } }
-
Final Methods: In the following example, the stop method is declared as final, which means it cannot be overridden by any subclass. The start method, on the other hand, can be overridden in a subclass.
public class Vehicle { public void start() { // Code to start the vehicle } public final void stop() { // Code to stop the vehicle } }
-
Final Classes: In this example, the
MathUtils
class is declared asfinal
, indicating that it cannot be extended by any other class. It prevents inheritance and ensures that the class remains unchanged.public final class MathUtils { // Class implementation }
-
-
Polymorphism (poly greek word means many and morphism greek word means form = many forms) refers to the ability of objects to take on multiple forms. It allows a child class to override or extend the behaviors of its parent class, enabling dynamic binding of methods at runtime. There are 2 types of polymorphism - Compile time (static polymorphism - method/constructor overloadin) and run time polymorphism (dynamic polymorphism - method overriding).
class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void printDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } class Teacher extends Person { private double salary; public Teacher(String name, int age, double salary) { super(name, age); this.salary = salary; } public void setSalary(double salary) { this.salary = salary; } public double getSalary() { return salary; } @Override public void printDetails() { super.printDetails(); System.out.println("salary: " + getSalary()); } } class Student extends Person { double gpa; Student(String name, int age, double gpa) { super(name, age); this.gpa = gpa; } @Override public void printDetails() { super.printDetails(); System.out.println("GPA: " + gpa); } } class Test { public static void main(String[] args) { Person p = new Person("Anisul Islam", 33); p.printDetails(); // super class object is used here as reference variable and its taking // different forms based on the object that we are assigning p = new Teacher("Anisul Islam", 33, 4.500); p.printDetails(); p = new Student("Anisul Islam", 33, 3.5); p.printDetails(); // Teacher t = new Teacher("Anisul Islam", 33, 4.500); // Student s = new Student("Anisul Islam", 33, 3.5); } }
- Another example of polymorphism
class Shape { double dim1, dim2; Shape(double dim1, double dim2) { this.dim1 = dim1; this.dim2 = dim2; } double area() { return 0; } } class Rectangle extends Shape { Rectangle(double dim1, double dim2) { super(dim1, dim2); } double area() { return dim1 * dim2; } } class Triangle extends Shape { Triangle(double dim1, double dim2) { super(dim1, dim2); } double area() { return 0.5 * dim1 * dim2; } } class Test { public static void main(String[] args) { Shape s = new Shape(0, 0); System.out.println("Shape Area: " + s.area()); s = new Rectangle(10, 20); System.out.println("Rectangle Area: " + s.area()); s = new Triangle(10, 20); System.out.println("Triangle Area: " + s.area()); } }
- Abstraction focuses on hiding the implementation details of a class and providing a simplified interface for interacting with objects. Abstract classes and interfaces are used to achieve abstraction.
public abstract class Vehicle {
// Abstract method
abstract void startEngine();
// Concrete method
void stopEngine() {
System.out.println("Engine stopped!");
}
}
- interface