More about Platform Independence
JDK
JRE
JVM
Compile Time
More on JVM
In float and long we have used f an dl. it denotes that the number in the variable is float or long type. If we don not use this java consider float value as double and long value as int.
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
}
int number = 3;
if (number % 2 == 0) {
System.out.println("Number is even");
} else {
System.out.println("Number is odd");
}
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Good");
} else if (score >= 70) {
System.out.println("Average");
} else {
System.out.println("Needs improvement");
}
int dayOfWeek = 4;
switch (dayOfWeek) {
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("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
Enhanced Switch ↓
int dayOfWeek = 4;
switch (dayOfWeek) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
case 6 -> System.out.println("Saturday");
case 7 -> System.out.println("Sunday");
default -> System.out.println("Invalid day");
}
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
int i = 0;
do {
System.out.println("Value of i: " + i);
i++;
} while (i < 5);
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
int[] numbers = { 1, 2, 3, 4, 5 };
for (int num : numbers) {
System.out.println(num);
}
Source Code in Java
However, there are some rules:
javac Main.java
javac Main.java
java Main
public class Test{
public static void main(String[] args){
System.out.println("Hello World");
}
}
Comments are something which is written in source code but ignored by the compiler.
// This is a single line comment
/* This is a
Multi line comment
*/
// import java.util.*; // This will import all classes although we require only scanner class so, we should import only that
import java.util.Scanner;
class Test {
public static void main(String args[]) {
int a;
int b;
int c;
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number : ");
a = input.nextInt();
input.nextLine();
System.out.println("Enter the a second number : ");
b = input.nextInt();
System.out.println("Enter the a third number : ");
c = input.nextInt();
input.close(); // after usage on Scanner object we should close it.
// displaying data :
System.out.println("a is = " + a + ", b = " + b + " and c = " + c);
}
}
Output ↓
a is = 1, b = 13 and c = 44
We have Scanner class available in java.util package to take input
//syntax
import java.util.Scanner;
public class Main{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
}
}
int input → nextInt() is a function used to take input of int.
Scanner input = new Scanner(System.in);
int rollno = input.nextInt();
float input → nextFloat() is a function used to take input of float.
Scanner input = new Scanner(System.in);
float marks = input.nextFLoat();
string input →
Two ways to take string input
// 1. using next() methods - It will take one word input till a space occurs
Scanner input = new Scanner(System.in);
String s1 = input.next();
// 2. using nextLine() methods - It will take all string input including spaces.
Scanner input = new Scanner(System.in);
String s2 = input.nextLine();
Syntax ↓
public static void main(String[] args)
{
// Access and use command line arguments here
}
Accessing Command Line Arguments ↓
Here's a simple Java program that takes two command line arguments (numbers) and calculates their sum:
public class CommandLineArgumentsExample {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as command line arguments.");
return;
}
// Parse the command line arguments as integers
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
// Calculate and display the sum
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
}
}
Running the program:
java CommandLineArgumentsExample 10 20
The program will calculate the sum of the provided numbers and display the result.
1: Using System.out.print(): This method prints the given content without moving to the next line.
int number = 42;
System.out.print("The answer is: ");
System.out.print(number);
Output ↓
The answer is: 42
2: Using System.out.println(): This method prints the given content and moves to the next line after printing.
String message = "Hello, World!";
System.out.println(message);
System.out.println("This is a new line.");
Output ↓
Hello, World!
This is a new line.
3: Using System.out.printf(): This method allows you to format and print text with placeholders for variables.
String name = "Alice";
int age = 30;
System.out.printf("My name is %s and I am %d years old.", name, age);
Output ↓
My name is Alice and I am 30 years old.
4: Using Concatenation: You can use the + operator to concatenate strings and variables for printing.
double price = 19.99;
System.out.println("The item costs $" + price);
Output ↓
The item costs $19.99
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first no. ");
int num1 = input.nextInt();
System.out.print("Enter second no. ");
int num2 = input.nextInt();
int sum = num1+num2;
System.out.println("The sum is ="+ sum);
}
}
Consideraton: Be cautious when mixing different next*() methods, as newline characters might be left in the input buffer. Use additional nextLine() to consume them if needed.
import java.util.Scanner;
class Initial {
public int a;
public String b;
void getValue() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number : ");
a = input.nextInt();
System.out.println("Enter the a string : ");
b = input.nextLine();
input.close();
}
void display() {
System.out.println("a is = " + a + " and b = " + b);
}
}
class Test {
public static void main(String args[]) {
Initial obj = new Initial();
obj.getValue();
obj.display();
}
}
import java.util.Scanner;
class Initial {
public int a;
public String b;
void getValue() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number : ");
a = input.nextInt();
input.nextLine();
System.out.println("Enter the a string : ");
b = input.nextLine();
input.close();
}
void display() {
System.out.println("a is = " + a + " and b = " + b);
}
}
class Test {
public static void main(String args[]) {
Initial obj = new Initial();
obj.getValue();
obj.display();
}
}
Misconception about main function in java, see the following program
import java.util.Scanner;
class Test {
public int a;
public int b;
public int c;
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number : ");
a = input.nextInt();
input.nextLine();
System.out.println("Enter the a second number : ");
b = input.nextInt();
System.out.println("Enter the a third number : ");
c = input.nextInt();
input.close();
// displaying data :
System.out.println("a is = " + a + ", b = " + b + " and c = " + c);
}
}
import java.util.Scanner;
class Test {
public static int a; // *
public static int b; // *
public static int c; // *
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number : ");
a = input.nextInt();
input.nextLine();
System.out.println("Enter the second number : ");
b = input.nextInt();
System.out.println("Enter the third number : ");
c = input.nextInt();
input.close();
// displaying data :
System.out.println("a is = " + a + ", b = " + b + " and c = " + c);
}
}
import java.util.Scanner;
class Digits {
static Scanner input = new Scanner(System.in);
static int num;
public static void main(String args[]) {
System.out.println("Enter your number : ");
num = input.nextInt();
System.out.println("Number of digits = " + noOfDigits(num));
}
public static int noOfDigits(int num) {
int digits = 0;
while (num > 0) {
digits++;
num /= 10;
}
return digits;
}
}
import java.util.Scanner;
class Sum {
static Scanner input = new Scanner(System.in);
static int num;
public static void main(String args[]) {
System.out.println("Enter your number : ");
num = input.nextInt();
System.out.println("Sum of digits = " + sumOfDigits(num));
}
public static int sumOfDigits(int num) {
int sum = 0;
while (num > 0) {
sum = sum + (num % 10);
num /= 10;
}
return sum;
}
}
When one type of data is assigned to another type of variable an automatic type conversion will take place under some condition
When we convert one type of data to another type is known as type casting.
Ex :- int num = (int) (67.3455f)
While evaluating expressions the intermediate value may exceed the operands and hence the expression value will be promoted.
There are some condition for type promotion :-
byte a = 40;
byte b = 50;
byte c = 100;
int d = (a*c)/c;
System.out.println(d);
Here when a*b occurred it became 2000 which is out of the range of byte (as byte max can be 256). So, here byte is automatically promoted to int type.
public class TypePromotion {
public static void main(String[] args) {
byte b = 42;
byte c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = 0.1234;
double result = (f*b)+(i/c)+(d*s);
System.out.println((f*b)+" "+(i/c)+" "+(d*s));
System.out.println(result);
}
}
If we want to store large value into small data type
Ex : byte b = 50;
b = (byte) (b*2); // type casting int to byte.
access_modifier return_type method_name(parameter_list) {
// Method body
// Code to perform the task
// Optional return statement if return_type is not void
}
The concepts of "static" and "non-static" are fundamental in object-oriented programming, and they pertain to how members (variables and methods) of a class are associated with the class itself and instances of the class.
Remember ↠ We can't directly access these non-static members and variable in static methods because they belong to an instance of the class, not to the class itself.
public class StaticVsNonStaticExample {
// Non-static variable
int nonStaticVar = 10;
// Non-static method
void nonStaticMethod() {
System.out.println("Non-static method called.");
}
public static void main(String[] args) {
// Cannot access non-static variables or methods directly from a static context (main method)
// Uncommenting the following lines will result in a compilation error
// System.out.println(nonStaticVar); // Error: non-static variable cannot be referenced from a static context
// nonStaticMethod(); // Error: non-static method cannot be referenced from a static context
// To use non-static variables/methods, you need to create an instance of the class
StaticVsNonStaticExample instance = new StaticVsNonStaticExample();
System.out.println("Non-static variable: " + instance.nonStaticVar);
instance.nonStaticMethod();
}
}
Using both static and non static method
public class StaticAndNonStaticExample {
static int staticVar = 10; // Static variable
int nonStaticVar = 20; // Non-static variable
static void staticMethod() {
System.out.println("Static method called.");
}
void nonStaticMethod() {
System.out.println("Non-static method called.");
}
public static void main(String[] args) {
System.out.println("Static variable: " + staticVar);
staticMethod();
// Uncommenting the following lines will result in a compilation error
// System.out.println(nonStaticVar); // Error: non-static variable cannot be referenced from a static context
// nonStaticMethod(); // Error: non-static method cannot be referenced from a static context
StaticAndNonStaticExample instance = new StaticAndNonStaticExample();
System.out.println("Non-static variable: " + instance.nonStaticVar);
instance.nonStaticMethod();
}
}
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
System.out.print("Enter a number : ");
number = input.nextInt();
System.out.println("The sqare of the given number = " + squareNum(number));
input.close();
}
public static int squareNum(int num) {
return num * num;
}
}
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
System.out.print("Enter a number : ");
number = input.nextInt();
if (isPalindrome(number)) {
System.out.println("Given number is palindrome");
} else {
System.out.println("Given number is not palindrome");
}
input.close();
}
public static boolean isPalindrome(int num) {
int rev = 0;
int temp = num;
while (temp > 0) {
rev *= 10;
rev += (temp % 10);
temp /= 10;
}
if (rev == num)
return true;
return false;
}
}
Example ↓
public class StaticBlockExample {
static {
System.out.println("This is a static block.");
}
public static void main(String[] args) {
// The static block is executed before the main method.
System.out.println("Inside the main method.");
}
}
Example ↓
public class StaticVariableExample {
static int count = 0; // Static variable
public StaticVariableExample() { // This is a constructor which will automatically excute and count variable will be incremented.
count++; // Increment count for each instance created
}
public static void main(String[] args) {
StaticVariableExample obj1 = new StaticVariableExample();
StaticVariableExample obj2 = new StaticVariableExample();
// Both objects share the same 'count' variable.
System.out.println("Total instances created: " + count); // Output: 2
}
}
Example ↓
public class StaticMethodExample {
static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
int result = StaticMethodExample.multiply(5, 3); // Calling static method
System.out.println("Result: " + result); // Output: 15
}
}
Why static methods only access static members?
Static methods in Java can only access static members (variables and methods) of a class. This restriction exists because static methods belong to the class itself, not to any specific instance of the class. Here's an explanation of why static methods can only access static members:
Example code ↓
public class MyClass {
static int staticVariable = 10; // Static variable
int instanceVariable = 20; // Instance variable
static void staticMethod() {
System.out.println("Static method accessing staticVariable: " + staticVariable);
// Attempting to access instanceVariable would result in a compilation error.
// System.out.println("Static method accessing instanceVariable: " + instanceVariable); // Error
}
void instanceMethod() {
System.out.println("Instance method accessing staticVariable: " + staticVariable);
System.out.println("Instance method accessing instanceVariable: " + instanceVariable);
}
public static void main(String[] args) {
staticMethod(); // Calling a static method
MyClass myObj = new MyClass();
myObj.instanceMethod(); // Calling an instance method
}
}
In the above example, the staticMethod can access staticVariable but cannot access
instanceVariable. In contrast, the instanceMethod can access both staticVariable and
instanceVariable because it operates within the context of a specific object created from the
class.
In summary, static methods in Java can only access static members because they are
associated with the class as a whole and are not tied to any specific instance's state.
Accessing instance members from static methods would be ambiguous and is therefore not allowed.
Creating an array
Declaration of Arrays
// Form 1
type arrayname[];
// Form 2
type [] arrayname;
int number[];
float average[];
int[] counter;
float[] marks;
Creation of array
arrayname = new type[size];
Examples ↓
number = new int[5];
average = new float[10];
int number[] = new int[5];
Initialization of Arrays
arrayname[subscript] = value;
Example ↓
number[0] = 35;
number[1] = 40;
type arrayname[] = {list of values};
Example ↓
int number [] = {35, 40, 20, 57, 19};
int a[] = {1, 2, 3};
int b[];
b = a;
Array length
int aSize = a.length;
int myArray[][];
myArray = new int[3][4];
// OR
int myArray[][] = new int[3][4]; // this creates a table that can store 12 integer values, four across and three down.
int myArray[][];
myArray = new int[3][4];
// OR
int myArray[][] = new int[3][4];
int table[][] = {{0, 0, 0}, {1, 1, 1}};
class Test {
public static void main(String[] args) {
int value = 10;
int table[][] = new int[2][3];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
table[r][c] = value++;
}
}
// displaying 2D array
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
System.out.print(table[r][c] + " ");
}
System.out.println("");
}
}
}
class Test {
public static void main(String[] args) {
int value = 10;
int table1[][] = new int[2][3];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
table1[r][c] = value++;
}
}
int table2[][] = new int[2][3];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
table2[r][c] = value++;
}
}
int table3[][] = new int[2][3];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
table3[r][c] = table1[r][c] + table2[r][c];
}
}
// displaying sum of 2D array
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
System.out.print(table3[r][c] + " ");
}
System.out.println("");
}
}
}
public class AnonymousArrayExample {
public static void main(String[] args) {
int[] numbers = new int[]{10, 20, 30, 40, 50}; // normal array
// Creating and using an anonymous array for integer values
// Passing the anonymous array to a method
int sum = calculateSum(new int[]{5, 10, 15, 20});
System.out.println("Sum of numbers: " + sum);
}
// Method to calculate the sum of an array
public static int calculateSum(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
}
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
// Accessing elements
int element = jaggedArray[1][0]; // Accessing 4
Simple program to print values of jagged array ↓
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jaggedArray = {
{ 1, 2, 3 },
{ 4, 5 },
{ 6, 7, 8, 9 }
};
// Printing elements of the jagged array
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println(); // Move to the next line for the next row
}
}
}
class Test {
public static void main(String[] args) {
int arr[] = { 2, 4, 6, 8, 99, 1 };
System.out.println("Printing the array using function : ");
printArray(arr);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
class Test {
public static void main(String[] args) {
int arr1[] = { 2, 4, 6, 8, 99, 1 };
int arr2[] = { 2, 1, 2, 3, 9, 4 };
System.out.print("arr1 : ");
display(arr1);
System.out.print("arr2 : ");
display(arr2);
System.out.print("Sum of arr1 and arr2 : ");
sumTwoArray(arr1, arr2);
}
public static void sumTwoArray(int[] arr1, int[] arr2) {
int newArray[] = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
newArray[i] = arr1[i] + arr2[i];
}
display(newArray);
}
public static void display(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
}
char charArray[] = new char[4];
charArray[0] = 'J';
charArray[1] = 'a';
charArray[2] = 'v';
charArray[3] = 'a';
String firstName;
firstName = new String("Anil");
String firstName = new String("Anil");
int m = firstName.length;
String fullName = name1 + name2;
String city1 = "New" + "Delhi";
System.out.println(firstName + "Kumar");
class Test {
static String name[] = { "Madras", "Delhi", "Ahmedabad", "Calcutta", "Bombay" };
public static void main(String[] args) {
int size = name.length;
String temp = null;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (name[j].compareTo(name[i]) < 0) {
// Swap the strings
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for (int i = 0; i < size; i++) {
System.out.println(name[i]);
}
}
}
StringBuffer key methods ↓
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello");
stringBuffer.append(" World"); // Appends " World" to the buffer
stringBuffer.insert(5, ","); // Inserts a comma at index 5
stringBuffer.delete(5, 7); // Removes characters from index 5 to 7
stringBuffer.replace(0, 5, "Hi"); // Replaces characters from index 0 to 5 with "Hi"
String finalString = stringBuffer.toString(); // Converts StringBuffer to String
System.out.println(finalString); // Output: "Hi World"
}
}
// WAP to state the difference between mutable and immutable string
class Test {
public static void main(String[] args) {
String str1 = new String("Hello");
str1.concat(" World");
// str1 = str1.concat(" world"); // this will work
System.out.println(str1); // Hello was printed although we concatenated " World" that means it is
// immutable
StringBuffer str2 = new StringBuffer("Hello");
str2.append(" World");
System.out.println(str2); // Hello World is printed
}
}
In the above program:
Integer num = 10; // Autoboxing int to Integer
Double price = 4.99; // Autoboxing double to Double
Integer num = 15;
int value = num; // Unboxing Integer to int
Example ↓
public class AutoboxingUnboxingExample {
public static void main(String[] args) {
// Autoboxing: Converting int to Integer
int primitiveInt = 42;
Integer wrappedInt = primitiveInt; // Autoboxing
System.out.println("Autoboxing:");
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
// Unboxing: Converting Integer to int
Integer anotherWrappedInt = new Integer(88);
int anotherPrimitiveInt = anotherWrappedInt; // Unboxing
System.out.println("\nUnboxing:");
System.out.println("Wrapped Integer: " + anotherWrappedInt);
System.out.println("Primitive int: " + anotherPrimitiveInt);
}
}
Syntax ↓
final int A = 10;
// usually we use upper-case letter with final keyword (not a rule)
public class Test {
public static void main(String[] args) {
final int MAX_VALUE = 100; // Declaring a constant using the "final" keyword
// MAX_VALUE = 200; // This line would result in a compilation error
System.out.println("The maximum value is: " + MAX_VALUE);
}
}
Syntax ↓
final void m1()
{
// body
}
Program example ↓
class Parent {
final void display() {
System.out.println("This is the parent's display method.");
}
}
class Child extends Parent {
// Attempting to override the final method will result in a compilation error
// void display() {
// System.out.println("This is the child's display method.");
// }
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
parent.display(); // Calls the parent's display method
Child child = new Child();
child.display(); // Calls the parent's display method even though Child attempted to override it
}
}
class Shape {
final void draw() {
System.out.println("Drawing a generic shape.");
}
}
class Circle extends Shape {
// Attempting to override a final method will result in a compilation error
// void draw() {
// System.out.println("Drawing a circle.");
// }
}
class Square extends Shape {
// Attempting to override the final method will result in a compilation error
// void draw() {
// System.out.println("Drawing a square.");
// }
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Shape();
shape1.draw(); // Calls the draw() method from Shape
Circle circle = new Circle();
circle.draw(); // Calls the draw() method from Shape (not overridden in Circle)
Shape shape2 = new Circle();
shape2.draw(); // Calls the draw() method from Shape (not overridden in Circle)
Square square = new Square();
square.draw(); // Calls the draw() method from Shape (not overridden in Square)
}
}
Syntax ↓
final class A
{
// body
}
Built-in Java Classes and 'final':
It's important to note that while final classes provide benefits in certain scenarios, they also impose limitations. You need to carefully consider whether a class should be marked as final, as it restricts its extensibility. In many cases, designing classes for inheritance (by not marking them final) is more flexible and allows for easier future expansion.
// Define a final class
final class MyFinalClass {
// Fields and methods can be defined here
public void displayMessage() {
System.out.println("This is a final class.");
}
}
// This class is trying to extend a final class, which will result in a compilation error.
// class SubclassOfFinalClass extends MyFinalClass {}
public class Main {
public static void main(String[] args) {
// Create an instance of the final class
MyFinalClass finalObject = new MyFinalClass();
// Call a method on the final class
finalObject.displayMessage();
}
}
A constructor is a special method used to initialize an object in Java. Every class in Java has a constructor, either implicitly or explicitly defined.
If we do not declare a constructor in a class, the Java Virtual Machine (JVM) automatically generates a default constructor for that class. This default constructor is known as the default constructor.
A constructor in Java has the same name as the class in which it is declared. Constructors must have no explicit return type. They cannot be declared as abstract, static, final, or synchronized. These modifiers are not allowed for constructors.
class ClassName (parameter-list) {
// code-statements
}
ClassName is the name of the class, and the constructor name is the same as the class name. The parameter-list is optional because constructors can be either parameterized or non-parameterized.
Constructor Example:
class Car {
String name;
String model;
Car() // Constructor
{
name = "";
model = "";
}
}
Java supports two types of constructors:
// Each time a new object is created, at least one constructor will be invoked.
Car c1 = new Car(); // Default constructor invoked.
Car c2 = new Car(name); // Parameterized constructor invoked.
Constructors play a fundamental role in object initialization in Java, allowing you to set initial values for an object's properties when it is created.
public class MyClass {
int myValue;
// Default constructor (no parameters)
public MyClass() {
myValue = 0;
}
public static void main(String[] args) {
MyClass obj = new MyClass(); // Using the default constructor
System.out.println("obj.myValue: " + obj.myValue); // Output: 0
}
}
class Cricketer {
String name;
String team;
int age;
Cricketer() {
name = "";
team = "";
age = 0;
}
Cricketer(String n, String t, int a) {
name = n;
team = t;
age = a;
}
Cricketer(Cricketer ckt) {
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString() {
// Default constructor.
// Constructor overloaded.
// Constructor similar to copy constructor of C++
return "This is " + name + " of " + team;
}
}
public class Test {
public static void main(String[] args) {
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("Sachin", "India", 32);
Cricketer c3 = new Cricketer(c2);
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team = "India";
c1.age = 32;
System.out.println(c1);
}
}
public class MyClass {
private int value;
// Constructor
public MyClass(int value) {
this.value = value;
}
// Copy Constructor
public MyClass(MyClass other) {
this.value = other.value;
}
public int getValue() {
return value;
}
public static void main(String[] args) {
MyClass originalObject = new MyClass(42);
MyClass copyObject = new MyClass(originalObject);
System.out.println("Original Object Value: " + originalObject.getValue());
System.out.println("Copy Object Value: " + copyObject.getValue());
}
}
public
: The element is accessible from anywhere, both within and outside the
package.protected
: The element is accessible within its own package and by subclasses, even
if
they are in a different package.default (package-private)
: The element is accessible only within its own package
(when no access modifier is specified).private
: The element is accessible only within its own class.
public class MyClass {
public int publicVar; // Accessible from anywhere
protected int protectedVar; // Accessible within the same package and by subclasses
int defaultVar; // Accessible only within the same package (default access)
private int privateVar; // Accessible only within the same class
public void publicMethod() {
// Public method code
}
protected void protectedMethod() {
// Protected method code
}
void defaultMethod() {
// Default method code
}
private void privateMethod() {
// Private method code
}
}
class Parent {
public void p1() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1() {
System.out.println("Child method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.c1(); // Method of Child class
cobj.p1(); // Method of Parent class
}
}
class Vehicle {
// Variable defined
String vehicleType;
}
public class Car extends Vehicle {
String modelType;
public void showDetail() {
vehicleType = "Car"; // Accessing Vehicle class member variable
modelType = "Sports";
System.out.println(modelType + " " + vehicleType);
}
public static void main(String[] args) {
Car car = new Car();
car.showDetail();
}
}
class A
{
int a = 10;
void show()
{
System.out.println("a = "+a);
}
}
public class B extends A
{
public static void main(String[] args)
{
B b = new B();
b.show();
}
}
For example a class C extends to class B that also extends to class A and all the data members an methods of class A and B are now accessible in class C.
class A
{
int a = 10;
void show()
{
System.out.println("a = "+a);
}
}
class B extends A
{
int b = 10;
void showB()
{
System.out.println("b = "+b);
}
}
public class C extends B
{
public static void main(String[] args)
{
C c = new C();
c.show();
c.showB();
}
}
class A
{
int a = 10;
void show()
{
System.out.println("a = "+a);
}
}
class B extends A
{
int b = 10;
void showB()
{
System.out.println("b = "+b);
}
}
public class C extends A
{
public static void main(String[] args)
{
C c = new C();
c.show();
B b = new B();
b.show();
}
}
Java does not support multiple inheritance through classes, but Interfaces offer a way to achieve it.
The "implements" keyword is used to inherit an interface's properties and methods.
An interface is a collection of abstract methods, meaning they have no implementation details.
In a class that inherits an interface, you must provide concrete implementations for all the methods declared in the interface.
// Define an interface for a printable object
interface Printable {
void print();
}
// Define another interface for a displayable object
interface Displayable {
void display();
}
// Create a class that implements both interfaces
class MyObject implements Printable, Displayable {
private String data;
public MyObject(String data) {
this.data = data;
}
// Implement the print() method from the Printable interface
public void print() {
System.out.println("Printing: " + data);
}
// Implement the display() method from the Displayable interface
public void display() {
System.out.println("Displaying: " + data);
}
}
public class Main {
public static void main(String[] args) {
MyObject myObj = new MyObject("Hello, World!");
// Call methods from both interfaces
myObj.print();
myObj.display();
}
}
Interfaces also serve the purpose of defining a standard for method names and signatures, ensuring that classes implementing the interface adhere to a consistent method structure.
Some important points for interface ↓
interface MyInterface {
void method1();
int method2(String input);
}
class MyClass implements MyInterface {
public void method1() {
// Implementation for method1
}
public int method2(String input) {
// Implementation for method2
return input.length;
}
}
class MyOtherClass implements Interface1, Interface2 {
// Implement methods from Interface1 and Interface2
}
Purpose of Interfaces:
Example ↓
// Define an interface
interface MyInterface {
void doSomething();
}
// Implement the interface in a class
class MyClass implements MyInterface {
public void doSomething() {
System.out.println("Doing something in MyClass");
}
}
public class Main {
public static void main(String[] args) {
MyInterface myObject = new MyClass();
myObject.doSomething();
}
}
Programs
// Define the Animal interface
interface Animal {
void bark();
}
// Implement the Animal interface in the Dog class
class Dog implements Animal {
@Override
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
// Create a Dog object
Dog myDog = new Dog();
// Call the bark method of the Dog object
myDog.bark();
}
}
// Define the Account interface
interface Account {
void deposit(double amount);
void withdraw(double amount);
void displayBalance();
}
// Implement the SavingsAccount class
class SavingsAccount implements Account {
private double balance;
public SavingsAccount(double initialBalance) {
this.balance = initialBalance;
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds in Savings Account.");
}
}
@Override
public void displayBalance() {
System.out.println("Savings Account Balance: " + balance);
}
}
// Implement the CurrentAccount class
class CurrentAccount implements Account {
private double balance;
public CurrentAccount(double initialBalance) {
this.balance = initialBalance;
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds in Current Account.");
}
}
@Override
public void displayBalance() {
System.out.println("Current Account Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
// Create SavingsAccount and CurrentAccount objects
SavingsAccount savingsAccount = new SavingsAccount(1000.0);
CurrentAccount currentAccount = new CurrentAccount(2000.0);
// Perform transactions and display balances
savingsAccount.deposit(500.0);
currentAccount.withdraw(100.0);
savingsAccount.displayBalance();
currentAccount.displayBalance();
}
}
abstract class A
{
// code
}
abstract class Animal
{
}
class Dog extends Animal
{
}
class Demo
{
public static void main(String[] args)
{
Animal r = new Dog(); // reference
}
}
An abstract method is a method declared in an abstract class but does not have an implementation in the abstract class itself. Instead, its implementation is provided by concrete (non-abstract) subclasses that inherit from the abstract class.
Abstract methods are declared using the abstract
keyword and have no method body. They serve
as placeholders for methods that must be implemented by any concrete subclass. Abstract methods define a
contract that concrete subclasses must adhere to, ensuring that specific behavior is implemented
consistently across all subclasses.
Here's an example of an abstract class with an abstract method:
abstract class Shape
{
abstract void draw(); // Abstract method without implementation
}
Any concrete subclass of Shape must provide an implementation for the draw method. This enforces a specific behavior for drawing shapes while allowing each shape type to implement it differently.
Abstract classes are used in Java for several reasons:
// Abstract class
abstract class Shape {
// Abstract method without implementation
abstract void draw();
}
// Concrete subclass 1
class Circle extends Shape {
// Implementation of the abstract method
void draw() {
System.out.println("Drawing a Circle");
}
}
// Concrete subclass 2
class Rectangle extends Shape {
// Implementation of the abstract method
void draw() {
System.out.println("Drawing a Rectangle");
}
}
public class Main {
public static void main(String[] args) {
// Create objects of concrete subclasses
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// Call the draw method on both objects
circle.draw();
rectangle.draw();
}
}
Example ↓
class Calculate {
void sum(int a, int b) {
System.out.println("sum is " + (a + b));
}
void sum(float a, float b) {
System.out.println("sum is " + (a + b));
}
public static void main(String[] args) {
Calculate cal = new Calculate();
cal.sum(8, 5); // sum(int a, int b) is called.
cal.sum(4.6f, 3.8f); // sum(float a, float b) is called.
}
}
class Demo {
void multiply(int l, int b) {
System.out.println("Result is " + (l * b));
}
void multiply(int l, int b, int h) {
System.out.println("Result is " + (l * b * h));
}
public static void main(String[] args) {
Demo ar = new Demo();
ar.multiply(8, 5); // multiply(int l, int b) is called.
ar.multiply(4, 6, 2); // multiply(int l, int b, int h) is called.
}
}
Example ↓
public class MethodDemo10 {
public static void main(int args) {
System.out.println("Main Method with int argument Executing");
System.out.println(args);
}
public static void main(char args) {
System.out.println("Main Method with char argument Executing");
System.out.println(args);
}
public static void main(Double[] args) {
System.out.println("Main Method with Double Executing");
System.out.println(args);
}
public static void main(String[] args) {
System.out.println("Original main Executing");
MethodDemo10.main(12);
MethodDemo10.main('c');
MethodDemo10.main(1236);
}
}
Below, we have a simple code example with one parent class and one child class in which the child class will override a method provided by the parent class. ↓
class Animal {
public void eat() {
System.out.println("Eat all edibles");
}
}
class Dog extends Animal {
public void eat() { // eat() method overridden by Dog class
System.out.println("Dog likes to eat meat");
}
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}
class Animal {
public void eat() {
System.out.println("Eat all edibles");
}
}
class Dog extends Animal {
protected void eat() { // Error
System.out.println("Dog likes to eat meat");
}
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}
Let's first understand the most common use of the `this` keyword, which is to differentiate between local and instance variables in a class.
Example:
class Demo {
double width, height, depth;
Demo(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10, 20, 30);
System.out.println("width = " + d.width);
System.out.println("height = " + d.height);
System.out.println("depth = " + d.depth);
}
}
In this example, `this` is used to initialize the members of the current object. For example, `this.width` refers to the variable of the current object, while `width` alone refers to the parameter received in the constructor, which is the argument passed when calling the constructor.
Calling a Constructor using the `this` Keyword:
We can call a constructor from another function inside the class by using the `this` keyword.
Example:
class Demo {
Demo() {
// Calling the constructor
this("ducatindia");
}
Demo(String str) {
System.out.println(str);
}
public static void main(String[] args) {
Demo d = new Demo();
}
}
Accessing a Method using the `this` Keyword:
Another use of the `this` keyword is to access methods. While you can access methods using object references, using `this` allows you to use the implicit object provided by Java.
Example:
class Demo {
public void getName() {
System.out.println("ducatindia");
}
public void display() {
this.getName();
}
public static void main(String[] args) {
Demo d = new Demo();
d.display();
}
}
Reference ↓