UNIT 1.1 Java Fundamentals
UNIT 1.1 Java Fundamentals
Object- Platform
Simple Portable
Oriented independent
Architecture
Secured Robust Interpreted
neutral
High
Multithreaded Distributed Dynamic
Performance
Features of Java
Robust: Interpreted:
Secured: Architecture neutral:
Lack of pointers, Java byte code is
No explicit pointer, Java Byte-code is not
automatic garbage translated on the fly to
Programs run inside a dependent on any
collection, exception native machine
virtual machine sandbox machine architecture
handling instructions
Platform Independent
Unlike many other programming languages including C and C++, when Java is compiled,
it is not compiled into platform specific machine, rather into platform-independent byte
code. This byte code is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.
Java Features
Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime
system.
Portable
Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. The compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
Java Features
Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile time error checking and runtime checking.
Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform
many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
Java Features
High Performance
With the use of Just-In-Time compilers, Java enables high performance.
Distributed
Java is designed for the distributed environment of the internet.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry an extensive amount of run-time
information that can be used to verify and resolve accesses to objects at run-time.
Crating a First Java Program
class Sample Parameters used in First Java Program
{
public static void main(String args[ ]) class keyword is used to declare a class in Java.
{ public access modifier that represents visibility..
System.out.println(“Welcome to Java"); static - no need to create an object to invoke the static
} method.
} void : it doesn't return any value.
main represents the starting point of the program.
• Save the above file as Sample.java. String[] args or String args[] is used for command line
argument.
compile: javac Sample.java System.out.println() is used to print statement.
execute: java Sample
Output:
Welcome to Java
C++ Java
platform-dependent. platform-independent.
Used for system programming. Used for application programming (web, mobile)
Supports the goto statement. Java doesn't support the goto statement.
Doesn't have built-in support for threads. It relies Java has built-in thread support.
on third-party libraries for thread support.
Supports virtual keyword so that we can decide Java has no virtual keyword.
whether to override a function.
JDK, JRE, and JVM
JDK - Java Development Kit. JRE is used to provide the runtime environment. It is the
implementation of JVM. It physically exists.
It is a software development environment
which is used to develop Java applications It contains a set of libraries + other files that JVM uses
at runtime.
It contains JRE + development tools. It contains JRE + development tools.
RAM Visualization
Eg : int a;
float b;
char c;
Variable Declaration:
a
int a;
10
float b;
1000
Variable Initialization:
2 bytes
a = 10;
b
b = 10.456;
10.456000
2000
4 bytes
Types of Java Variables 3) Static variable
A single copy of the static variable can be
There are THREE types of variables in java: shared among all the instances of the
local, instance and static. class.
1) Local Variable Memory allocation for static variables
A variable declared inside the body of the method is happens only once when the class is
called local variable loaded in the memory.
You can use this variable only within that method
the other methods in the class aren't even aware public class A
{
that the variable exists. static int m=100;//static variable
void method()
2) Instance Variable {
A variable declared inside the class but outside int n=90;//local variable
the body of the method, is called an instance }
public static void main(String args[])
variable. {
It is not declared as static. int data=50;//instance variable
}
It is called an instance variable because its value }//end of class
is instance-specific and is not shared among
instances.
Constants : and Literals
c)Hexadecimal integer
Constant means fixed value which is not change at the time of
It allows the sequence which is preceded by 0X or 0x and it
execution of program.
also allows alphabets from A to F or a to f , A to F stands for
In Java, there are two types of constant as follows:
Numeric Constants the numbers 10 to 15 it is called as Hexadecimal integer.
Integer constant For example: 0x7
Real constant 00X
Character Constants 0A2B
Character constant Real Constant
String constant
It allows us fractional data and it is also called as folating
Integer Constant:
An Integer constant refers to a series of digits. point constant. For example: 0.0234 0.777 -1.23
There are three types of integer as follows:
a) Decimal integer Character Constant
Embedded spaces, commas and characters are not allowed in It allows us single character within pair of single quote.
between digits. For example: ‘A‘ ‘7‘
For example: String Constant
23 411 7,00,000 17.33 It allows us the series of characters within pair of double
b) Octal integer quote.
Any sequence of numbers or digits from 0 to 7 with leading For example: “WELCOME”
0 and it is called as Octal integer.
For example: 011 00 0425
Symbolic constant: Java provides final keyword to declare
final float PI=3.1459
Identifiers
Name given to entities such as variables, functions, structures etc.
Example: int sum; float marks; void swap(int a, int b);
sum, marks, swap - Identifiers
int, float – Keywords
An identifier is a long sequence of letters(a-z & A-Z) and numbers(0-9).
No special character except underscore ( _ ) can be used as an identifier.
Keyword should not be used as an identifier name.
C is case sensitive. So using case is significant.
First character of an identifier can be letter, underscore ( _ ) but not digit
Character Set
• A character denotes any alphabet, digit or special symbol used to represent
information
3 Relational operators
Operator Meaning
2 Logical operators
> Greater than
Operators Importance/ significance
< Less than
|| Logical – OR
!= Not equal to
>= Greater than or equal to
&& Logical –AND
The precedence of operator specifies that which operator will be evaluated first and next.
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).
Associativity of Operators
The associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
‘*’ and ‘/’ have same precedence and their associativity is Left to Right.
E.g. 100 / 10 * 10
Operator Hierarchy:
Precedence Category Operator Associativity
1 Postfix () [] -> . ++ - - Left to right
2 Unary + - ! ~ ++ - - (type)* & sizeof Right to left
3 Multiplicative */% Left to right
4 Additive +- Left to right
5 Shift << >> Left to right
6 Relational < <= > >= Left to right
7 Equality == != Left to right
8 Bitwise AND & Left to right
9 Bitwise XOR ^ Left to right
10 Bitwise OR | Left to right
11 Logical AND && Left to right
12 Logical OR || Left to right
13 Conditional ?: Right to left
14 Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Types:
1. if statement (conditional)
2. switch statement
Control Structures/control statements:
i) simple if ii) if – else statement
Syntax : Syntax :
if(condition)
if(condition) {
{ //block1: code to be executed if condition is true
// Statements inside. }
else
} {
//remaining statements //block2: code to be executed if condition is
//statement outside false
}
If the expression or condition returns true, then the • If the expression is true, the statement-block1 is
statements-inside will be executed, otherwise executed, else statement-block1 is skipped and
statements-inside will be skipped statement-block2 is executed..
// Check if person 1 is taller
// Check if person 1 is taller if (h1 > h2) {
if (h1 > h2) System.out.println("Person 1 is taller");
{ } else
System.out.println("Person 1 is taller"); {
} System.out.println("Person 2 is taller");
}
Control Structures/control statements:
Ex Decision Making in PUBG
iii) If else if ladder
Syntax : • PUBG players are not going to get a Chicken
if(condition1) Dinner anytime soon without the ability to aim
{ at targets and take them down with relative
//block1: code to be executed if condition1 is ease.
true • So to aim the target they must use scope. It can
} take hundreds of rounds before you become
else if(condition2) more comfortable with all the weapons on offer
{ and start landing your shots, but we’re here to
//block2:code to be executed if condition2 is help speed that process up.
true
}
else if(condition3){ Conditions:
//block3:code to be executed if condition3 is • If you have 8x scope, Use sniper gun.
true
} • If you have 6X scope, Use AUG A3, GROZA, QBZ, M16A4,
... M416 .
else{ • If you have 4x Scope, Use UMP9, AKM, SCAR-L, Cross Bow .
//:code to be executed if all the conditions are false
• If you have 2x Scope, almost all guns.
} • If you don’t have scope, find one.
The if...else ladder allows you to check between multiple test
Now Let’s help them by writing a program which helps them
expressions and execute different statements..
to select the gun based on the scope .
Control Structures/control statements: If(age >= 12)
iv) Nested if {
Syntax: If(weight >= 40)
if (condition1) {
{
// code to be executed if condition1 is true If(weight <= 110)
if (condition2) {
{
print(“He can Jump”);
// code to be executed if condition2 is true
} }
} else
{
print(“Extra ropes will be added”);
}
}
else
{
print(“He can’t Jump”);
}
}
else
{
Print(“He can’t Jump”);
}
Control Structures/control statements:
switch(number)
Switch Case (Multiple Branching Statement) {
case 1:
Syntax: Print(“Welcome to Erangel Map. You are Inside a
switch(expression){ Forest”);
case 1: break;
//code to be executed; case 2:
break; Print(“Welcome to Miramar Map. You are Inside a
case 2: Desert”);
//code to be executed; break;
break; case 3:
...... Print(“Welcome to Sanhok Map. You are Inside a
default: Rain Forest”);
code to be executed if all break;
cases are not matched; case 4:
} Print(“Welcome to Vikendi Map. You are Inside a
Snow Forest”);
The switch statement allows us to execute one code break;
block among many alternatives. default:
Allows us to execute multiple operations for the Print(“Invalid Input”);
different possible values of a single variable called }
switch variable.
We can define various statements in the multiple
cases for the different values of a single variable.
Loops / Iterations
The process of repeatedly executing a statements and is for-each loop
called as looping. Used to traverse the array or collection elements
Types:
In Iteration statement, there are three types of operation: Syntax:
1. for loop
2. while loop for(data_type variable : array | collection){
3. do-while loop
//body of for-each loop
}
1. Java for loop:
for loop is used to iterate a part of the program several times. If for(int i=1;i<=10;i++){
the number of iteration is fixed, it is recommended to use for System.out.println(i);
loop. }
Syntax:
for(initialization;condition; incr/decr) Ex.,
{ int arr[]={12,13,14,44};
Statement block; //traversing the array with for-each loop
}
for(int i:arr)
for(int i=1;i<=10;i++){
{
System.out.println(i);
System.out.println(i);
}
}
Loops / Iterations
2 while loop 3.The Do/While Loop
The while loop loops through a block of code as long as a This loop will execute the code block once, before checking if
specified condition is true: the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax: Syntax:
while (condition) do
{ {
// code block to be executed
// code block to be executed
}
Ex.
}
int i = 0; while (condition);
while (i < 5)
{ Ex.
System.out.println(i); int i=1;
i++; do{
} System.out.println(i);
i++;
}while(i<=10);
Unconditional / Jumps In Statement
break : continue:
The break statement immediately terminates the loop
The continue statement in Java is used within loops to
for (int i = 0; i < 10; i++) skip the current iteration and proceed to the next
{ iteration of the loop.
if (i == 5)
{
break; // Exits the loop when i equals 5 for (int i = 0; i < 10; i++)
} { if (i % 2 == 0)
System.out.println(i); {
} continue; // Skips the even numbers
}
System.out.println(i);
System.out.println("Loop ended."); }
Console Input and output in java
import java.util.Scanner;
• In Java, handling console input and output involves using
the Scanner class for input and System.out for output public class InputOutputExample {
public static void main(String[] args) {
1. Console Input // Create a Scanner object to read input
• To read input from the console, use the Scanner class from Scanner sc = new Scanner(System.in);
the java.util package.
• You create a Scanner object and use its methods to read // Prompt the user for their name
different types of data. System.out.print("Enter your name: ");
String name = sc.nextLine();
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for their age
2. Console Output System.out.print("Enter your age: ");
• To print output to the console, use System.out.println() or int age = sc.nextInt();
System.out.print().
// Display the collected information
System.out.println("Hello, " + name + "!");
• System.out.println: Prints text followed by a new line. System.out.println("You are " + age + " years old.");
• System.out.print: Prints text without a new line.
}
}
Type Conversion and Casting in Java
• process of converting a value of one data type into
2.Narrowing Conversion (Explicit Casting)
another converting a value from a larger data type to a smaller
1. implicit conversion data type
2. explicit casting requires explicit casting to prevent potential data loss.
e.g., double to int, long to short
Types of Casting:
• Upcasting: Implicit conversion of a subclass object to its
superclass type. Safe and always possible.
• Downcasting: Explicit conversion of a superclass reference
to a subclass type. Requires careful checking to avoid
runtime error
class Animal { }
class Dog extends Animal {}
FOUR TYPES
Key Features :
Type Safety:
Enums ensure that only predefined constants can be
used, avoiding invalid values.
Namespace:
Enums create their own namespace, which helps in
organizing constants related to a specific concept.
Enhanced Functionality:
Enums can have fields, methods, and constructors,
making them more versatile than simple constants.
Enumerated types in java
// Enum for Days of the Week case SATURDAY:
public enum Day { case SUNDAY:
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, System.out.println("It's the weekend!");
FRIDAY, SATURDAY break;
} default:
System.out.println("Midweek.");
public class EnumExample { break;
public static void main(String[] args) { }
// Create an enum variable and assign it a value }
Day today = Day.FRIDAY; }