JAVA UNIT-I-part-1
JAVA UNIT-I-part-1
JAVA
R 20 OOPS THROUGH JAVA
UNIT – I
OBJECT ORIENTED THINKING
Encapsulation
Encapsulation is the process of combining data and code into a single unit
(object / class). In OOP, every object is associated with its data and code. In
programming, data is defined as variables and code is defined as methods. The
java programming language uses the class concept to implement encapsulation.
Polymorphism
Polymorphism is the process of defining same method with different
implementation. That means creating multiple methods with different
behaviours. The java uses method overloading and method overriding to
implement polymorphism. Method overloading - multiple methods with same
name but different parameters. Method overriding - multiple methods with same
name and same parameters.
Abstraction
Abstraction is hiding the internal details and showing only essential
functionality. In the abstraction concept, we do not show the actual
implementation to the end user, instead we provide only essential things. For
example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how
music system works? etc.
OVERVIEW OF JAVA
Java is a computer programming language. Java was created based on C
and C++. Java uses C syntax and many of the object-oriented features are taken
from C++. Before Java was invented there were other languages like COBOL,
FORTRAN, C, C++, Small Talk, etc. These languages had few disadvantages
which were corrected in Java. Java also innovated many new features to solve
History of Java :
• The C language developed in 1972 by Dennis Ritchie had taken a decade to
become the most popular language.
• In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language
with included OOP fundamentals and features.
• A project named “Green” was initiated in December of 1990, whose aim was
to create a programming tool that could render obsolete the C and C++
programming languages.
• Finally in the year of 1991 the Green Team was created a new Programming
language named “OAK”.
• After some time they found that there is already a programming language with
the name “OAK”.
• So, the green team had a meeting to choose a new name. After so many
discussions they want to have a coffee. They went to a Coffee Shop which is
just outside of the Gosling’s office and there they have decided name as
“JAVA”.
Applications:
There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone Application
Standalone applications are also known as desktop applications or
window-based applications. These are traditional software that we
need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic
page is called a web application. Currently, Servlet, JSP, Struts,
Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking
applications, etc. is called enterprise application. It has advantages
of the high-level security, load balancing, and clustering. In Java,
EJB is used for creating enterprise applications.
4) Mobile Application
4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user
interface API.
CLASS IN JAVA
The class is at the core of Java. It is the logical construct upon
which the entire Java language is built because it defines the shape
and nature of an object. As such, the class forms the basis for object-
oriented programming in Java. Any concept you wish to implement
in a Java program must be encapsulated within a class. Because the
class is so fundamental to Java.
Syntax:
class <class_name>{
Variables;
method;
}
When you define a class, you declare its exact form and nature. You do
this by specifying the data that it contains and the code that operates on
that data. While very simple classes may contain only code or only
data, most real-world classes contain both.
type
methodname1(parameter
-list) { // body of method
}
type
methodname2(parameter
-list) { // body of method
}
// ...
type
methodnameN(parameter
-list) { // body of method
}
}
CREATING AN OBJECT
JAVA METHODS
Creating a method
A method is created inside the class and it may be created with any access
specifier. However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
🔔 The methodName must begin with an alphabet, and the Lower-case letter is
preferred.
🔔 The methodName must follow all naming rules.
🔔 If you don't want to pass parameters, we ignore it.
🔔 If a method defined with return type other than void, it must contain the
return statement, otherwise, it may be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it
belongs and a dot operator. It may call directly if the method defined with the
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted
• High performance
• Distributed
• Dynamic
Simple
Portable
Portability is one of the core features of java which enables the java programs to
run on any computer or operating system. For example, an applet developed
using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism, and many more.
Architecture-neutral (or) Platform Independent
Java has invented to archive "write once; run anywhere, any time, forever". The
java provides JVM (Java Virtual Machine) to to archive architectural-neutral or
platform independent. The JVM allows the java program created using one
operating system can be executed on any other operating system.
Multi-threaded
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
Example:
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
Example:
Example:
float f1 = 234.5f
double d1 = 12.3
Example:
In java, non-primitive data types are the reference data types or user-created
data types. All non-primitive data types are implemented using object concepts.
Every variable of the non-primitive data type is an object. The non-primitive
data types may use additional methods to perform certain operations. The
default value of non-primitive data type variable is null. In java, examples of
non-primitive data types are String, Array, List, Queue, Stack, Class, Interface,
etc.
JAVA VARIABLES
A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.
Syntax:
• Local variables
• Final variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
3) Static variable
Example:
1. public class A
4) Final variable
A final variable is a variable that declared using final keyword. The final
variable is initialized only once, and does not allow any method to change it's
value again. The variable created using final keyword acts as constant. All
variables like local, instance, and static variables can be final variables. Let's
look at the following example java program to illustrate final variable in java.
JAVA ARRAYS
Examples:
//Java Program to illustrate the use of declaration, instantiation and initialization
of Java array in a single line
1. class Testarray1{
2. public static void main(String args[]){
3. int a[]={33,3,4,5};//declaration, instantiation and initialization
4. //printing array
5. for(int i=0;i<a.length;i++)//length is the property of array
6. System.out.println(a[i]);
7. }}
Multidimensional Array:
In java, we can create an array with multiple dimensions. We can
The above statement creates a two-dimensional array of three rows and two
columns.
Examples:
//Java Program to illustrate the use of multidimensional array
1. lass Testarray3{
2. public static void main(String args[]){
//declaring and initializing 2D array
3. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
4. //printing 2D array
5. for(int i=0;i<3;i++){
6. for(int j=0;j<3;j++){
7. System.out.print(arr[i][j]+" ");
8. }
[21] Syeda Sumaiya
Afreen
R 20 OOPS THROUGH JAVA
9. System.out.println();
10. }
11. }
}
JAVA OPERATORS
• Arithmetic Operqators
• Relational (or) Comparision Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
o negating an expression
Example: ++ and --
1. class OperatorExample{
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10 8. }}
Example :
1. class OperatorExample{
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0 10. }}
Example:
1. class OperatorExample{
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
Example:
1. class OperatorExample{
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
The bitwise & operator always checks both conditions whether first condition is
true or false.
Example: 1
1. class OperatorExample{
3. int a=10;
4. int b=5;
5. int c=20;
8. }}
The logical || operator doesn't check second condition if first condition is true. It
checks second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is
true or false.
Example:
1. class OperatorExample{
3. int a=10;
4. int b=5;
5. int c=20;
13. }}
Example:
1. class OperatorExample{
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Example:
1. class OperatorExample{
3. int a=10;
4. int b=20;
7. System.out.println(a);
8. System.out.println(b);
9. }}
JAVA EXPRESSIONS
Expression Types:
In the java programming language, expressions are divided into
THREE types. They are as follows.
• Infix Expression
• Postfix Expression
• Prefix Expression
Infix Expression :
The expression in which the operator is used between operands is
called infix expression.
The infix expression has the following general structure.
Example:
Example:
Prefix Expression:
The expression in which the operator is used before operands is
called a prefix expression.
The prefix expression has the following general structure.
Example:
• Jump Statements
1. simple if statement
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
if(condition) {
Consider the following example in which we have used the if statement in the java
code.
Student.java
Output:
x + y is greater than 20
2. if-else statement :
The if-else statement
is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
Student.java
Output:
x + y is greater than 20
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Student.java
Output:
Delhi
4. nested if statement :
if(condition 1) {
Student.java
Output:
Delhi
5. switch statement
In Java switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
switch
(expression) {
case value1:
// statement
sequence
break;
case value2:
// statement
sequence
break;
...
case valueN:
// statement
sequence
break;
default:
i is three.
i is greater
than 3. i is
greater
than 3.
while(condition){
//looping statements
}
Example Program:
1. Output:
2. Printing the list of first 10 even numbers
3.
4. 0
5. 2
6. 4
7. 6
8. 8
9. 10
10. Printin
Example:
Output:
Output:
Example:
Output:
Java
C
C++
Python
JavaScript
JUMP STATEMENTS
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution
control to the other part of the program.
In java, the jump statements are used to terminate a block or take the execution
control to the next iteration.
Java provides the following jump statements.
• break statement
• continue
• return
1. Break :
It is used to break the current flow of the program and transfer the control to the next
statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Output:
0
1
2
3
4
5
6
2. Continue : It skips the specific part of the loop and jumps to the next
iteration of the loop immediately. The continue statement is used to move the
execution control to the beginning of the looping statement. When the continue
statement is encountered in a looping statement, the execution control skips the
rest of the statements in the looping block and directly jumps to the beginning
of the loop. The continue statement can be used with looping statements like
while, do-while, for, and for-each.
3. Return : In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling
function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
🔔 Java allows the use of return-statement with both, with and without return
type methods. In java, the return statement used with both methods with and
without return type. In the case of a method with the return type, the return
statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return
type. But, when it is used without a return type, it does not carry any value.
Instead, simply transfers the execution control
return statement:
Syntax:
return;
(or)
return value; // value may be of any type
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method
4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)
6 String substring(int beginIndex, int It returns substring for given begin index and end index.
endIndex)
7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char value.
10 boolean equals(Object another) It checks the equality of string with the given object.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given index.
22 int indexOf(String substring, int It returns the specified substring index starting with given index.
fromIndex)
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.