0% found this document useful (0 votes)
4 views

UNIT 1.1 Java Fundamentals

Uploaded by

polavenitharun48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

UNIT 1.1 Java Fundamentals

Uploaded by

polavenitharun48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Java Programming

History of Java Java is an Object-Oriented Programming language.


James Gosling and his team at “Sun Micro Systems” in
1995
In the early 90s initially designed for embedded systems
in electronic appliances like set-top boxes, digital cameras,
etc.
Firstly, it was called "Green talk" later, it was called “Oak”
Why named as Oak to Java?

• Oak is a symbol of strength.


• In 1995, Oak was renamed as "Java"
because it was already a trademark by
Oak Technologies.
• Java is an island where the first coffee
was produced (called Java coffee).
• Java name was chosen by James
Gosling while having a cup of coffee
nearby his office.
Features of Java

Object- Platform
Simple Portable
Oriented independent

Architecture
Secured Robust Interpreted
neutral

High
Multithreaded Distributed Dynamic
Performance
Features of Java

Portable: Platform independent :


Simple: Object Oriented :
Everything in Java is an The same bytecode Java code can be
Its syntax is simple,
object. program can run on any executed on multiple
syntax is based on C++
computer system . platforms

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

High Performance : Distributed:


Multithreaded: Dynamic:
Just-In-Time compilers Programs can be
Many tasks at once by classes are loaded on
enables high designed to run on
defining multiple threads demand.
performance. computer networks
Java Features
 Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.

 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.

Supports multiple inheritance. Java doesn't support multiple inheritance through


class. It can be achieved by using interfaces in java.

Supports operator overloading. Java doesn't support operator overloading.

supports pointers. Doesn’t have pointers

Supports structures and unions. Doesn't support structures and unions.

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.

JVM (Java Virtual Machine) is an abstract machine. It


is called a virtual machine because it doesn't physically
exist.
It is a specification that provides a runtime
environment in which Java bytecode can be executed.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
bytecode

 The Virtual machine code is not machine specific.


 The machine specific code is generated by Java interpreter by
acting as an intermediary between the virtual machine and real
machines shown below
Variables in java

A Variable is a name given to the memory location.


It is used to store data
Its value can be changed, and it can be reused many times.
1000
1001
a
1002
Syntax: type variable_name;
1003
1004

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

 Alphabets - A, B, ….., Y, Z a, b, ……, y, z


 Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
 Special symbols - ~ ‘ ! @ # % ^ & * ( ) _ - + = | \ , -* + : ; " ‘
 <>,.?/
Data Types in Java
 Data types specify the different sizes and values
that can be stored in the variable.
 There are two types of data types in Java:
1. Primitive data types: The primitive data types
include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data
types include Classes , Interfaces and Arrays
Data Types in Java
Data type Size (byte) Range
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
Int 4 2,147,483,648 to 2,147,483,647
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308
Data Types default values

Data Type Default Value Default size

boolean false 1 bit


char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byt
Operators:

An operator is symbol that specify operation to be perform certain operation.

1. Arithmetic operators 1 Arithmetic operators


2. Logical operators Operator Meaning
3. Relational operators + Addition
4. Assignment operators - Subtraction
5. Bit wise operators / Division
6. Increment and decrement operators
* Multiplication
7. Conditional operators
% Modulo division or remainder

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

<= Less than or equal to ! Logical –NOT


Operators:
5 Bit wise operators
4 Assignment operators Operator meaning
| Bitwise OR
symbol shorthand Meaning
& Bitwise AND
+= A+=1 A=A+1
&= Bitwise AND assignment
-= A-=1 A=A-1 |= Bitwise OR assignment
/= A/=B A=A/B ^ Bitwise Exclusive OR
<< Left shift
*= A*=B A=A*B
>> Right shift
%= A%=C A=A%C ~ One‘s complement

6 Increment and decrement operators 7. Conditional Operator( ?: )


Expression Process Example end result
A++ (post incr) Add 1 to a variable int A=10,B; A=11
after use. B=A++; B=10
++A (pre incr) Add 1 to a variable int A=10,B; A=11
before use. B=++A; B=11 Expression1 ? Expression2 : Expression3
A– (post decr) Subtract 1 from a int A=10,B; A=9
variable after use. B=A--; B=10
--A (Pre dect) Subtract 1 from a int A=10,B; A=9
int max = (a > b) ? a : b;
variable before use. B=--A; B=9
Precedence and associativity of Operators:

 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

15 Comma , Left to right


Control Structures/control statements:
In java program, control structure is can divide in three parts:
1. if statement (conditional)
I. Selection Statement/ Conditional Statement i. If (simple if)
II. Loops/Iteration Statement
III. Unconditional / Jumps In Statement ii. if – else
iii. Cascaded(if else - if)
I . SELECTION statements:
 Selection statements used for Decision making. iv. Nested if
 Decision making is about deciding the order of execution of
statements based on certain conditions

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

1. Automatic Conversion (Implicit Casting)


double doubleValue = 9.99;
• value is automatically converted from a smaller data type to a int intValue = (int) doubleValue; // double to int (explicit
larger data type
casting, may lose precision)
• e.g., int to long, float to double)
• No Data Loss long longValue = 1000L;
short shortValue = (short) longValue; // long to short (explicit
casting)
int num = 10;
long bigNum = num; // int to long (automatic conversion)

float floatValue = 5.5f;


double doubleValue = floatValue; // float to double (automatic
conversion)
Type Conversion and Casting in Java
Casting Objects:
• casting is also used with objects, particularly in the context
of inheritance hierarchies.

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 {}

Animal a = new Dog(); // Upcasting (implicit)

Dog d = (Dog) myAnimal; // Downcasting (explicit, requires


checking)
Access Modifiers in Java
 Specifies the scope of a field, method or class

FOUR TYPES

1. Public: accesses from everywhere.


• It can be accessed from within /outside the class,
with in package/outside of package

2. Private: accessed only within the class.


• Can’t be accessed from outside the class.

3. Protected: within the package and outside the


package through child class.

4. Default: only within the package.


• Can’t be accessed from outside the package.
• If we do not specify any access level, it will be the
default.
Enumerated types in java
 Enum is a special kind of class that represents a group of
constants .
 Define a set of named constants, which can be used to
represent fixed sets of values in a type-safe manner.

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}

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; }

// Print the current day


System.out.println("Today is: " + today);

// Use a switch statement with the enum


switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("End of the work week.");
break;
Garbage Collection in java
 Garbage collection (GC) is the process by which Java finalize() method
automatically cleans up memory by removing objects that The finalize() method is invoked each time before the object
are no longer needed, so that memory can be used again. is garbage collected. This method can be used to perform
cleanup processing
GC happens when object is not reachable:
gc() method
1. By nulling the reference
The gc()  invoke the garbage collector to perform cleanup
2. By assigning a reference to another
processing.
3. By anonymous object etc.
Ex.
1.By nulling the reference
public class Garbage{
Employee e=new Employee();
public void finalize()
e=null
{
System.out.println("object is garbage collected");}
2. By assigning a reference to another
public static void main(String args[]){
Garbage s1=new Garbage();
Employee e1=new Employee();
Garbage s2=new Garbage();
Employee e2=new Employee();
s1=null;
e1=e2;// first object referred by e1 is available for GC
s2=null;
System.gc();
3. By anonymous object etc.
}
new Employee();
}

You might also like