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.