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: