Unit I
Unit I
• Object-oriented programming brings together data and its behavior (methods) into a single
entity (object).
• Many of the most widely used programming languages (such as C++, Java, Python etc.)
Features of object-oriented programming
• The basic concepts of OOP are as follows:
Object
Classes
Encapsulation
Inheritance
Polymorphism
Abstraction
Dynamic binding
Message Passing
CLASS
• Class is a collection of objects of similar
datatypes.
• For Example: quincy, sanjay,srimathi are
members(objects) of the class(II CSE B).
• Syntax: Class class_name
{………
}
• Example:
Secure:
• Java provides a secure means of creating Internet
applications and to access web applications.
• Java enables the construction of secured, virus-free.
Object Oriented:
• Java programming is pure object-oriented programming
language. Like C++, Java provides most of the object
oriented features.
Robust:
• Java encourages error-free programming by being
strictly typed and performing run-time checks.
Platform Independent:
• Unlike C, C++, when Java program is compiled, it is not
compiled into platform-specific machine code, rather it is
converted into platform independent code called bytecode.
• The Java bytecodes are not specific to any processor. They
can be executed in any computer without any error.
• Because of the bytecode, Java is called as Platform
Independent.
Portable:
• Java bytecode can be distributed over the
web and interpreted by Java Virtual Machine
(JVM)
• Java programs can run on any platform
(Linux, Window, Mac)
• Java programs can be transferred over world
wide web.
Architecture Neutral:
• Java is not tied to a specific machine or operating system
architecture.
• Machine Independent i.e. Java is independent of hardware.
• Bytecode instructions are designed to be both easy to
interpret on any machine and easily translated into native
machine code.
Dynamic and Extensible:
• Java is a more dynamic language than C or C++. It
was developed to adapt to an evolving environment.
• Java programs carry with them substantial amounts
of run-time information that are used to verify and
resolve accesses to objects at run time.
Interpreted:
• Java supports cross-platform code through the use of Java
bytecode.
• The Java interpreter can execute Java Bytecodes directly on any
machine to which the interpreter has been ported.
High Performance:
• Bytecodes are highly optimized.
• JVM can execute the bytecodes much faster.
• With the use of Just-In-Time (JIT) compiler, it enables high
performance.
Multithreaded:
• Java provides integrated support for multithreaded programming.
• Using multithreading capability, we can write programs that can
do many tasks simultaneously.
• The benefits of multithreading are better responsiveness and real-
time behavior.
Distributed:
• Java is designed for the distributed environment for the Internet
because it handles TCP/IP protocols.
• Java programs can be transmit and run over internet.
Overview of java
• Java is a object-oriented programming language was
originally developed by Sun Microsystems which was
initiated by James Gosling and released in early 1990 .
• James Gosling, often called as the father of Java
• In initial stage java was called as 'Oak. ‘
• Laterly it renamed as “java” in 1995.
BASIC JAVA TERMINALOGIES
Bytecode-intermediate code is generated from the source code by Java
compiler and it is platform-independent.
Java development kit (JDK)-offers a collection of tools and libraries
necessary for developing Java-based software applications.
Java virtual machine(JVM)-provide a means for a Java program to run in
any environment.
Java runtime environment-(JRE) provides runtime environment for JVM.
It contains set of libraries + and other files that JVM uses at runtime
Jit (just in time) compiler: It is used to improve the performance and hence
reduces the amount of time needed for compilation.
JAVA SOURCE FILE - STRUCTURE – COMPILATION
The java source file:
• A Java source file is a plain text file containing Java source
code and having .java extension.
Java Program Structure:
• Java program may contain many classes of which only one
class defines the main method.
//save as Simple.java.
package mypack;
Import java.io.*;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
Main Method Class :
• Every Java Standalone program requires a main method as its
starting point.
• A Simple Java Program will contain only the main method class.
Syntax for writing main:
class userinput
{
public static void main(String[] args)
{
int x, y, sum;
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Type a number:");
x = myObj.nextInt(); // Read user input
}
}
Using BufferReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();
// Printing the read line
System.out.println(name); OUTPUT:
} CSE
} CSE
JAVA – DATA TYPES
• Data type is used to allocate sufficient
memory space for the data.
• Data types specify the different sizes and
values that can be stored in the variable.
• Every variable in java must be declared with a
data type.
Data types in Java are of two types:
Boolean:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true
Variables
• Variables are containers(memory) for storing data values.
Declaring (Creating) Variables:
Syntax:
20
Final Variables
• Use the final keyword (if we declare the variable as "final" or "constant", which
means unchangeable and read-only):
public class Main {
public static void main(String[] args)
{
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
} output:
• Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;
^
1 error
class area
{
int length=20;
int breadth=30;
void calc()
{
int areas=length*breadth;
System.out.println(“The area is"+ areas);
}
public static void main(String args[])
{
area a=new area();
a.calc();
}
}
Output:
Java Arrays
• An array is a collection of similar type of elements which
has contiguous memory location.
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• 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.
• To declare an array, define the variable type with square
brackets:
String cars[];
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int mynum[]={10,20,30,40};
• Advantage of Array:
• • Code Optimization: It makes the code
optimized; we can retrieve or sort the data
easily.
• • Random access: We can get any data
located at any index position.
• Disadvantage of Array:
• Size Limit: We can store only fixed size of
elements in the array. It doesn't grow its size
at runtime.
Change an Array Element
Output:
4
Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
One-Dimensional Array:
1. Assignment operator
2. Arithmetic operator
3. Relational operator
4. Logical operator
5. Bitwise operator
6. Conditional operator
Java Assignment Operator
• The java assignment operator statement has
the following syntax:
<variable> = <expression>
Java Assignment Operator Example
class assignmentop{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Java Arithmetic Operators
• Java arithmetic operators are used to perform
addition, subtraction, multiplication, and
division.
• They act as basic mathematical operations.
Java Arithmetic Operator Example:
class arithmeticop
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Relational Operators
• Relational operators in Java are used to
compare 2 or more objects.
• Java provides six relational operators: Assume
variable A holds 10 and variable B holds 20,
then:
public class RelationalOperatorsDemo {
public RelationalOperatorsDemo()
{
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));}
public static void main(String args[])
{
RelationalOperatorsDemo d1=new RelationalOperatorsDemo();
}
Logical Operators
• Logical operators return a true or false value based on the
state of the Variables.
• Given that x and y represent boolean expressions, the
boolean logical operators are defined in the Table below.
public class LogicalOperatorsDemo
{
void LogicalOperatorsDemo()
{
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
public static void main(String args[])
{
LogicalOperatorsDemo d1=new LogicalOperatorsDemo();
d1.LogicalOperatorsDemo();
}
Bitwise Operators
• Java provides Bit wise operators to
manipulate the contents of variables at the
bit level.
Conditional Operators
• The Conditional operator is the only ternary (operator takes
three arguments) operator in Java.
• The operator evaluates the first argument and, if true,
evaluates the second argument.
• If the first argument evaluates to false, then the third
argument is evaluated.
• The conditional operator is the expression equivalent of the
if-else statement.
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo()
{ int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[])
{
TernaryOperatorsDemo d1=new TernaryOperatorsDemo();
}
}
CONTROL-FLOW STATEMENTS
• Java Control statements control the order of
execution in a java program, based on data values
and conditional logic.
if(<conditional expression>)
{
< Statement Action>
}
public class IfStatementDemo {
Output:
$java IfStatementDemo
b>a
if-else Statement:
• The if/else statement is an extension of the if statement.
• if statement fails, the statements in the else block are executed.
• Syntax:
• The if-else statement has the following syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
Example:
public class IfElseStatementDemo {
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i ==10)
{
if (i < 15)
{
System.out.println("i is smaller than 15");
}
else
{
}
}
else
{
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
Switch Statement:
• The switch case statement, also called a case statement is a
multi-way branch with several choices.
• A switch is easier to implement than a series of if/else
statements.
• A switch statement allows a variable to be tested for equality
against a list of values.
• Each value is called a case, and the variable being switched
on is checked for each case.
Syntax:
switch (<expression>)
{
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
}
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Looping Statements (Iteration Statements)
• While Statement :
• The while statement is a looping control
statement that executes a block of code while
a condition is true.
• It is entry controlled loop.
Example:
public class WhileLoopDemo {
public static void main(String[] args) { int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++); } } }
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
do-while Loop Statement
• 1. break statement
• 2. continue statement
Using break Statement:
a different task.
METHODS
• A Java method is a collection of statements
that are grouped together to perform an
operation.
• The syntax shown above includes:
• modifier: It defines the access type of the method
and it is optional to use.
• returnType: Method may return a value.
• Method_name: This is the method name. The
method signature consists of the method name and
the parameter list.
• Parameter List: The list of parameters, it is the type,
order, and number of parameters of a method. These
are optional, method may contain zero parameters.
• Method body: The method body defines what the
method does with statements.
class method
{
void display() //Method declaration
{
System.out.print(“this is 2nd cse B”);
}
public static void main(String args[])//main function
{
method m1=new method();
m1.display();
}
Output:
nd
ACCESS SPECIFIERS
• Access specifiers are used to specify the
visibility and accessibility of a class
constructors, member variables and methods.
• One of four different access modifiers:
1. Public
2. Private
3. Protected
4. Default (package)
Packages
1. Public (anything declared as public can be accessed from anywhere):
}
}
JavaDoc Comments
• Javadoc is a tool which comes with JDK and it is used for
generating Java code documentation in HTML format
from Java source code which has required
documentation in a predefined format.
Format:
• A Javadoc comment precedes similar to a multi-line comment except that
it begins with a forward slash followed by two asterisks (/**) and ends
with a */
• Each /** . . . */ documentation comment contains free-form text
followed by tags.
• A tag starts with an @, such as @author or @param.
• The first sentence of the free-form text should be a summary statement.
• The javadoc utility automatically generates summary pages that extract
these sentences.
• In the free-form text, you can use HTML modifiers such as <h1>...</h1>
for heading, <p>...</p> .