Java Fundamentals
JAVA
Introduction:
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:
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.
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 |
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.
|
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;
|
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;
|
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
|
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;
|
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
|
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:
int y = (x > 5) ? ((x < 15) ? 100 : 200) : 300;
Here's the expression breakdown:
|
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.