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

Unit 1

Uploaded by

Mannered Zone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Unit 1

Uploaded by

Mannered Zone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

OOPS THROUGH JAVA M.

RAMACHANDRA DEPT OF CSE


HISTORY OF JAVA:

OBJECT ORIENTED PROGRAMMING PRINCIPLES:


1. Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc.
It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of each other's data or code. The only
necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging
the tail, barking, eating, etc.
2. Class

Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which
you can create an individual object. Class doesn't consume any space.
3. Inheritance
Inheritance are of 5 types.

1.Single Inheritance
2.Hierarchial Inheritance
3.Multilevel Inheritance
4.Hybrid Inheritance
5.Multiple Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
4. Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
5. Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't
know the internal processing. In Java, we use abstract class and interface to achieve abstraction.
6. Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the
fully encapsulated class because all the data members are private here.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
7. Coupling

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are
aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we
use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can
use interfaces for the weaker coupling because there is no concrete implementation.
8. Cohesion

Cohesion refers to the level of a component which performs a single well–defined task. A single well–defined
task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts.
The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the
java.util package is a weakly cohesive package because it has unrelated classes and interfaces.
9. Association

Association represents the relationship between the objects. Here, one object can be associated with one object
or many objects. There can be four types of association between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Let's understand the relationship with real–time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have
one prime minister (many to one), and many ministers can have many departments (many to many).
Association can be unidirectional or bidirectional.
10. Aggregation

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains
other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has– a
relationship in Java. Like, inheritance represents the is–a relationship. It is another way to reuse objects.
11. Composition

The composition is also a way to achieve Association. The composition represents the relationship where one
object contains other objects as a part of its state. There is a strong relationship between the containing object and
the dependent object. It is the state where containing objects do not have an independent existence. If you delete
the parent object, all the child objects will be deleted automatically.
12. Dynamic binding

Dynamic binding is slower than static binding because it occurs in runtime and spends some time to find out
actual method to be called. That's all on difference between static and dynamic binding in java. Bottom line is
static binding is a compile time operation while dynamic binding is a runtime.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
13. Multithreading

Multithreading in java is a process of executing multiple threads simultaneously. A thread is a lightweight sub–
process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve
multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context–switching between the threads takes
less time than process.

IMPORTANCE OF JAVA TO INTERNET:


Applications: An application is a program that runs on our Computer under the operating system of that
computer. It is more or less like one creating using C or C++. Java’s ability to create Applets makes it important.

Applet: An Applet is an application designed to be transmitted over the Internet and executed by a Java
compatible web browser. An applet is actually a tiny Java program, dynamically downloaded across the
network, just like an image. But the difference is it is an intelligent program, not just a media file. It can react to
the user input and dynamically change.

BYTE CODE

What is Java Byte code?


Java byte code is the instruction set for the Java Virtual Machine. It acts similar to an assembler which is an
alias representation of a C++ code. As soon as a java program is compiled, java byte code is generated. In more
apt terms, java byte code is the machine code in the form of a .class file. With the help of java byte code we
achieve platform independence in java.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
ADVANTAGE OF JAVA BYTE CODE
Platform independence is one of the soul reasons for which James Gosling started the formation of java and it
is this implementation of byte code which helps us to achieve this. Hence byte code is a very important
component of any java program. The set of instructions for the JVM may differ from system to system but all
can interpret the byte code. A point to keep in mind is that byte codes are non–runnable codes and rely on the
availability of an interpreter to execute and thus the JVM comes into play.
JAVA FEATURES

The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as java buzzwords.

A list of most important features of Java language is given below.


1. Simple
2. Object–Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely–used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.
Object–oriented
Java is an object–oriented programming language. Everything in Java is an object. Object–oriented means we
organize our software as a combination of different types of objects that incorporates both data and behavior.
Object–oriented programming (OOPs) is a methodology that simplifies software development and maintenance
by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Portable
o Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require
any implementation.

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

Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled
into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware
or software environment in which a program runs.
There are two types of platforms software–based and hardware–based. Java provides a software–based
platform.
The Java platform differs from most other platforms in the sense that it is a software–based platform that runs
on the top of other hardware–based platforms. It has two components:
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code
is compiled by the compiler and converted into byte code. This byte code is a platform–independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus–free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to load
Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for
the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the
local disk.
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java
robust.
Architecture–neutral
o Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.
o In C programming, int data type occupies 2 bytes of memory for 32–bit architecture and 4 bytes of
memory for 64–bit architecture. However, it occupies 4 bytes of memory for both 32 and 64–bit
architectures in Java.
High–performance
o Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
o Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Multi–threaded
o A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi–threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi–
media, Web applications, etc.
Dynamic
o Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
o Java supports dynamic compilation and automatic memory management (garbage collection).

METHODS IN JAVA:
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as functions.
 Why use methods? To reuse code: define the code once, and use it many times.

A method must be declared within a class. It is defined with the name of the method, followed by parentheses
(). Java provides some pre–defined methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:

Example
Create a method inside MyClass:
public class MyClass {
static void myMethod() {
// code to be executed
}
}
Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the MyClass class and not an object of the MyClass class. You
will learn more about objects and how to access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn more about return values later
in this chapter

Example 2
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
Output:
I just got executed!
I just got executed!
I just got executed!
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
CLASSES AND OBJECTS IN JAVA

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life
entities.
Class
A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can include
these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends.
A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma–separated list of interfaces implemented by the class, if any, preceded by
the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Object
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program
creates many objects, which as you know, interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object with other
objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.

INSTANCE VARIABLES IN JAVA :

A variable is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
 In Java, all the variables must be declared before use.
 We can declare variables in java as follows:
 datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
DATA TYPES IN JAVA:
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE

EXAMPLE:
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
ARRAYS IN JAVA:
Normally, an array is a collection of similar type of elements which have a contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are
stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array. Array in Java is index–based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OUTPUT:
10
20
70
40
50
EXAMPLE 2:
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}

OUTPUT:
10
30
50
90
60
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
CONTROL STATE MENTS:

Decision Making in Java


Decision making statements are statements which decides what to execute and when. They are similar to
decision making in real time. Control flow statements control the flow of a program’s execution. Here flow of
execution will be based on state of a program. We have 4 decision making statements available in Java.
Simple if Statement
Simple if statement is the basic of decision–making statements in Java. It decides if certain amount of code
should be executed based on the condition.
Syntax:

if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false

Example:
class ifTest
{ public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
}

Output:
After if statement
if…else Statement
In if…else statement, if condition is true then statements in if block will be executed but if it comes out as false
then else block will be executed.
Syntax:

if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}

Example:
class ifelseTest
{ public static void main(String args[])
{ int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}

Output:
i is less than 10
After if else statement

Nested if statement
Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside
another if…else statement.
Syntax:

if (condition1) {
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Statemen 1; //executed when condition1 is true
if (condition2) {
Statement 2; //executed when condition2 is true
}
else {
Statement 3; //executed when condition2 is false
}
}

Example:
class nestedifTest
{
public static void main(String args[])
{ int x = 25;
if (x >
10)
{
if (x%2==0)
System.out.println("i is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else
{
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
}
}

Output:
i is greater than 10 and odd number After nested if statement
if...else if…else statement
if…else if statements will be used when we need to compare the value with more than 2 conditions. They are
executed from top to bottom approach. As soon as the code finds the matching condition, that block will be
executed. But if no condition is matching then the last else statement will be executed.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Syntax:
if (condition2) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
<span style="white–space:pre"> </span>Statement 2; // if condition2 becomes true then this will be executed
}
.
.
else {
Statement 3; //executed when no matching condition found
}

Example:
class ifelseifTest
{
public static void main(String args[])
{
int x = 2;

if (x > 10)
{
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else
{
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Output:
i is less than 10
After if else if ladder statement

Switch statement
Java switch statement compares the value and executes one of the case blocks based on the condition. It is same
as if…else if ladder. Below are some points to consider while working with switch statements:
 case value must be of the same type as expression used in switch statement
 case value must be a constant or literal. It doesn’t allow variables
 case values should be unique. If it is duplicate, then program will give compile time error
Let us understand it through one example.

class switchDemo{
public static void main(String args[]){
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Looping Statements in Java
Looping statements are the statements which executes a block of code repeatedly until some condition meet to
the criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.
While
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the
body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a
Boolean expression. If int or string is used instead, compile will give the error.

Syntax:

while (condition)
{
statement1;
}

Example:
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}

Output:
1
3
5
7
9

Do…while
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Do…while works same as while loop. It has only one difference that in do…while, condition is checked after the
execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of
loop will be executed at least once before checking the condition
Syntax:

do{
statement1;

}while(condition);
Example: here
class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;
do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}

Output:
10
For
It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as
initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is
easy to debug structure in Java.
Syntax:

for (initialization; condition; increment/decrement)


{
statement;
}

Example:
class forLoopTest
{
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}

Output:

1
2
3
4
5

For–Each Loop
For–Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.
Example:

class foreachDemo{
public static void main(String args[]){
int a[] = {10,15,20,25,30};
for (int i : a) {
System.out.println(i);
}
}

Output:

10
15
20
25
30

BRANCHING STATEMENTS IN JAVA


OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Branching statements jump from one statement to another and transfer the execution flow. There are 3
branching statements in Java.
Break
Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in
loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the
innermost loop.
Example:

class breakTest
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}

Output:
0
1
2
3
4
After loop

Continue
Continue statement works same as break but the difference is it only comes out of loop for that iteration and
continue to execute the code for next iterations. So it only bypasses the current iteration.
Example:

class continueTest
{
public static void main(String args[])
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
// only even numbers will be printed
System.out.print(j + " ");
}
}
}

Output:
02468

Return
Return statement is used to transfer the control back to calling method. Compiler will always bypass any
sentences after return statement. So, it must be at the end of any method. They can also return a value to the
calling method.
Example: Here method getwebURL() returns the current URL to the caller method.

public String getwebURL()


{
String vURL= null;
try {
vURL= driver.getCurrentUrl();
}
catch(Exception e) {
System.out.println("Exception occured while getting the current url : "+e.getStackTrace());
}
return vURL;
}

SIMPLE JAVA PROGRAMS:


1.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
}
}

OUTPUT: Hello Java


Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in java.
o public keyword is an access modifier which represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the object of PrintStream
class, println() is the method of PrintStream class. We will learn about the internal working of
System.out.println statement later.

Example: How to Print an Integer entered by an user


import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Creates a reader instance which takes
// input from standard input – keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
// nextInt() reads the next integer from the keyboard
int number = reader.nextInt();
// println() prints the following line to the output screen
System.out.println("You entered: " + number);
}
}

OUTPUT: Enter a number: 10


You entered: 10

Example: Program to Add Two Integers


OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
1. public class AddTwoIntegers {
2.
3. public static void main(String[] args) {
4.
5. int first = 10;
6. int second = 20;
7.
8. int sum = first + second;
9.
10. System.out.println("The sum is: " + sum);
11. }
12. }

OUTPUT :

13. Enter two numbers: 10 20


14. The sum is: 30

EXAMPLE: Check whether a number is even or odd using if...else statement


1. import java.util.Scanner;
2.
3. public class EvenOdd {
4.
5. public static void main(String[] args) {
6.
7. Scanner reader = new Scanner(System.in);
8.
9. System.out.print("Enter a number: ");
10. int num = reader.nextInt();
11.
12. if(num % 2 == 0)
13. System.out.println(num + " is even");
14. else
15. System.out.println(num + " is odd");
16. }
17. }

OUTPUT :

Enter a number: 12
12 is even

EXAMPLE: Check whether a number is even or odd using ternary operator


1. import java.util.Scanner;
2.
3. public class EvenOdd {
4.
5. public static void main(String[] args) {
6.
7. Scanner reader = new Scanner(System.in);
8.
9. System.out.print("Enter a number: ");
10. int num = reader.nextInt();
11.
12. String evenOdd = (num % 2 == 0) ? "even" : "odd";
13.
14. System.out.println(num + " is " + evenOdd);
15.
16. }
17. }

OUTPUT :

Enter a number: 13
13 is odd
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
CONSTRUCTORS IN JAVA:
Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of
statements (i.e. instructions) that are executed at time of Object creation.
Rules for writing Constructor:
 Constructor(s) of a class must has same name as the class name in which it resides.
 A constructor in Java cannot be abstract, final, static and synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other class can
call the constructor.
TYPES OF CONSTRUCTORS:

No–argument constructor or Default constructor: A constructor that has no parameter is known as default
constructor. If we don’t define a constructor in a class, then compiler creates default constructor (with no
arguments) for the class. And if we write a constructor with arguments or no–arguments then the compiler
does not create a default constructor. Default constructor provides the default values to the object like 0, null, etc.
depending on the type.

Example:
// Java Program to illustrate calling a
// no–argument constructor
import java.io.*;
class Geek
{
int num;
String name;
// this would be invoked while an object
// of that class is created.
Geek()
{
System.out.println("Constructor called");
}
}
class GFG
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}

Output :
Constructor called
null
0

Example 2:
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor

Parameterized constructor
Constructor with arguments (or you can say parameters) is known as Parameterized constructor.
Example :

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
}
}
Output :
Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD IN JAVA:

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or may not be
same as the class name.

CONSTRUCTOR OVERLOADING:
Constructor overloading is a concept of having more than one constructor with different parameters list, in
such a way so that each constructor performs a different task. In Java, a constructor is just like a method but
without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique
of having more than one constructor with different parameter lists. They are arranged in a way that each
constructor performs a different task. They are differentiated by the compiler by the number of parameters in
the list and their types.

Example :
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

ACCESS CONTROLS IN JAVA:

There are two types of modifiers in Java: access modifiers and non–access modifiers.
The access modifier in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non–access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.

Example
Private access rule:

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile–time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple1{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Output : compile time error

DEFAULT ACCESS RULE:

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Note: In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

Protected

 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
 It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so
can be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
B obj = new B();
obj.msg();
}
}
Output : Hello
Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier.
EXAMPLE :
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
OUTPUT : Hello
THIS KEYWORD:

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current
object.

Usage of java this keyword:


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Example:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output : 0 null 0.0


0 null 0.0

Example2:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output: 111 ankit 5000
112 sumit 6000

METHOD OVERLOADING IN JAVA:


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading. If we have to perform only one operation, having same name of the methods increases the
readability of the program. Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.

Advantage of method overloading:


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

Example1:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Output: 22
33
Example2:
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output: 22
24.9

Java Garbage Collection in java:


 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it
is a way to destroy the unused objects.
 To do so, we were using free () function in C language and delete () in C++. But, in java it is performed
automatically. So, java provides better memory management.

ADVANTAGE OF GARBAGE COLLECTION

o It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Example1: public class TestGarbage1{


public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Output: object is garbage collected
object is garbage collected
String Handling Functions:
String Class in Java
It is a predefined class in java.lang package can be used to handle the String. String class is immutable that
means whose content can not be changed at the time of execution of program. String class object is immutable
that means when we create an object of String class it never changes in the existing object.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output
Java Explanation: Here we cannot change the object of String class so output is only java not java software.

Methods of String class


length()
length(): This method is used to get the number of character of any string.
Example
class StringHandling
{
public static void main(String arg[])
{
int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output Length:
4
charAt(index):
charAt(): This method is used to get the character at a given index value.
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE

Example
class StringHandling
{
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output
Character: v
toUpperCase()
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output
String: JAVA
toLowerCase()
toLowerCase(): This method is used to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
Output : String: java
concat()
concat(): This method is used to combined two string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
System.out.println("Combined String: "+s1.concat(s2));
}
}
Output
Combined String: HiteshRaddy
equals()
equals(): This method is used to compare two strings, It return true if strings are same otherwise return false. It
is case sensitive method.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}
Output
Compare String: false
Compare String: true

equalsIgnoreCase()
equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of both strings are
same otherwise false.
Example
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
String s3="Raddy";
System.out.println("Compare String: "+s1.equalsIgnoreCase(s2));
System.out.println("Compare String: "+s1.equalsIgnoreCase(s3));
}
}
Output
Compare String: true
Compare String: false
compareTo()
compareTo(): This method is used to compare two strings by taking unicode values, It return 0 if the string are
same otherwise return +ve or –ve integer values.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
Strings are not same
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE

compareToIgnoreCase()
compareToIgnoreCase(): This method is case insensitive method, which is used to compare two strings similar
to compareTo().
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
Strings are same
startsWith()
startsWith(): This method return true if string is start with given another string, otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
true
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
endsWith()
endsWith(): This method return true if string is end with given another string, otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output true
subString()
subString(): This method is used to get the part of given string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
indexOf()
indexOf(): This method is used find the index value of given string. It always gives starting index value of first
occurrence of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output
8
lastIndexOf()
lastIndexOf(): This method used to return the starting index value of last occurence of the given string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Java is programming language";
String s2="Java is good programming language";
System.out.println(s1.lastIndexOf("programming"));
System.out.println(s2.lastIndexOf("programming"));
}
}
Output
8
13
trim()
trim(): This method remove space which are available before starting of string and after ending of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
OOPS THROUGH JAVA M.RAMACHANDRA DEPT OF CSE
System.out.println(s.trim());
}
}
Output
Java is programming language
split()
split(): This method is used to divide the given string into number of parts based on delimiter (special symbols
like @ space , ).
Example
class StringHandling
{
public static void main(String arg[])
{
String s="[email protected]";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{
System.out.println(c);
}
}
}
Output
contact
@tutorial4us.com
replace()
replace(): This method is used to return a duplicate string by replacing old character with new character.
Note: In this method data of original string will never be modify.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="java";
String s2=s1.replace('j', 'k');
System.out.println(s2);
}
}
Output : kava

You might also like