PROGRAMMING WITH JAVA
TAAHOFU + ex
PROCEDURAL ORIENTED OBJECT ORIENTED
PROGRAMMING PROGRAMMING
In procedural programming, program is divided In object oriented programming, program is
into small parts called functions. divided into small parts called objects.
Procedural programming follows top down Object oriented programming follows bottom
approach. up approach.
There is no access specifier in procedural Object oriented programming have access
programming. specifiers like private, public, protected etc.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have any Object oriented programming provides data
proper way for hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is not Overloading is possible in object oriented
possible. programming.
In procedural programming, function is more In object oriented programming, data is more
important than data. important than function.
Procedural programming is based on unreal Object oriented programming is based on real
world. world.
ALSO INCLUDE EXAMPLES
ALSO ADD CHATGPT POINTS -IF POSSIBLE
OBJECT AND CLASS
THE THREE OOP PRINCIPLES
1. Encapsulation
🞆 Encapsulation is the mechanism that binds together
code and the data it manipulates, and
keeps both safe from outside interference and misuse.
🞆 One way to think about encapsulation is as a
protective wrapper that prevents the code and data
from being arbitrarily accessed by other code defined
outside the wrapper.
🞆 In Java, the basis of encapsulation is the class.
🞆 Encapsulation allows you to migrate your
implementations over time without breaking the code
that depends on the public interface of your classes.
2. Inheritance
🞆 Inheritance is the process by which one object
acquires the properties of another object.
🞆 by use of inheritance, an object need only define
those qualities that make it unique within its
class.
🞆 It can inherit its general attributes from its
parent.
🞆 A well-designed hierarchy of classes is the basis
for reusing the code in which you have invested
time and effort developing and testing
3. Polymorphism
🞆 Polymorphism is a feature that allows one
interface to be used for a general class of actions.
🞆 The specific action is determined by the exact
nature of the situation.
🞆 “one interface, multiple methods.
🞆 This helps reduce complexity by allowing the
same interface to be used to specify a general
class of action. It is the compiler’s job to select the
specific action (i.e method) as it applies to each
situation.
🞆 Polymorphism allows you to create clean,
sensible, readable, and resilient code.
THE HISTORY AND EVOLUTION OF JAVA
🞆 Java is a general-purpose programming
language that is class-based and object-oriented
🞆 Java is related to C++, which is a direct descendant of
C.
🞆 Much of the character of Java is inherited from these
two languages ( C and C++).
🞆 All code is written inside classes, and every data item
is an object, with the exception of the primitive data
types, (i.e. integers, floating-point numbers, boolean
values, and characters), which are not objects for
performance reasons.
🞆 Unlike C++, Java does not support operator
overloading or multiple inheritance for classes,
though multiple inheritance is supported
for interfaces.
🞆 James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green
Team.
🞆 Initially it was designed for small, embedded systems in
electronic appliances like set-top boxes.
🞆 Firstly, it was called "Greentalk" by James Gosling, and
the file extension was .gt.
🞆 After that, it was called Oak and was developed as a part
of the Green project.
🞆 In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.
🞆 Primary motivation behind JAVA was the need for a
platform-independent language
🞆 that could be used to create software to be embedded in
various consumer electronic devices.
🞆 JAVA was intended to let application developers write
once, run anywhere (WORA), meaning that compiled Java
code can run on all platforms that support Java without
the need for recompilation.
🞆 Second force was World Wide Web, which
demanded portable programs.
How Java Changed the Internet???
Java Applets
🞆 is a special kind of Java program that is designed
to be transmitted over the Internet and
automatically executed by a Java-compatible web
browser.
🞆 applet allows some functionality to be moved
from the server to the client.
how Security is assured ??
🞆 Java achieved this protection by confining an
applet to the Java execution environment and not
allowing it access to other parts of the computer
JAVA’S MAGIC: THE BYTECODE
🞆 Java was designed to be portable , which means
programs written for the Java platform must run
similarly on any combination of hardware and
operating system with adequate run time support.
🞆 This is achieved by compiling the Java language code
to an intermediate representation called Java
bytecode, instead of directly to architecture-
specific machine code.
🞆 Bytecode is a highly optimized set of instructions
designed to be executed by the Java run-time system,
🞆 which is called the Java Virtual Machine (JVM). The
original JVM was designed as an interpreter for
bytecode.
🞆 Translating a Java program into bytecode makes it
much easier to run a program in a wide variety of
environments because only the JVM needs to be
implemented for each platform. Once the run-time
package exists for a given system, any Java program
can run on it.
🞆 Although the details of the JVM will differ from
platform to platform, all understand the same Java
bytecode
🞆 Since Java program is executed by the JVM also
helps to make it secure. JVM contains the program
and prevent it from generating side effects outside of
the system.
🞆 When a Java program is compiled the .java files are
fed to a compiler which produces a .class file for each
.java file
🞆 The fact that a Java program is executed by the JVM
also helps to make it secure.
How to boost performance ?
🞆 Just In Time (JIT) compilers interact with the Java
Virtual Machine (JVM) at run time and compile
suitable bytecode sequences into native machine code.
🞆 When a JIT compiler is part of the JVM, selected
portions of bytecode are compiled into executable code
in real time, on a piece-by-piece, demand basis.
🞆 It is important to understand that it is not practical to
compile an entire Java program into executable code
all at once, because Java performs various run-time
checks that can be done only at run time.
JAVA BUZZWORDS
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
[Link]
🞆 Since Java inherits the C/C++ syntax and many
of the object-oriented features of C++, so most
programmers with programming experience , will
not find Java hard to master.
[Link]-Oriented
🞆 Although influenced by its predecessors, Java
was not designed to be source-code compatible
with any other language.
🞆 The object model in Java is simple and easy
to extend, while primitive types, such as integers,
are kept as high-performance non-objects.
3. Robust
🞆 Java is a strictly typed language, it checks code
at compile time and at run time.
🞆 Java virtually eliminates the problems of
memory management by managing memory
allocation and deallocation .
🞆 Automatically by garbage collection for unused
objects.
🞆 By providing Exception handling , all run-time
errors can—and should—be managed by
program.
[Link]
🞆 Java meets the real-world requirement of
creating interactive, networked programs.
🞆 To accomplish this, Java supports multithreaded
programming, which allows you to write
programs that do many things simultaneously
5. Architecture-Neutral
A central issue for the Java designers was that of
code longevity and portability.
🞆 Operating system upgrades, processor upgrades,
and changes in core system resources can all
combine to make a program malfunction.
🞆 goal was “write once; run anywhere, any time,
forever.”
6. Interpreted and High Performance
🞆 Java bytecode was designed so that its easy to
translate directly into native machine code for very
high performance by using a just-in-time compiler.
🞆 Java run-time systems that provide this feature
lose none of the benefits of the platform-
independent code.
7. Distributed
🞆 Java is designed for the distributed environment of
the Internet because it handles TCP/IP protocols.
🞆 Java also supports Remote Method Invocation
(RMI).
🞆 This feature enables a program to invoke methods
across a network.
[Link]
🞆 Java programs carry with them substantial
amounts of run-time type information that is
used to verify and resolve accesses to objects at
run time.
🞆 This is crucial to the robustness of the Java
environment, in which small fragments of
bytecode may be dynamically updated on a
running system.
🞆 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.
🞆 JVMs are available for many hardware and software
platforms. JVM, JRE, and JDK are platform dependent
because the configuration of each OS is different from
each other. However, Java is platform independent
🞆 The JVM performs the following main tasks:
🞆 Loads code
🞆 Verifies code
🞆 Executes code
🞆 Provides runtime environment
🞆 JRE is an acronym for Java Runtime Environment. The Java
Runtime Environment is a set of software tools which are used for
developing Java applications.
🞆 It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists.
🞆 It contains a set of libraries + other files that JVM uses at
runtime.
🞆 JDK is an acronym for Java Development Kit. The Java
Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
🞆 JDK is an implementation of any one of the below given Java
Platforms released by Oracle Corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform
🞆 The JDK contains a private Java Virtual Machine (JVM) and a
few other resources such as an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc.
FIRST JAVA PROGRAM
[Link]
class Hello {
public static void main(String[] args) {
[Link](“Hello World !!!”);
}
}
C:\javac [Link] ( compilation creates [Link] )
C:\java Hello (Execution on the local JVM)
public static void main(String[] args)
All Java applications begin execution by calling
main( ).
🞆 In this case, main( ) must be declared as public,
since it must be called by code outside of its
class when the program is started.
🞆 The keyword static allows main( ) to be called
without having to instantiate a particular instance
of the class.
🞆 This is necessary since main( ) is called by the
Java Virtual Machine before any objects are made.
The keyword void simply
🞆 Void tells the compiler that main( ) does not
return a value.
🞆 Java compiler will compile classes that do not
contain a main( ) method.
🞆 But java has no way to run these classes. So, if
you had typed Main instead of main, the compiler
would still compile your program.
🞆 However, java would report an error because it
would be unable to find the main( ) method.
🞆 String args[ ] declares a parameter named args,
which is an array of instances of the class String.
🞆 Objects of type String store character strings. In
this case, args receives any command-line
arguments present when the program is
executed.
[Link]("This is a simple Java
program.");
🞆 System is a predefined class that provides
access to the system, and out is the output
stream that is connected to the console.
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
🞆 In this statement, the plus sign causes the value of
num to be appended to the string that precedes
it, and then the resulting string is output.
🞆 Actually, num is first converted from an integer
into its string equivalent and then concatenated with
the string that precedes it.
DATA TYPES
Java defines eight primitive types of data: byte,
short, int, long, char, float, double, and
boolean
Integers This group includes byte, short, int,
and long, which are for whole-valued signed
numbers.
Floating-point numbers This group includes float
and double, which represent numbers with
fractional precision.
Characters This group includes char, which
represents symbols in a character set, like
letters and numbers.
Boolean This group includes boolean, which is a
special type for representing true/false
values.
Characters
🞆 In Java, the data type used to store characters is
char. In C/C++, char is 8 bits wide.
🞆 , Java uses Unicode to represent characters.
🞆 Unicode defines a fully international character set
that can represent all of the characters found in all
human languages. Java char is a 16-bit type.
The range of a char is 0 to 65,536. There are
no negative chars.
.
LEXICAL ISSUES
Whitespace
🞆 Java is a free-form language. This means that you
do not need to follow any special indentation rules.
Identifiers
🞆 Identifiers are used for class names, method names,
and variable names
🞆 Java is case-sensitive, so VALUE is a different
identifier than Value.
Literals
🞆 A constant value in Java is created by using a literal
representation of it.
🞆 100, 98.6, 'X' ,"This is a test“.
Comments
multiline comment
/*
This is a simple Java program.
Call this file "[Link]".
*/
single-line comment
// Your program begins with a call to main().
Documentation comment
/** this is comment */.
🞆 This type of comment is used to produce an
HTML file that documents your program.
DYNAMIC INITIALIZATION
🞆 Java allows variables to be initialized
dynamically, using any expression valid at the
time the variable is declared
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}
THE SCOPE AND LIFETIME OF VARIABLES
🞆 Scope of a variable is the part of the program where the
variable is accessible. Like C/C++, in Java, all identifiers
are lexically (or statically) scoped, i.e. scope of a variable
can be determined at compile time and independent of
function call stack.
🞆 Member Variables (Class Level Scope)
We can declare class variables anywhere in class, but
outside methods. Access specified of member variables
doesn’t affect scope of them within a class
🞆 Local Variables (Method Level Scope)
Variables declared inside a method have method level scope
and can’t be accessed outside the method.
🞆 A block defines a scope. A scope determines
🞆 what objects are visible to other parts of your program.
class Scope {
public static void main(String args[]) {
int x=10;
if(x == 10)
{
int y = 20;
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
y = 100; // Error! y not known here
[Link]("x is " + x);
}
}
public class Test
{ static int x = 11;
private int y = 33;
public void method1(int x) {
Test t1 = new Test();
Test.x = 22; y = 44;
[Link]("Test.x: " + Test.x); ?
[Link]("t1.x: " + t.x);
[Link]("t1.y: " + t.y);
[Link]("y: " + y); }
public static void main(String args[]) {
Test t = new Test();
t.method1(5);
} Test.x: 22
t.x: 22
} t.y: 33
y: 44
JAVA IS STRONG-TYPED LANGUAGE
🞆 A strongly-typed is one in which variables are
bound to specific data types, and will result
in type errors if types do not match up as expected in
the expression — regardless of when type checking
occurs.
🞆 Java’s safety and robustness comes from this fact
🞆 Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for
type compatibility.
🞆 There are no automatic coercions or conversions of
conflicting types as in some languages.
🞆 Any type mismatches are errors that must be
corrected before the compiler will finish compiling the
class
TYPE CONVERSION AND CASTING
Automatic type conversion
will take place if the following two conditions are
met:
• The two types are compatible.
• The destination type is larger than the source
type.
When these two conditions are met, a widening
conversion takes place
int to long, byte to int (allowed)
Num to char /boolean ( not allowed)
CASTING INCOMPATIBLE TYPES
🞆 explicitly making the value narrower so that it will fit
into the target type.
🞆 Int to byte
🞆 This kind of conversion is sometimes called a
narrowing conversion
🞆 To create a conversion between two incompatible
types, you must use a cast.
🞆 A cast is simply an explicit type conversion.
🞆 It has this general form:
(target-type) value
int a;
byte b;
b = (byte) a;
NUMERIC TYPE CONVERSION
Consider the following statements:
byte i = 100;
long k = i*3+4;
double d = i*3.1+k/2;
int x = k; //(Wrong)
long k = x; //(fine,implicit casting)
AUTOMATIC TYPE PROMOTION IN
EXPRESSIONS
Java defines several type promotion rules that
apply to expressions
The Type Promotion Rules
🞆 First,all byte, short, and char values are
promoted to int.
🞆 Then, if one operand is a long, the whole
expression is promoted to long.
🞆 If one operand is a float, the entire
expression is promoted to float.
🞆 If any of the operands is double, the result
is double.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
[Link]("result = " + result);
}
}
🞆 Types of Operators in Java
🞆 There are multiple types of operators in Java all
are mentioned below:
🞆 Arithmetic Operators
🞆 Unary Operators
🞆 Assignment Operator
🞆 Relational Operators
🞆 Logical Operators
🞆 Ternary Operator
🞆 Bitwise Operators
🞆 1. Arithmetic Operators
🞆 They are used to perform simple arithmetic operations on primitive and non-
primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
🞆 Example:
import [Link].*;
class GFG {
public static void main (String[] args) {
int a = 10; int b = 3;
String num1 = "15"; String num2 = "25";
int a1 = [Link](num1);
int b1 = [Link](num2);
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));
[Link]("a1 + b1 = " + (a1 + b1)); } }
🞆 Unary Operators
🞆 Unary operators need only one operand. They are used to
increment, decrement, or negate a value.
– : Unary minus.
+ : Unary plus.
🞆 ++ : Increment operator, used for incrementing the value by 1.
There are two varieties of increment operators.
⚫ Post-Increment.
⚫ Pre-Increment
🞆 – – : Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operators.
⚫ Post-decrement
⚫ Pre-Decrement:
🞆 ! : Logical not operator, used for inverting a boolean value.
class GFG {
public static void main(String[] args) {
int a = 10; int b = 10;
[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));
[Link]("Postdecrement : " + (b--));
[Link]("Predecrement : " + (--b)); } }
🞆 Assignment Operator
🞆 ‘=’ Assignment operator is used to assign a value to any
variable. It has right-to-left associativity
🞆 variable = value;
🞆 In many cases, the assignment operator can be combined
with other operators to build a shorter version of the
statement
+=, -=, *= , /= , %=
class GFG {
public static void main(String[] args) {
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
}}
🞆 Relational Operators
🞆 These operators are used to check for relations like
equality, greater than, and less than. They return
boolean results after the comparison and are
extensively used in looping statements as well as
conditional if-else statements. The general format is,
🞆 Some of the relational operators are-
🞆 ==, !=, <, <=, >, >=
class GFG {
public static void main(String[] args) {
int a = 10; int b = 3; int c = 5;
[Link]("a > b: " + (a > b));
[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c)); } }
Logical Operators
🞆 These operators are used to perform “logical AND” and
“logical OR” operations, i.e., a function similar to AND
gate and OR gate in digital electronics Java also has
“Logical NOT”, which returns true when the condition
is false and vice-versa
Conditional operators are:
&&, ||, !
class GFG {
public static void main (String[] args) {
boolean x = true;
boolean y = false;
[Link]("x && y: " + (x && y));
[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x)); } }
Ternary operator
The ternary operator is a shorthand version of the if-else
statement. It has three operands and hence the name
[Link] general format is:
condition ? if true : if false
public class operators {
public static void main(String[] args) {
int a = 20, b = 10, c = 30, result;
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = " + result);
}}
🞆 Bitwise Operators
🞆 These operators are used to perform the
manipulation of individual bits of a number.
They can be used with any of the integer types.
🞆 &, Bitwise AND operator
🞆 |, Bitwise OR operator
🞆 ^, Bitwise XOR operator
🞆 ~, Bitwise Complement Operator
OPERATOR PRECEDENCE
🞆 var++, var--
🞆 +, - (Unary plus and minus), ++var,--var
🞆 (type) Casting
🞆 ! (Not)
🞆 *, /, % (Multiplication, division, and modulus)
🞆 +, - (Binary addition and subtraction)
🞆 <, <=, >, >= (Comparison)
🞆 ==, !=; (Equality)
🞆 & (Unconditional AND)
🞆 ^ (Exclusive OR)
🞆 | (Unconditional OR)
🞆 && (Conditional AND) Short-circuit AND
🞆 || (Conditional OR) Short-circuit OR
🞆 =, +=, -=, *=, /=, %= (Assignment operator)
public class operators {
public static void main(String[] args) {
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
[Link]("a+b/d = " + (a + b / d));
[Link]("a+b*d-e/f = " + (a + b * d - e / f)); } }