OOPs (Object Oriented Programming System)
Introduction to Java
C Lan is basic programming language
C++ is a Procedural Oriented programming language
Java is a high-level, object-oriented programming language.
James Gosling developed at Sun Microsystems in 1995.
In 2009, Oracle
Corporation acquired it.
Key Features of Java
1.
Platform Independent: Java is famous for its Write Once, Run Anywhere
(WORA) feature.
2.
Object-Oriented:
Java follows the object-oriented programming. This makes code clean and
reusable.
3.
Multithreading: Java programs can do many things at
the same time using multiple threads.
Java
is a collection of Objects and classes.
Object
Object means a real word entity.
Any entity that has state and behaviour is known as an object. For example: chair, pen,
table, keyboard, bike etc. as well as Opening bank account, Movie
Reservation, etc..,,, It can be physical and logical.
Key characteristics of a Java object:
Instance of a Class:
An object is
created from a class, which acts as a blueprint or template defining the
object's structure and behavior.
State (Attributes/Fields):
An object
possesses state, represented by its attributes or fields. These store data
specific to that particular object. For example, a "Car" object
might have attributes like "color," "make," and
"model."
Behaviour (Methods):
Objects also
exhibit behavior, defined by methods within their class. These methods
encapsulate the actions an object can perform or the operations that can be
performed on it. For instance, a "Car" object could have methods
like startEngine(), accelerate(), or brake().
Collection of objects is called class. It is a
logical entity.
4 Pillars of Java –
1.
Abstraction
2.
Encapsulation
3.
Inheritance
4.
Polymorphism
Compilation and
Execution:
C++: Compiled directly
into machine code, making it platform-dependent. The compiled code runs
directly on the specific hardware and operating system for which it was
compiled.
Java: Compiled into
bytecode, which is then interpreted by the Java Virtual Machine
(JVM). This bytecode can run on any system with a compatible JVM, making
Java platform-independent ("Write once, run anywhere").
Object-Oriented Features:
C++: Supports
both procedural and object-oriented programming paradigms. It allows
multiple inheritance.
Java: Primarily
an object-oriented language. It does not support multiple inheritance of
classes (though it supports multiple inheritance of interfaces).
We write a
program in .java file, and once we compile we get .class file. That which is
nothing but an Byte code. And this
class file we can execute in any OS. This is platform independent as well Java
is much secured.
Importance of : JDK, JVM, JRE
Features of Java
https://www.tpointtech.com/features-of-java
Features of Java
Below is a list of the
most important features of the Java language.
- Simple
- Object-Oriented
- Portable
- Platform Independent
- Secured
- Robust
- Architecture Neutral
- Interpreted
- High Performance
- Multithreaded
- Distributed
- Dynamic
Basic Program structure in Java
class Program1
{
public
static void main(String args[])
{
System.out.println("Welcome
to the world");
}
}
class Program2
{
{
int
a = 25, b = 25, marks=50;
String
result;
final
int minimumbal = 1000;
if(a%2==0)
{
System.out.println("The
number" +a +"is even
num");
}
else
{
System.out.println("The
number :" +a +" is odd
num");
}
/* if(marks>40)
{
result
= "Pass";
System.out.println(result);
}
else
{
result
= "fail";
System.out.println(result);
} */
result
= (marks>40) ? "Exam Pass" : "Exam Fail" ;
System.out.println(result);
}
}
Tokens in Java
https://www.geeksforgeeks.org/java/java-tokens/
Tokens are the smallest
elements of a program that is meaningful to the compiler. They are also known
as the fundamental building blocks of the program. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
1. Keywords
Keywords are pre-defined or
reserved words in a programming language. Each keyword is meant to perform a
specific function in a program. Since keywords are referred names for a compiler,
they can’t be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed.
2. Identifiers
Identifiers are used as the general terminology
for naming of variables, functions and arrays. These are user-defined names
consisting of an arbitrarily long sequence of letters and digits with either a
letter or the underscore (_) as a first character.
Ex:- int AbC, ABC, abc, a, i, a1, a2, _a, $a, cse_b,
cse566,
3. Constants/Literals
Constants are also like normal variables. But
the only difference is, their values cannot be modified by the program once
they are defined. Constants refer to fixed values. They are also called as
literals. Constants may belong to any of the data type. Syntax:
final data_type variable_name;
final double PI = 3.14; // Use double instead of int
// Example
usage of PI
System.out.println("The value of PI is: " + PI);
Operators
https://www.geeksforgeeks.org/java/java-relational-operators-with-examples/
Java provides many types of operators which can
be used according to the need. They are classified based on the functionality
they provide. Some of the types are-
1)
Precedence
and Associativity
1. Precedence and Associativity
Precedence tells us which operators should be evaluated first, while
associativity determines the direction (left to right or right to left)
// Precedence and associativity applied here
Ex:- 10 + 20 * 30
res = a + b * c / 2;
These operators involve the mathematical operators that can
be used to perform various simple or advanced arithmetic operations on the
primitive data types referred to as the operands.
This are to perform any
operation like increment, decrement, negation, etc.
Operator 1: Unary minus(-)
This operator can be used to convert a positive
value to a negative one.
int n1 = 20;
// Printing the above
variable
System.out.println("Number = " + n1);
// Performing unary
operation
n1 = -n1;
// Printing the above
result number
// after unary operation
System.out.println("Result = " + n1);
Output
Number = 20
Result = -20
Operator 2: 'NOT' Operator(!)
This is used to convert true to false or vice
versa. Basically, it reverses the logical state of an operand.
cond = !true;
// cond < false
System.out.println("!(a < b) = " + !(a <
b));
System.out.println("!(a > b) = " + !(a > b));
Output
!(a < b) = true
!(a > b) = false
Operator 3: Increment(++) & Decrement (--)
3.1: Post-increment operator
int x = 10, a;
a = x++;
Output
x = 11
Assigning x to a with Post Incrementation
a = 10, x = 11
3.2: Pre-increment operator
int y = 20, p;
p = ++y;
Output
y = 20
Assigning x to a with Post Incrementation
p = 21, y = 21
4. Assignment Operator
'=' Assignment operator is used to assign a value to any variable.
For example, a += 5 replaces a
= a + 5. Common compound operators include:
·
+= , Add and assign.
·
-= , Subtract and assign.
·
*= , Multiply and assign.
·
/= , Divide and assign.
·
%= , Modulo and assign.
4.
Relational Operators
Relational Operators are used to check for relations like
equality, greater than, and less than.
Relational operators compare
values and return Boolean results:
·
== , Equal to.
·
!= , Not equal to.
·
< , Less than.
·
<= , Less than or equal to.
·
> , Greater than.
·
>= , Greater than or equal to.
Logical operators are
used to perform logical "AND", "OR", and "NOT" operationsUsed extensively to test
for several conditions for making a decision.
AND Operator (&&): If( a && b ) [if true
execute else don't]
OR Operator (||): If( a || b) [if one of them is true to
execute; else don't]
NOT Operator (!): !(a<b) [returns false if a is smaller
than b]
Java
ternary operator is the only conditional operator that takes three operands.
It’s a one-liner replacement for the if-then-else statement and is used a lot
in Java programming. We can use the ternary operator in place of if-else
conditions or even switch conditions using nested ternary operators.
Note: Ternary
Operator improves the code readability.
Syntax of Ternary Operator
variable = Expression1 ? Expression2:
Expression3
Note:
·
If Expression1 is true, Expression2 is
executed
·
If Expression1 is false, Expression3 is
executed.
Ex:-
Int marks = 50;
result = (marks>40) ? "Exam Pass" : "Exam
Fail" ;
int age = 25;
bool isAdult = age > 18 ? true : false;
Bitwise
operators are used to perform operations at the bit level. These
operators are useful when we work with low-level programming
1. Bitwise AND (&)
This
operator is a binary operator, denoted by '&.' It returns bit by bit AND of
input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
2. Bitwise OR (|)
This
operator is a binary operator, denoted by '|'. It returns bit by bit OR of
input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
________
0111 = 7 (In decimal)
3. Bitwise XOR (^)
This
operator is a binary operator, denoted by '^.' It returns bit by bit XOR of
input values, i.e., if corresponding bits are different, it gives 1, else it
shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise
Complement (~)
This
operator is a unary operator, denoted by '~.' It returns the one's complement
representation of the input value, i.e., with all bits inverted, which means it
makes every 0 to 1, and every 1 to 0.
Example:
a = 5 = 0101 (In Binary)
Bitwise Complement Operation of 5 in java
(8 bits)
~ 00000101
________
11111010 = -6 (In decimal)
Scanner
Class
The Scanner class is used to get user input, and it is
found in the java.util package.
Example Program:-
import java.util.*;
class InputOutput
{
public
static void main(String args[])
{
int
marks;
float
abc;
Scanner
sc = new Scanner(System.in);
System.out.println("Enter
marks : ");
marks
= sc.nextInt();
result
= (marks>40) ? "Exam Pass" : "Exam Fail" ;
System.out.println(result);
}
}
Default Values
int, byte, short, long = 0 default value
float, double = 0.0 default value
Char = null default value
Boolean = false
default value
“Lang” is the
default package in Java
“Object” is
the default class in Java
Declaration
of variables
int myNum = 5; short
s = 200, byte b = 300, long myNum =
15000000000L;
float myFloatNum = 5.99f; double myNum = 19.99d;
char myLetter = 'D';
String myText = "Hello";
boolean myBool = true;
Formatting Using Java
Printf() in the package of io
Number Formatting
int a=10000;
sop(a);
System.out.printf("%d",a);
Output
10,000
Decimal Number Formatting
double a = 3.14159265359d
System.out.printf("%f\n", a); // default It prints 6 digtis
System.out.printf("%5.3f\n", a);
Output
3.141593
3.142
Boolean Formatting
int a = 10;
Boolean b = true, c = false;
Integer d = null;
System.out.printf("%b\n",
a); // output :
true
System.out.printf("%B\n", b); //
output : TRUE
System.out.printf("%b\n",
c); // output :
false
System.out.printf("%B\n", d); //
output : FALSE
Char & String
Formatting
char c = 'g';
System.out.printf("%c\n", c); // output : g
System.out.printf("%C\n", c); //
output : G
String str = "india";
System.out.printf("%s \n", str); // output : india
System.out.printf("%S \n", str); // output : INDIA
Date and Time Formatting
Date time = new Date();
System.out.printf("Current Time: %tT\n", time); //Output
: Current Time: 05:25:43
%tT, %tH, %tM, %tS // Try in
lab wats the Output comes for this syntax.
Type
Casting
In Java, typecasting is the one process of
converting data type to another data type using the casting operator.
There are two types of Type Casting in Java:
·
Implicit/Automatic
·
Explicit/Manual
Implicit/Automatic
This is converting a smaller data type
to a larger data type where no chance of data loss, it is secure.
·
The
Java compiler performs this conversion automatically.
·
The
main imp things to consider:
ü The target type must be
larger than the source type.
ü Both data types must be
compatible with each other.
Example2.java
class Casting
{
public static
void main(String args[])
{
byte
b = 100;
int
a = b; // Implicit
int
z = 200;
byte
p = (byte)z; // Explicit
int
y = 20;
float
f = 34.5f, g = y;
//int
r = (int) f;
System.out.println("Value
is : "+g);
}
}
Explicit/Manual
This is converting a larger data type to a smaller data
type where data loss is possible and it is unsafe.
ü The
programmer must explicitly perform this conversion using a cast operator (targetDataType)
Scope
of Variables
1.
Member variables / Instance variables
2.
Local variables
3.
Static variables / Class variables
Member variables
These variables must be declared
inside a class but outside of all the functions/methods.
Variables declared inside a method
have method level scope and can't be accessed outside the method.
Static variables
A static variable is associated with a class rather than
an instance. A static field is declared using the static
keyword. This are declared with the static keyword in a
class, but outside a method,
This variables we call with ClassName.VariableName
Program: 1
Program: 2
Program: 3
class lbrce
{
int p =
500;
}
class Scope
{
static
int a = 253 ;
void
hello()
{
float
f = 34.5f; // local variables
}
public
static void main(String args[])
{
lbrce
l = new lbrce();
System.out.println("Value
from lbrce class : "+l.p);
}
}
Program: 4
class lbrce
{
static
int p = 500;
}
class Scope
{
static
int a = 253 ;
void
hello()
{
float
f = 34.5f; // local variables
}
public
static void main(String args[])
{
lbrce
l = new lbrce();
System.out.println("Value
from lbrce class : "+lbrce.p);
}
}
Importance of String args[] in main
method
class Demo1
{
public
static void main(String args[])
{
if(args.length
> 0)
{ String file = args[0];
System.out.println("Processing
the file "+file);
}
else
{
System.out.println("No file processing"); }
}
}
/*
Command line:
If we want to pass some data to main program from cmd prompt
we
have a option of "String args"
for(String x : args)
{ System.out.println("Display
data "+x); }
*/
https://www.tpointtech.com/control-statements-in-java
Control Statements in Java
Java
compiler executes the code from top to bottom. The statements
in the code are executed according to the order in which they appear.
However, Java provides statements that can be used to
control the flow of Java code. Such statements are called control flow
statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Java provides three
types of control flow statements.
- Decision
Making statements
- if statements
- switch statement
- Loop statements
- do
while loop
- while
loop
- for
loop
- for-each
loop
- Jump statements
- break statement
- continue statement
Static
Features of Static
·
The static keyword in Java is mainly used for memory managementmanagement
·
We can call static variables & static
methods without creating a object
o
ex:-
classname.staticvariable
or classname.staticmethod
·
A static method or static variable is associated
with the class, not with any object or instance.
·
static methods can access static variables
directly without the need for an object.
·
They cannot access non-static variables
(instance) or methods directly.
·
static memory shares common memory ie..,, static
pool
Example program :
1
class Scope
{
static int a = 100
; // Member
variables / Instance variables
void hello()
{
float
f = 34.5f; // local variables
System.out.println("Value
is : "+f);
}
public static void
main(String args[])
{
Scope
s = new Scope();
System.out.println("Value
is : "+a);
}
}
Example program : 2
class StaticExp1
{
int z = 10; // static variables or methods
we call by classname.varname
static int p =
100; // StaticExp1.p
static void
hello() // StaticExp1.hello()
{
sop;
}
}
class StaticExp2
{
public static void
main(String[] arg)
{
System.out.println("Static
Example Program");
StaticExp1
s1 = new StaticExp1();
System.out.println("value
:"+s1.z+" p value:
"+StaticExp1.p);
}
}
Diff btwn For & while loop
When we know exactly how many times the loop has to repeat
than we go to "for" loop.
eg:- to display all 70 class students names
When we dnt know how many times the loop has to repeat than
we go to "while" loop.
eg:- to display student names who got Distinction
No comments:
Post a Comment