Java

Java

  • Mahalakshmi
    Teacher
    Mahalakshmi
  • Category
    Nellie Hodkiewicz
  • Review
    • (20 Reviws)
Courses
Course Summery

Java Fundamentals

Requrements

Java Lecture Started

                                                   JAVA

 

Introduction:

  • Java is a High level, Object Oriented Programming language.
  • Developed by Sun Microsystems, Now Owned by Oracle Corporation.
  • First released in 1995 and has since become one of the most popular Programming Language.
  • It is both compiler and interpreted.
  • Widely used for building Web Applications, Mobile Apps, Desktop Applications, and more.
  • Offers a rich set of Libraries and Frameworks.

Compilation Flow of Java:

          Writing Code: You write your Java code in a text editor or an Integrated Development Environment (IDE).

Compilation: You compile your Java code using the Java compiler (javac). The compiler checks for syntax errors and generates bytecode files (.class files) for each class in your code.

Bytecode Generation: The bytecode files contain instructions that the Java Virtual Machine (JVM) can understand. This bytecode is platform-independent, meaning it can run on any device or platform with a JVM.

Execution: The JVM loads and executes the bytecode files. It translates the bytecode into machine code specific to the underlying hardware, allowing your Java program to run.

 

 

 

 

 

 

Features Of Java:

 

 

Application of Java:

Keyword:

In Java, a keyword is a reserved word that has a predefined meaning and cannot be used for any other purpose, such as naming variables or methods.

Each keyword will be having some specific tasks.

Types of Java Keywords:

abstract

assert

boolean

break

byte

case

catch

class

char

continue

const

double

default

do

extends

enum

finally

for

false

float

goto

import

int

if

interface

instanceof

implements

long

new

native

null

private

protected

package

public

short

static

strictfp

synchronized

switch

super

return

try

transient

throws

this

true

throw

volatile

Void

while

 

 

 

Hello world! Program:

Public class Simple{

Public static void main(String args[]){

System.out.println(“Hello world!”);

}

}

Output:

Hello world!

 

Variables:

          In java, a variable is a named storage location that holds a value while the java program is executed.

          Variables in Java must be declared before they are used. When declaring a variable, you specify its type and name.

                     Example: int value;

Naming Rules:

  • Variable names must begin with a letter (A-Z or a-z), underscore (_), or dollar sign ($).
  • After the first character, variable names can also include digits (0-9).
  • Variable names cannot contain spaces or special characters (except underscore or dollar sign).
  • Variable names are case-sensitive.

         

          There are three types of variables in java.

Local: Local Variables are declared within a Method.They are only accessible within the scope in which they are declared.

Example:

public class Vari{

public static void main(String[] args) {

int Number = 26;

System.out.println(“The Value Of Number is:” + Number);

}

Output:26

Instance  Variable:Instance variables are variables declared within a class, holding unique data for each object instance; they define the state of individual objects in object-oriented programming.

Example:

public class Vari{

int Number1=30;

public static void main(String[] args) {

int Number = 26;

Vari Obj = new Vari();

System.out.println (“The Value Of Number1 is:” + Obj.Number1);

}

Output:30

Static Variable:A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.

Example:

public class Vari{

static int Number1=30;

public static void main(String[] args) {

int Number = 26;

System.out.println (“The Value Of Number1 is:” + Number1);

}

Output: 30

 

 

 

Data Type:

          Data types are used to declare variables and specify the type of data that the variable can hold.

          Data types are classified into two types.

  1. Primitive Data type.
  2. Non-Primitive Data type.

Primitive Data type

Non-Primitive Datatype

Primitive Data type stores the data of only one type.

Non-Primitive Data type stores the data of more than one type.

It Starts with Lowercase

It starts with Uppercase.

Ex: int, char

Ex: String, Array

 

Size of  Primitive Data types:

Data Type

Default
Size

Values

Example

Size

Boolean

false

true, false

boolean one=false;

1 bit

Char

\u0000

‘A’

char letr=’A’

2 byte

byte

0

-128 to 127

byte val=-50;

1 byte

short

0

-32 k to 32 k

short val1=-34;

2 byte

int

0

-2 B to 2 B

int val2=9000;

4 byte

long

0

Above 2 B

long val3=8923438 L

8 byte

float

0.0

1.0998 f

float val4=1.987f

4 byte

double

0

2.334 d

double val5=0.9834 d

8 byte

 

 

Type Casting:
         
typecasting refers to the process of converting one data type into another.Typecating are classified into two types, they are implicit and explicit.

Implicit Type Casting:

          Implicit typecasting occurs automatically when the destination data type can hold all possible values of the source data type. For example, converting an integer to a floating-point number.

          It Converts a smaller type to larger type size.

Priorities:

byteàshortàcharàintàlongàfloatàdouble

Int numInt = 10;

Double numDouble = numInt; // Implicit typecasting from int to double

Explicit Type Casting:
         
Explicit typecasting is performed manually by the programmer and is required when the destination data type cannot hold all possible values of the source data type. This conversion may result in loss of data. For example, converting a double to an int.

          It Converts a larger type to smaller type size.

Priorities:

double à float à long àintà char à short à byte

double numDouble = 10.5;

int numInt = (int) numDouble; // Explicit typecasting from double to int

 

 

 

 

 

 

 

 

Scanner:

          A scanner is used to obtain values from the user, and it is found in the java.util package.

Input Types:

Types

Definition

nextBoolean()

Obtains a Boolean Values from the User.

nextByte()

Obtains a Byte Values from the User.

nextDouble()

Obtains a Double Values from the User

nextFloat()

Obtains a Float Values from the User

nextInt()

Obtains a Int Values from the User

nextLine()

Obtains a String Values from the User

nextLong()

Obtains a Long Values from the User

nextShort()

Obtains a Short Values from the User

 

 

import.java.util.Scanner ;// Import the Scanner class

publicclass Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);// Create a Scanner object

System.out.println("Enter username");

String userName = myObj.nextLine();// Read user input

System.out.println("Username is: " + userName);  // Output user input

  }

}

Example:

Output:

 

 

Operators:

          In Java, operators are symbols that perform operations on operands. Operands can be variables, values, or expressions.

Types of Operators:

Operators

Precedence

Arithmetic

*, /, %, +, -

Unary

expr ++, ++expr, --expr, expr--,~,!

Shift

>>, <<, >>>

Relational

<, >, <=, >=, !=, ==

Bitwise

And (&), inclusive OR (^), Excusive Or (|)

Logical

Logical And (&&), Logical OR (||)

Ternary

?, :

Assignment

=, +=,-=,*=,/=,%=,etc.

 

Arithmetic Operator:

          arithmetic operators are used to perform mathematical operations on numeric data types, including addition(+),  subtraction (-),  Multiplication (*), division (/), modulo(%) operation.

 

TASK:Write a Java program to perform the following arithmetic operation.

  1. D=A + C – A * (A + B) /(C-B);                      (A=15    B=22   C=30 )
  2. E = (A * B) / (C + A) - (B - C) * A;                 (A=6    B=12    C=3)
  3. F = (A^2 + B^2) / (C - A) + (B * C) – A          (A=4    B=3     C=5)
  4. G = (A * B) + (C / A) - (B % C)                       (A=7    B=14   C=6)

 

Logical Operator:

Logical And (&&):
         
The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true.If both condition are true it returns TRUE; Otherwise, it returns FALSE.

Example:

a=50;b=30

Out= (a>b && a==b) àFalse

Out= (a!= b && a>b) àTrue

Logical Or (||):

          The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false.If either condition is true, it returns TRUE; otherwise, it returns FALSE.

Example:

a=50;b=30

Out= (a>b && a==b) àTrue

Out= (a!= b && a>b) àTrue

Out= (a==b && a<b) àFalse

TASK:Write a Java program to perform the following Logical operation.

Val1 = 80; Val2 = 40;

  1. A = (Val1 * Val2) % (Val1 + Val2) == 0 && Val1 / Val2 >= 2
  2. B = (Val2 * Val1) > (Val1 + Val2) || (Val1 - Val2) < 0
  3. C = (Val2 % Val1) != 0 && (Val1 % Val2) == 0
  4. D = (Val1 / Val2) <= 2 || (Val1 % Val2) != 0
  5. E= Val1 * Val2 == Val1 + Val2 || Val1 - Val2 >= 0
  6. F = Val2 % Val1 != 0 || Val1 % Val2 == 0
  7. G = Val1 / Val2 > 2 && Val1 % Val2 == 0
  8. H = Val1 * Val2 <= Val1 + Val2 && Val2 - Val1 < 0
  9. I = Val1 / Val2 <= 2 && Val1 % Val2 != 0
  10. J = Val1 - Val2 < 0 || Val2 * Val1 < Val1 + Val2

 

Assignment Operator:

          An assignment operator is used to assign a value to a variable.

a=10;b=5;

Operator

Example

=

C=a;

+=

a+=b  àa=a+b

-=

b-=a;  àb=b-a

*=

a*=a;  àa=a*a;

/=

a/=b;  à  a=a/b;

%=

b%=a;àb=b%a;

 

TASK: Write a Java program to perform the following Assignment operation.

x=10; y=5;

  1. Add 3 to x using the addition assignment operator (+=).
  2. Subtract 2 from y using the subtraction assignment operator (-=).
  3. Multiply x by 4 using the multiplication assignment operator (*=).
  4. Divide y by 2 using the division assignment operator (/=).
  5. Apply the modulus operator to x with 5 using the modulus assignment operator (%=).

 

 

Relational Operator:

          Relational operators are used to compare two values and determine the relationship between them. These operators return a boolean value (true or false) based on whether the comparison is true or false.

x=50; y=28

Operation

Example

Output

==

Z= x == x

True

!=

Z= x!=x

False

<

Z= x<y

False

>

Z= x>y

True

>=

Z= x>=x

True

<=

Z= x<=y

False

 

TASK:Write a Java program to perform the following Relational operation.

num1=100; num2= 150

  1. num2<=num1+num2/2;
  2. num1<=num2;
  3. num1!=num1
  4. num2+num1*3<=num1+num2/2*2
  5. num1 < num2 / 2
  6. num1 + num2-num1 == num2
  7. num1 * num2 < num2 * num2
  8. num2 + num1 <= num1 + num2 / 2 * 2

 

 

Unary Operator:

          A unary operator is an operator that operates on a single operand. This means it performs an operation with only one operand. Which includes postfix (a++)and prefix(++a) increment, postfix(a--)  and prefix(--a)  decrement, Logical Complement (!) and Bitwise Complement(~).

A=30; b=false

Operators

Example

A++

30++ à30;

++A

++30 à32;

A--

30--   à32;

--A

--30   à30;

!

! b     à true

~

~30   à -29;

 

TASK:Write a Java program to perform the following Unary operation.

a=18;  b=16;  a1=-10; b1=true;

  1. C=(a++ + a++)
  2. D=(a++ + ++b)
  3. E=(++a + ++b)
  4. F=(~b)
  5. G=(~a1)
  6. H=(!b1)
  7. I=a + b*(a1++ -a)
  8. J=a /b + d – e++ *a*b+c*c;    (a=10,b=2,c=18,d=31,e=21)
  9. K=a++ / b-- *e +c--;
  10. L=a – b-- * c++ *++d /e;

 

 

 

Bitwise Operator:

Bitwise And (&):

          The bitwise & operator always checks both conditions whether first condition is true or false.

          If both condition are true it returns TRUE; Otherwise, it returns FALSE.

Example:

A=10; B=2;

C=A>B & B<Aàtrue

C=A<B & B<Aà false

Bitwise Or (|):

          The bitwise | operator always evaluates both conditions, regardless of whether the first condition is true or false. If either condition is true, it returns TRUE; otherwise, it returns FALSE.

Example:

Num1=234 ; Num2=263

Num=Num1> Num2 | Num1 !=Num2       àtrue

Num= Num1 == Num2 | Num1 >= Num2 àfalse

TASK:Write a Java program to perform the following Bitwise operation.

Val1= 20; Val2=15

  1. A=Val1 >= Val2 & Val1 == Val2
  2. B=Val2 <= Val1 & Val1++ > Val2
  3. C=++Val2>=Val1 | Val1 != Val2
  4. D=++Val1 > Val1 | Val1==Val1
  5. E = Val1 % Val2 == 0 & Val1 / Val2 >= 2
  6. F = Val2 * Val1 > Val1 + Val2 |Val1 - Val2 < 0
  7. G = Val2 % Val1 != 0 & Val1 % Val2 == 0
  8. H = Val1 / Val2 <= 2 | Val1 % Val2 != 0
  9. C = (Val2 % Val1) != 0 && (Val1 % Val2) == 0
  10. D = (Val1 / Val2) <= 2 || (Val1 % Val2) != 0

 

 

 

Ternary Operator:

          The ternary operator (also known as the conditional operator) is a compact way to express a simple conditional expression. It's the only ternary operator in Java, and it takes three operands.

Syntax:

Boolean Expression ? valueIfTrue : valueIfFalse

Example:

int x = 10;

int y = (x > 5) ? 100 : 200;

Output: 100

TASK:

  1. int x = 10;

int y = (x > 5) ? ((x < 15) ? 100 : 200) : 300;

 

  1. Write a Java program that calculates the price of a product after applying discounts based on certain conditions. Use a ternary operator to determine the discount amount and calculate the final price accordingly.The Product Price is 60.

Here's the expression breakdown:

  • If the product price is greater than $50, apply a 10% discount.
  • If the product price is less than or equal to $50, apply a 5% discount.
  • If the product price is less than $20, apply no discount.

 

 

Shift Operator:

          In Java, shift operators are used to perform bit-level operations on integer data types (byte, short, int, long). These operators shift the bits of a value left or right. There are three types of shift operators:

Left Shift Operator (<<):

          The left shift operator shifts all bits of a value to the left by a specified number of positions.

Syntax: value <<numPositions

 

Example:int result = 5 << 2;

This will shift the binary representation of 5, which is 0000 0101, to the left by 2 positions, resulting in 0001 0100, which is 20 in decimal.

Right Shift Operator(>>):

          The right shift operator shifts all bits of a value to the right by a specified number of positions.

Syntax: value >>numPositions

 

 

If the value is positive, the most significant bit (sign bit) is shifted in from the left. If the value is negative, the sign bit is extended as well.

Example:int result = 20 >> 2;

This will shift the binary representation of 20, which is 0001 0100, to the right by 2 positions, resulting in 0000 0101, which is 5 in decimal.

Unsigned Right Shift Operator:

          The unsigned right shift operator shifts all bits of a value to the right by a specified number of positions. Unlike the right shift operator (>>), it fills the leftmost positions with zeros regardless of the sign bit.

Syntax: value >>>numPositions

 

 

Example:int result = -20 >>> 2;

This will shift the binary representation of -20, which is 1111 1111 1111 1111 1111 1111 1110 1100, to the right by 2 positions, resulting in 0011 1111 1111 1111 1111 1111 1111 1101, which is 1073741821 in decimal.

 

Control Statement:

          Control Statement are used to manage the flow of execution in a program.

Decision Making:

          Decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.

If Statement : In java, there are four types of If statements.

if:

Syntax: if(condition) {   

statement 1; //executes when condition is true  

}   

 

Example:

Output:

else:

Syntax:  if(condition) {   

statement 1; //executes when condition is true  

else{ 

statement 2; //executes when condition is false  

 

 

 

 

Example:

Output:

else if:

Syntax: if(condition 1) {   

statement 1; //executes when condition 1 is true  

else if(condition 2) { 

statement 2; //executes when condition 2 is true  

else { 

statement 2; //executes when all the conditions are false   

 

 

 

 

 

 

Example:

         

Output:

Nested if:

Syntax: if(condition 1) {   

statement 1; //executes when condition 1 is true  

if(condition 2) { 

statement 2; //executes when condition 2 is true  

else{ 

statement 2; //executes when condition 2 is false  

} 

 

Example:

Output:

TASK:

  1. Java program that calculates the factorial of Write a Java program that takes a student's score as input and calculates their grade based on the following grading scale:

A: 90-100

B: 80-89

C: 70-79

D: 60-69

F: 0-59

  1. Write a Java program that determines the price of a movie ticket based on the age of the customer and the time of the movie.

Here are the rules:

  • If the customer is 12 years old or younger, the ticket price is 50.
  • If the customer is between 13 and 59 years old (inclusive), the ticket price is 70.
  • If the customer is 60 years old or older, the ticket price is 90.
  • Additionally, there's a discount for late-night shows. If the movie starts after 8 PM, there's a Rs.20 discount on the ticket price regardless of age.
  1. Write a Java program that calculates Body Mass Index (BMI) based on the user's weight (in kilograms) and height (in meters). Additionally, classify the BMI according to the following categories:

 

Underweight: BMI less than 18.5

Normal weight: BMI 18.5 - 24.9

Overweight: BMI 25 - 29.9

Obesity: BMI 30 or greater

 

Switch:

          A switch statement in Java evaluates an expression and executes different blocks of code based on the possible values of that expression. It provides a concise way to handle multiple conditional cases within a single control structure.

Syntax:  switch (expression) {

    case value1:

        // Code block 1

        break;

    case value2:

        // Code block 2

        break;

    // More cases as needed

    default:

        // Default code block

}

The case variables can be int, short, byte, char, or enumeration.          Cases cannot be duplicate.

The default clause is optional and executes when none of the case statements match the expression's value.

The break statement, also optional, exits the switch block once a condition is met, otherwise, the control flows to the next case.

It's crucial to ensure that the case expressions match the variable's type and are constant values.

 

 

 

Example:

Output:

TASK:

  1. Write a Java program that takes an integer input representing a month (1 for January, 2 for February, etc.) and prints the number of days in that month.
  2. Write a Java program that takes a character input representing a grade (A, B, C, D, or F) and prints a message indicating the corresponding grade description.
  3. Write a Java program that takes a string input representing a day of the week (e.g., "Monday", "Tuesday", etc.) and prints a message indicating whether it's a weekday or a weekend day.

 

Loop Statement:

          In Java, a loop statement is used to execute a block of code repeatedly. There are several types of loop statements available in Java:

for:

Syntax: for (initialization; condition; iteration) {

    // code to be executed

}

 

Example:

 

 

 

Output:

While:

Syntax: while (condition) {

    // code to be executed

}

Example:

Output:

Do-while:

Syntax: do {

    // code to be executed

} while (condition);

 

Example:

Output:

TASK:

  1. Write a Java program that calculates the sum of all the numbers from 1 to 100.
  2. Write a Java program that prints all the even numbers between 1 and 50.
  3. Write a Java program that calculates the factorial of a given number.
  4. Write a Java program that prints the multiplication table of a number entered by the user using loops.
  5. Write a Java program that calculates the factorial of a number entered by the user using loops.

 

 

Jump Statement:

          Jump statements are used to transfer the control of the program to the specific statements. There are two types of Jump statements in Java.

break:

Syntax: break;

 

Example:

Output:

Continue:

Syntax: continue;

 

Example:

Output:

 

Array:

          Array is a collection of similar data type. Arrays are used to store multiple values in a single variable.

          The index of the first element is always 0, and the index of the last element is (length - 1).

          There are two types of arrays in java: Single dimensional Array and Multi Dimensional Array.

 

Single Dimensional Array:

          A single-dimensional array in Java is an array that stores elements of the same data type in a linear sequence. It is the simplest form of an array, where elements are arranged in a single row.

Syntax:

 dataType[] arrayName = new dataType[size];

 

Example:

Output:

Multi Dimensional Array:

          A multi-dimensional array in Java is an array of arrays. Unlike one-dimensional arrays which consist of a single line of elements, multi-dimensional arrays can represent data in multiple dimensions, such as rows and columns in a table or layers in a cube.

Output:

 

OOPS:

          OOPS Stands for Object Oriented Programming Language.

          OOPs in Java is a programming paradigm that revolves around the concept of "objects" which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods). The key principles of OOPs in Java are:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

Class:

          In Java, a class is a blueprint or template for creating objects. It defines the properties and behaviors(methods) that objects of that type will have. Each object created from a class is an instance of that class.

Syntax:

          Class <Class Name>{

Field;

Method;

}

Object:

          In Java, an object is a fundamental concept representing a tangible entity that exists in memory at runtime. It is an instance of a class, created using the new keyword followed by a constructor invocation. Objects encapsulate data (properties or fields) and behaviors (methods or functions) defined by their class.

Here's a brief explanation of objects in Java:

Instance: An object is an instance of a class. You can create multiple objects from the same class, and each object will have its own set of properties.

 

Properties: Objects have state, which is defined by the values of their instance variables or fields.

Behavior: Objects can perform actions or exhibit behaviors, which are defined by the methods or functions associated with their class.

Passing Objects: Objects can be passed as parameters to methods, returned from methods, stored in data structure, etc

Syntax:
public class ClassName{

Public static void main {

ClassNameObj=new ClassName();

 }

}

Encapsulation:

          This is the mechanism that binds together the data and functions that manipulate the data, and keeps both safe from outside interference and misuse. In Java, this is achieved using classes, where data (fields) and methods (functions) are encapsulated together.Encapsulation is achieved through access modifiers: public, private, and default, protected.

Public:The member is accessible from any other class.

Ex:Shirt, Destination.

Private:The member is accessible only within the same class.

Ex: ATM Pin, Mobile Password.

Default: The member is accessible only within the same package.

Ex: pet, pet name.

 

 

Inheritance:

          Inheritance is a mechanism in which one object acquires all the properties and behaviorsof a parent object. It promotes code reusability and allows the creation of hierarchical classifications. In Java, classes can inherit attributes and methods from other classes using the extends keyword.

Protected:The member is accessible within the same package and subclasses (even if they are in different packages).

Ex: Neighbours and Relativesà Job, SSLC Mark

In Java, There are Several type of Inheritance

 

Single Inheritance:( 1 Parent Class & 1 Child Class)

Single inheritance in Java refers to the capability of a class to inherit properties and behaviorsfrom only one superclass, enabling a parent-child relationship where a subclass extends exactly one superclass.

 


Parent A   

 

 


Child B
 

 

 

Syntax:

Class Parents{

}

Class Childextends Parents{

}

 

Example:

Output:

Multi level Inheritance:

          Multi-level inheritance in Java involves a chain of inheritance where a subclass extends another subclass, forming a hierarchical structure. This enables the sharing of properties and behaviours from multiple levels up the inheritance tree.

     Parent A

 

Intermediate B

 

     Child C

 

Here, Intermediate B can access Parent A and Child C; also Child C can access Intermediate B; however, Child C can’t access Parent A.

Syntax:

class Parent{

//Methods and Fields

}

class Intermediateextends Parent{

//Methods and Fields

}

class Childextends Intermediate{

//Methods and Fields

}

 

 

 

 

Example:


Output:

Multiple Inheritance:( 2 Parent Class and 1 Child Class)

In Java, multiple inheritance of classes is not supported to reduce complexity and to avoid issues such as the diamond problem. However, Java does support multiple inheritance of types through interfaces, where a class can implement multiple interfaces.

Parent A

Parent B

 

Child C

 

What is Interface?

          An interface in Java serves as a blueprint for a class, providing a way to achieve abstraction.

It consists of static constants and abstract methods, enabling multiple inheritance by allowing classes to implement multiple interfaces.

          Interfaces can only contain abstract method decalrations and constant variables; they can’t have method implementations.

Why use Java Interface?

          It is used to achieve abstraction.

          By interface, we can support the functionality of multiple inheritance.

Syntax:

class Subclass extends Superclass {

    // subclass members and methods

}

Example:
 

Output:

Hierarchical Inheritance: ( 1 Parent Class and N number of Child Class)

          Hierarchical inheritance in Java involves multiple Child Class inheriting from a single Parent Class, allowing each Chid Class to share common characteristics while also having its own unique properties and behaviours. This creates a hierarchical structure where Child Classform branches stemming from a common ancestor Parent Class.


Parent A
 

Child B

 

 

Child C

Child N

 

 

Syntax:

// Superclass

class Parent Class {

    // Parent Class members

}

 

// Child 1

class Child1 extends Parent Class {

    // Child 1 members

}

 

// Child 2

class Child2 extends Parent Class {

    // Child 2 members

}

 

// Additional Child Class can be defined similarly

 

Example:

Output:

Hybrid Inheritance:

          In Java, hybrid inheritance refers to a combination of two or more types of inheritance, such as single and multiple inheritance, multilevel and hierarchical inheritance, or single and multilevel inheritance.

Here's an example program demonstrating hybrid inheritance in Java by combining single and multilevel inheritance:

 

Example:

 

 

Output:

 

Polymorphism:

          Polymorphism means "many forms" and refers to the ability of an object to take on multiple forms. In Java, polymorphism allows objects to be treated as instances of their parent class, enabling methods to be called on objects without knowing their exact type. This is achieved through method overriding and method overloading.

Method Overloading:

          This occurs when a class has multiple methods with the same name but different parameter lists. Java determines which method to call based on the arguments provided at compile time.

Example:

 

Output:


 

Method Overriding:

          This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass has the same name, return type, and parameter list as the method in the superclass. At runtime, Java determines which version of the method to execute based on the actual type of the object.

Example:

 

Example:

 

Abstraction:

          Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Ex:SMS, Phone Call.

Abstract class:

          A class is which declared with the abstract keyword is known as abstract class in java. It can have abstract and non abstract methods.

          There are two Ways to achieve abstraction such as, Abstract and Interface.

          An Abstract class must be declared with an abstract keyword.

Syntax:

abstract class A{}

 

Abstract method: A method which is declared as abstract &doen not have Implementation is known as abstract method.

Example: abstract void Print();   // No method body & abstract.

Output:

 

 

Threads:

          A thread is a lightweight process that enables a program to perform multiple tasks concurrently, allowing for more efficient use of resources and enabling parallel execution of code. Threads operate independently within a program, each with its own execution path, and can execute tasks simultaneously without interfering with each other or the main program's execution.

          Another benefit of using thread is that if a thread gets an exception or an error at the time of its execution, it doesn't affect the execution of the other threads. All the threads share a common memory and have their own stack, local variables and program counter. When multiple threads are executed in parallel at the same time, this process is known as Multithreading.

 

        New

Runnable

Runnable

Terminated

Non Runnable
(
Blocked)

 

 

 
   

 

 

 

 

 

 

 

 

 

New:When a thread is created, but the start() method hasn't been called yet, it's in the new state.

Runnable: Once the start() method is invoked, the thread becomes runnable. This means it's eligible to run, but the scheduler hasn't selected it to run yet.

Blocked: A thread transitions to the blocked state when it's waiting for a monitor lock. This happens when it's trying to enter a synchronized block or method, but another thread holds the lock.

Terminated: A thread enters the terminated state when its run() method exits or when it's terminated prematurely using methods like interrupt() or stop(). Once terminated, a thread cannot be restarted.

Methods in Thread:

start(): Starts the execution of the thread by calling its run() method.

 

run(): Contains the code that defines the behavior of the thread. This method needs to be overridden by subclasses of Thread or provided to the Thread constructor via a Runnable object.

 

sleep(long millis): Causes the currently executing thread to sleep (temporarily pause) for the specified number of milliseconds.

 

join(): Waits for the thread to complete its execution. If necessary, it can also specify a timeout.

 

interrupt(): Interrupts the thread, causing it to exit from a sleeping or waiting state, or to throw an InterruptedException if it's in an interruptible blocking method.

 

isAlive(): Checks whether the thread is still alive (i.e., has started but not yet terminated).

 

setName(String name): Sets the name of the thread.

 

getName(): Retrieves the name of the thread.

 

yield(): Causes the currently executing thread to yield execution to another thread of equal priority.

 

isInterrupted():Checks whether the thread has been interrupted.

 

setPriority(int priority): Sets the priority of the thread.

 

getPriority(): Retrieves the priority of the thread.

 

 

 

 

Example:

Output:

 

Multi Threading:

Multithreading refers to the ability of a program to execute multiple threads concurrently within a single process.

Each thread represents a separate flow of control, allowing different parts of the program to perform tasks simultaneously.

Multithreading enhances efficiency by utilizing available resources more effectively and improving responsiveness, particularly in applications with parallelizable tasks such as handling multiple user requests or performing background processing.

Advantages:

          It doesn't block the user because threads are independent and you can perform multiple operations at the same time.

You can perform many operations together, so it saves time.

Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Example:

Output:

 

 

 

 

 

T

Multitasking:

          Multitasking in Java refers to the ability of a Java program to execute multiple tasks simultaneously. This is typically achieved using threads, where each thread represents a separate flow of control. Multitasking allows different parts of the program to run concurrently, improving performance, responsiveness, and resource utilization.


Example:

 

 

 

 

Output:

Multitasking can be achieved in two ways:

  1. Process based Multitasking.
  2. Thread based Multitasking.

Process based Multitasking:

          Each process has an address in memory. In other words, each process allocates a separate memory area.

A process is heavyweight.

Cost of communication between the process is high.

Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

Thread based Multitasking:

Threads share the same address space.

A thread is lightweight.

Cost of communication between the thread is low.

 

         

Method:

          The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. A Java method can perform some specific task without returning anything. Java Methods allow us to reuse the code without retyping the code.

          A method is like a function i.e. used to expose the behavior of an object.

It is a set of codes that perform a particular task.

Syntax:

[access_modifier] [return_type] methodName(parameter1_type parameter1_name, parameter2_type parameter2_name, ...)

{

    // Method body

    // Code to perform the specific task

    // Optionally return a value using 'return' statement if return type is not void

}

 

 

Access Modifier: public, private, protected, default.

Return type: void, int, double, float, long, short, byte.

public void Sample (int a, int b){

int c=a+b;

System.out.println(c);

}

Types of method Creation:

          There are two type of method creation in java,

  1. Instance Method:

Instance methods are non-static methods that are associated with instances of the class. They can access instance variables and other instance methods directly.

 

Syntax: void methodName(){

//body

}

Output:

  1. Static Method:

These methods are associated with the class rather than with any instance of the class. They can be called directly using the class name.

Syntax: static void methodname() {

//body

}

Output:

 

 

 

 

         

Constructor:

A constructor resembles a method in appearance, but it differs in function. It contains the code executed when you instantiate an object using the new keyword. In essence, it initializes the newly created object.

Types of Constructor:

  Here are some familiar common types of constructions in Java.

  1. Default Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor.

Default Constructor:

          A constructor without parameters is referred to as a default constructor. A default constructor is invisible.

Syntax:

public class ClassName {

    // Instance variables

   

    // Constructor(s)

    public ClassName() {

        // Constructor body

    }

}

Example:

 

Output:

Parameterized Constructor:

          A parameterized constructor is a constructor that accepts parameters when an object of a class is instantiated.

Syntax:

public class ClassName{

//body

ClassName(Parameter Type Parameter){

//body

}

}

Example:

Output:

Copy Constructor:

A copy constructor in Java is a constructor that creates a new object by copying the state of an existing object of the same class, typically used to clone objects with distinct memory addresses while maintaining identical values.

Syntax:

Public class ClassName {

//body

ClassName(Parameter type, Parameter){

//body

}

ClassName(ClassName object){

//body

}

}

Example:

 

 

Output:

 

Final:

          In Java, the final keyword is used to define entities that cannot be changed. It can be applied to variables, methods, and classes, each with its own implications:

  1. Final Variable.
  2. Final Method.

Final Variable:

          When applied to a variable, it means that once initialized, the value of that variable cannot be changed.

Example:

Output:

Final Method:

Super:

          In Java, the super keyword is used to refer to the immediate parent class of a subclass. It can be used to access methods, variables, and constructors of the superclass within the subclass. Here are two lines explaining its usage:

  1. super() is used to call the constructor of the superclass from the subclass constructor.
  2. super.methodName() is used to call a method defined in the superclass from the subclass, overriding it or using it as is.

Output:

 

This:

     In Java, the this keyword refers to the current instance of the class in which it is used, allowing access to instance variables and methods within the class scope. It is commonly used to disambiguate between instance variables and parameters or to call another constructor within the same class.

Output:

Exception Handling:

          Exception handling in Java is a mechanism to gracefully manage runtime errors or exceptional situations by enclosing risky code within a try-catch block to prevent program crashes and maintain application stability.

printStackTrace():
          The printStackTrace() method in Java is a utility used for handling exceptions and errors. It displays the stack trace, including the error line number and class name, aiding in debugging

Types of Exception Handling:

Checked Exception:

          Checked exceptions in Java are exceptions that must be either caught or declared in the method signature using the throws keyword. They are checked at compile-time.         

In Java, checked exceptions are divided into several categories, including but not limited to:

  1. IOException
  2. SQLException
  3. ParseException
  4. ClassNotFoundException

IOException:

          This category includes exceptions related to input-output operations, such as FileNotFoundException, IOException, EOFException, etc.

 

 

FileNotFoundException:

In this example, we're trying to read from a file (example.txt). However, if the file doesn't exist, a FileNotFoundException is thrown, which is a checked exception. We handle it using a try-catch block to catch the exception and handle it gracefully.

Output:

ClassNotFoundException:

In this example, Class.forName("NonExistentClass") tries to load a class named "NonExistentClass", which does not exist. This results in a ClassNotFoundException being thrown. We catch this exception and handle it by printing an error message.

Output:

Unchecked Exception:

          Unchecked exceptions, also known as runtime exceptions, are exceptions that occur during program execution and are not required to be handled explicitly by the compiler, typically representing errors or conditions beyond the program's control.

          In Java, some common types of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, and NullPointerException, among others. These exceptions occur at runtime and typically indicate errors in the program logic or unexpected conditions during execution.

 

ArithmeticException:

          This Java program attempts to divide an integer by zero within a try block. If an ArithmeticException occurs (due to division by zero), it catches the exception, prints a message indicating the error ("Divided By Zero"), and displays the stack trace of the exception.

Output:

 

 

 

 

 

 

NumberFormatException:

This Java program attempts to convert a string, "Hello", into an integer using the parseInt method. Since "Hello" cannot be converted into a valid integer, it throws a NumberFormatException.

Output:

ArrayIndexOutOfBoundsException:

Output:

NullPointerException:

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Memory Management in Java:
         
Memory management in Java refers to the process by which Java manages memory allocation and deallocation for objects created during program execution. Here are some key aspects of memory management in Java:

  1. Stack Memory
  2. Heap Memory
  3. Garbage Collection

Stack:

          Stack memory primarily stores primitive values and references to object.

          It is used to storing method calls, local variables, and reference variables.

          Each thread in a Java program has its own stack memory. It operates in a Last-In-First-Out (LIFO) manner, meaning the most recently called method is the first one to finish and be removed from the stack. Stack memory is generally faster to access but limited in size compared to the heap memory.

Heap:

          Heap memory is used for storing objects.

          When you create an object using the new keyword, memory is allocated from the heap to store that object.

          Heap memory is dynamic, meaning it can grow or shrink as needed during the execution of the program. The Java garbage collector manages heap memory by automatically deallocating memory for objects that are no longer in use, freeing up space for new objects.

Code

Stack

Heap

int x=10;

int y=a;

x=10

y=10

 

int[] a;

a=new int[3];

int[] b=a;

a
 

b

 

[0,0,0]

 

         

Garbage Collection:

          Garbage collection in Java is an automatic process performed by the JVM (Java Virtual Machine) to identify and remove unreferenced objects from memory. This helps manage memory efficiently by freeing up space for new allocations, eliminating the need for manual memory management and reducing the risk of memory leaks.

Here some of the  unreferenced objects,

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

By Nulling the reference:

          Nulling a reference in Java means setting a reference variable to null, indicating it no longer points to any object. This action allows unreferenced objects to become eligible for garbage collection.

 

 

By Assigning a Reference to another:

          In Java, when you assign a reference variable to another, you're essentially making both variables point to the same object in memory. However, when it comes to garbage collection, what matters is the number of references to an object. If an object has no references pointing to it, it becomes eligible for garbage collection.

Ref obj1=new Ref(); 

Ref obj2=new Ref(); 

obj1=obj2;         //now the first object referred by e1 is available for garbage collection .

 

Example:

 

By anonymous object

          In Java, an anonymous object refers to an object that is instantiated without assigning it to a reference variable.

Difference between Stack and Heap memory management:

 

Stack

Heap

Stack Memory is used for Static Memory Allocation

Heap Memory is used for Dynamic Memory Allocation.

It stores method frames, local variables and reference variables.

It stores objects and instance variables.

Memory Allocation and Deallocation are handled automatically by the JVM.

Memory allocation and deallocation are managed explicitly by the programmer using the new and delete

Operators.

Each thread in a java application has its own stack memory.

Heap memory is shared among all threads in a Java application.

Stack Memory is efficient and has a limited size.

Heap memory is larger and can grow dynamically based on application requirements.

It is used for short lived data and method invocation.

It is used for long lived data and objects.

 

         

 

String:

          In java, String is an object that is used for storing characters or text surrounded by double quotes.

          Strings are immutable. immutability means  the property of an object that once it is created, its state cannot be changed.

          There are two ways to create a string object in java;

  1. String literal
  2. new keyword

String Literal:

          In Java, a string literal refers to a sequence of characters enclosed within double quotes(“ “). It represents a constant value that is assigned to a variable of type String. String literals are commonly used to initialize String objects or as arguments in method calls that expect String parameters.

Example:

By using new Keyword:

In Java, the new keyword is used to instantiate objects. When creating a new object using the new keyword with the String class, you're essentially creating a new instance of the String class.

 

String Methods:

          In Java, there are numerous string methods available to manipulate strings. Here are some of the commonly used ones:

Concatenation:

          Combining two or more strings together. This can be done using the + operator or the concat() method.

Example:

Output:

 

length ():

          Getting the length of a string, i.e., the number of characters in the string. This is done using the length() method.

Example:

Output:

Sub String:

Extracting a portion of a string. This can be achieved using the substring() method.

Example:

Output:

 

 

 

charAt():

          The charAt() method in Java is used to retrieve the character at a specified index within a string. The indexing of characters starts from 0, meaning the first character of the string has an index of 0, the second character has an index of 1, and so on.

Example:

Output:

Conversion:

          Converting a string to upper case or lower case. This can be done using methods like toUpperCase() and toLowerCase().

toUpperCase:

          It is used to convert all the characters in a string to uppercase.

This method does not modify the original string; instead, it returns a new string with all characters converted to uppercase.

Example:

Output:

toLowerCase():

          It is used to convert all the characters in a string to Lower Case.

This method does not modify the original string; instead, it returns a new string with all characters converted to Lower Case.

Example:

Output:

replace():
Replacing characters or substrings within a string. This can be done using methods like replace().

Example:

 

 

Output:

Searching:

          Finding occurrences of characters or substrings within a string. This can be done using methods like indexOf() and contains().

indexOf():

          The indexOf() method in Java is a part of the String class. It is used to find the index of the first occurrence of a specified substring within the string. If the substring is found, indexOf() returns the index of its first occurrence; otherwise, it returns -1.

Example:

Output:

Contains():

          The contains() method in Java is a part of the String class. It is used to check whether a specified substring is present within the string. It returns true if the substring is found within the string, and false otherwise.

 

 

Example:

Output:

StringBuffer:

          StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time.

Methods of StringBuffer:

Here are some of the StringBuffer methods.

 

append():

          append() is a method in Java used to add characters or sequences of characters to the end of an existing StringBuffer.

          It modifies the original object by concatenating the provided data at the end.

Example:

Output:

Insert():

          insert() is a method in Java used to insert characters or sequences of characters into an existing StringBuffer or StringBuilder object at a specified position.

It modifies the original object by inserting the provided data at the specified index.sert method is java is used to insert character or sequence of character into anStringBuffer.

 

 

 

 

 

Example:

Output():

Delete():

          The delete() method of the StringBuffer class deletes the string from the specified beginIndex to endIndex-1.

Example: