0% found this document useful (0 votes)
9 views27 pages

Unit 1 OOP Java

The document provides an introduction to Java programming, highlighting its features such as platform independence, object-oriented principles, and security. It explains the components of the Java environment, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with the process of writing and running Java programs. Additionally, it covers basic programming concepts, including class structure, the main method, command line arguments, and interactive input handling.
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)
9 views27 pages

Unit 1 OOP Java

The document provides an introduction to Java programming, highlighting its features such as platform independence, object-oriented principles, and security. It explains the components of the Java environment, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with the process of writing and running Java programs. Additionally, it covers basic programming concepts, including class structure, the main method, command line arguments, and interactive input handling.
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

Object Oriented Programming – Java DI04000021

Unit 1- Introduction to Java Programming

1.1 Introduction to Java

Introduction to Java
 Java is a general-purpose, object-oriented, secure, and robust programming language.
 Developed by James Gosling at Sun Microsystems in 1991; originally named Oak, renamed to Java in
1995 due to legal reasons.
 Initially designed for consumer electronic devices like TVs and VCRs.
 Java overcomes portability and reliability issues found in C and C++.
 Java programs run in different execution environments because it is strongly typed and uses bytecode
for machine-independent execution.
 Compile time: source code → platform-independent bytecode.
 Runtime: loading/linking classes, optional machine code generation, and dynamic optimization.
 Its key feature is platform independence—Java programs can run on any system with the Java Virtual
Machine (JVM).

Java Features
1. Compiled and Interpreted: Java uses both a compiler (creates bytecode) and an interpreter/JVM
(executes bytecode).
2. Platform Independent: Bytecode is not machine-specific so any system with a JVM can run the same
bytecode. It follows WORA(Write Once, Run Anywhere.)
3. Portable: Java programs run on any system and has high high portability due to JVM.
4. Object-Oriented: Everything is based on objects and classes. So it can use OOP concepts like
encapsulation, inheritance, and polymorphism.
5. Robust and Secure: Provides strong type checking, exception handling, Garbage collection, No
pointers. JVM verifies bytecode for safety and security.
6. Distributed: Allows programs to access remote objects and useful for collaborative and network-based
applications.
7. Simple : Easier than C/C++ and reducing programmer effort.
8. Multithreaded and Interactive: Supports multithreading, Provides built-in support for thread handling
and synchronization.
9. High Performance: JIT (Just-In-Time) compilation improves performance, Multithreading increases
overall program efficiency.
10. Dynamic and Extensible: Java can load new classes and methods at runtime. Easily adaptable and
expandable.

Java Applications
1. Mobile Applications
2. Desktop GUI Applications
3. Web-based Applications
4. Enterprise Applications
5. Scientific Applications

1.2 Writing & Running First Program

● JDK, JRE, JVM

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 1


Object Oriented Programming – Java DI04000021

JE (Java Environment)
 JE includes large no. of development tools and hundred of classes and methods.
 Tools are part of JDK (java development toolkit) and classes and methods are part of JSL (API) .

JE = JSL + JDK
Full Form:
 JDK : Java Development Toolkit
 JSL : Java Standard Library
 API : Application Programming Interface

1) JDK: Java Development Toolkit


 It is a collection of tools that are used for developing and running java program.
 JDK includes,
1. applet viewer (for viewing java applets)
2. javac (java compiler)
3. java (java interpreter)
4. javap (java disassembler)
5. javah (for C header files)
6. javadoc (for creating HTML documents)
7. jdb (java debugger)

No Tools Description
1 appletviewer It enables user to run java applets.

2 javac javac translates java source code to byte code files that the interpreter
(java compiler) can understand.

3 java It runs applets and application by reading and interpreting byte codes.
(java interpreter)
4 javap It enables users to convert byte code files into a program description.
(java disassembler)
5 javah It Produces header files for use with native methods.
(for C header files)

6 javadoc It creates HTML format documentation from java source code files.
(for creating HTML
Documents)

7 jdb (java debugger) It helps user to find error in our program.

2) JRE (Java Runtime Environment)


 JRE consists of JVM and the program on the other.
 It runs code compiled for JVM by:

1. Loading the .class files


2. Verifying byte code
3. Executing the code

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 2


Object Oriented Programming – Java DI04000021

Implementing java program


Java application program implementation involves a three steps:
 Creating the program (.java file)
 Compiling the program( using javac )
 Running the program ( using java )

3) Java Virtual machine (JVM)


 All language compilers translates source code into machine code for a specific computer.
 Java is platform independent or machine neutral!!!
 Java compiler produces an intermediate code (byte code or virtual machine code ) for a machine that
does not exist. That machine is Java Virtual Machine (JVM).
 JVM exists only inside the computer memory.
 JVM is a simulated computer within the computer and does all major functions of real computer.
 Byte code is not machine specific.
 Machine code is generated by the java interpreter by acting as intermediately between the virtual
machine and real machine.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 3


Object Oriented Programming – Java DI04000021

● Byte Code

 Bytecode is object-oriented programming (OOP) code co


 mpiled to run on a virtual machine (VM) instead of a central processing unit (CPU).
 The VM transforms program code into readable machine language for the CPU because platforms utilize
different code interpretation techniques.
 A VM converts Bytecode for platform interoperability, but Bytecode is not platform-specific.
 Bytecode is in a compiled Java programming language format and has the .class extension executed by
Java Virtual Machine (JVM).
 This term is also known as portable code (p-code).

● Structure of a Java program (class, main()).

 Java program may contain many classes of which only one class defines a main method.
 Class contain data members and methods that operate on data members of class.
 Method may contain data type declaration and executable [Link] program define classes and put
them together.

Documentation section:

 This section comprises a set of comment lines giving the name of the program, author and other
details, which the programme would like to refer to at a large stage.
 Comments must explain why and what of classes and how to algorithms.
 Java supports three types of comment line:

o Single comment line : //


o Multiline : /* ……. */
o Documentation line : /** ……. */

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 4


Object Oriented Programming – Java DI04000021

Package statement:
 The statement declares a package name and informs the compiler that the classes defined here belong to this
package.
package student ; //student is package
package statement is optional.
Import statements:
 After package statement (but before class definitions) be a number of import statements. This is similar to the
#include statement in C.
import [Link];
 This statement instructs the interpreter to load the test class contained in the package Student.
 Using import statement ,we can access to classes that are part of the other named packages.

Interface statement:
 Interface is like a class but includes a group of method declarations. This is also an optional section.
 It is used only when we want to implement the multiple inheritance feature in the program
Class definitions:
 A java program may contain multiple class definitions. Classes are the primary and essential elements of a
Java program. The number of classes used depends on the complexity of the problem.
Main method class:
 Every java stand alone program requires a main method as its starting point, this class is essential part of a
java program.
 Simple java program may contain only this part.
 The main method creates objects of various classes and creates communications between them.
 On reaching the end of main ,the program terminates and control passes back to th e operating system.
Machine neutral
 The compiler converts the source code files into byte code files. These codes are machine independent and
therefore can be run on any machine. That is, a program compiled on an IBM machine will run on a Linux
machine.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 5


Object Oriented Programming – Java DI04000021

 Java interpreter reads the byte code files and translates them into machine code for the specific machine on
which the java program is running.

● Hello World program – compile & run.

Simple java program

class Test
{
public static void main(String args[ ])
{
[Link]( “welcome to Java”);
}
}
1) First line : class Test
 declares a class which is an object oriented construct.
 java is true object oriented language and therefore everything must be placed inside a class.
 class is keyword and it declares that a new class definition follows.
 Test java identifier(name) specifies name of the class to be defined.
2) Second line : Opening brace : {
3) Third Line : public static void main (String args[ ])
 Every java program must include main( ) method.
 It is the starting point for interpreter to begin the execution of program.
 A java application can have any number of classes but only one of them class must include main method to
initiate the execution.(java applets will not use the main method at all).

main ( ) method of java


 public: The keyword public is an access modifier. It declares main method as unprotected .it makes
method accessible to all other classes.
 static : It is a keyword, which declare method is for entire class and not a part of any object of class. The
main must always be declared as static since the interpreter uses this method before any objects are created.
 void does not return any value.
 String args declares parameter names args which contain an array of object of class type string.

4) Output line:
[Link] (“Hello”);

class object method


 This line is similar to printf ( ) statement of C or cout<< construct of C++.
 Since java is true object oriented, every method must be part of an object.
 println method is a member of the out object, which is a data member of a System [Link] method
always append a new line character to the end of the string. This means subsequent output will start on a new
line.
 Semicolon at the end of each statement is used. Every java statement must end with semicolon.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 6


Object Oriented Programming – Java DI04000021

5) Fifth line :closing brace : }


 It is the ending of program.

Note: java program must name same as in class which includes main( ) method otherwise interpreter cannot
run that class.

Difference between print( ) and println( ) method


1) print ( ) method: print and wait
 This method sends information into a buffer. This buffer is not flushed until a newline (or end of
line) character sent.
 As a result print( ) method prints out on one line until a new character is encountered.
 [Link] ( “hello”);
 We can also use \n to force the display to be brought to the next line by printing a newline
character as follows:
 [Link] ( “ hello \n” ); //this would work same as println ( ) method
2) println ( ) method : prints a line and move to next line
 This method takes the information provided and displays it on a line followed by a line feed.
[Link]( “java !!!”);

Command line argument


 If we want, our program to act in a particular way depending on the input provided at the time of
execution. This is done in java programs by using command line arguments.
 Definition: command line arguments are parameters that are supplied to the application program
at the time of on invoking it for execution.
 We can write java program that can receive and use the arguments provided in the command line.
public static void main (String args[ ])
 args is declared as an array of strings(known as string object) .Any arguments provided in the command
line are passed to the array args as its elements.
 We can simply access the array elements and use them in the program as we want.
 Command line arguments are passed when we run the program
 To compile : javac [Link]
 To run : java Test Basic C++ C Java
 This command line contains four arguments .These arguments are assigned to the array args as follows:
Basic  args[0]
C++  args[1]
C  args[2]
Java  args[3]

 Example 1: write a java program takes 2 variable by user input using command line and find sum.
class CmdDemo
{
public static void main ( String args [ ] )
{
int a,b ,sum;
a= Integer .parseInt (args[0]);
b= Integer .parseInt (args[1]);
sum= a+b;

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 7


Object Oriented Programming – Java DI04000021

[Link]( “sum= “+ sum);


}
}
command line argument
Output : E :\ java program \ javac [Link]
E :\ java program \ java CmdDemo 10 20
sum=30

Example :2

class Cmd1
{
public static void main (String args[ ])
{
int count=0;
String str;
count=[Link]; //to find how many arguments are passed to command line

[Link] ( “total no. of arguments passed = “ + count );


while ( i < count )
{
str= args[ i ];
i=i+1;
[Link] ( i + “ : “ + “Java is “ + str + “ !!!” );
}
}
}
E: \java program \ javac [Link]
E: \java program \ java Cmd1 simple robust secure portable dynamic object_oriented
Output :
total no. Of arguments passed= 6
1 : Java is simple !!!
2 : Java is robust !!!
3 : Java is secure !!!
4 : Java is portable !!!
5 : Java is dynamic !!!
6 : Java is object_oriented !!!

Read statement
 We may also give values to variables interactively through the keyboard using readLine( ) method.
 readline( ) is invoked using an object of the class DataInputStream.
 readLine( ) reads the input from the keyboard as a string which is then converted to the corresponding
data type using the data wrapper classes.
 We have used the keywords try and catch to handle any errors that might occur during the reading
process.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 8


Object Oriented Programming – Java DI04000021

 Example :
import java. io .DataInputStream;
class Reading
{
public static void main (String args [ ])
{
DataInputStream obj=new DataInputStream([Link]);
int i=0;
float f=0.0 F;
try
{
[Link] (“enter an integer no “);
i = [Link] ( obj. readLine( ) );
[Link] (“enter float no “);
f = [Link] ([Link] ( ) ).floatValue( );
}
catch(Exception e)
{
[Link] ( “enter proper value” );
}
[Link]( “int no i= “+ i );
[Link]( “float no f= “ +f);
}
}
Output:
E :\ java program\ javac [Link]
E :\ java program\ java Reading

enter an integer no
56
enter float no
23.455
int no i= 56
float no f=23.455f

1.3 Data Types & Variables

● Primitive types (byte, short, int, long, float, double, char, boolean).

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 9


Object Oriented Programming – Java DI04000021

• Floating point no. are treated as double precision , so to force them to be in single
precision mode ,we must append f or F.
Ex: 1.23f , 7.6512F
• NaN: Not a Number (special value supported by floating point data type)
It is used to represent result of operation such as dividing by zero ,where actual number is
not produced.
Character type
• char is used ,Size : 2 byte
• It holds single character only.
Boolean type
• It is used to test a particular condition during execution of program.
• It has two values : true or false
• boolean keyword is used
• Size: 1 bit ( 0 or 1).All comparison operators return boolean type variable. So, there
are 8 basic(primitive ) data type in java.
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 10
Object Oriented Programming – Java DI04000021

Sr. No. Type Size (in bytes)


1 boolean 1 bit
2 byte 1 byte
3 character 2 bytes
4 short 2 bytes
5 int 4 bytes
6 float 4 bytes
7 long 8 bytes
8 double 8 bytes

User Defined Data Type


Class, interface and array are user defined data type.

• Class encapsulates various variables and methods


• Interface is same as class except it contains methods without body. It is used to implement
multiple inheritance.
• An array contains same type of elements and provides sequential access.

Identifiers & Literals (Java tokens)

• Java program is a collection of classes.


• Class is defined by a set of declaration statements and methods containing executable
statements.
• Smallest individual unit in program is tokens.
• Compiler recognize them for building up expressions and statement
Java program=tokens + comments + white space

There are Five types of tokens :


PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 11
Object Oriented Programming – Java DI04000021

1) reserved keywords
2) identifiers
3) literals
4) operators
5) separators

Java character set


• Smallest unit of java language are characters.
• Characters are used to write java tokens, this characters are defined by Unicode character set.
• Unicode is 16-bit character coding system.
1) Keywords
• Java has 60 reserved keywords.
• We cannot use keywords as names for variables, classes, methods and so on.
• Keywords should be written in small letters.

abstract Boolean Break byte byvalue* case cast*

catch char Class const* continue default do

double else Extends false** final finally float

for future** generic* goto* if implements import

inner* instanceof* Int interface long native new

null** operator* outer* package private protected public

rest* return Short static super switch syncronized

this threadsafe* Throw throws transient true** Try

var* void Volatile while

* Reserved for future use


** These are values defined by java

2) Identifiers
• Identifiers are programmer designed tokens.
• It is used for naming classes ,methods , variables , objects , label , package and interface in
program.
Example:
▫ average , sum ,dayTemprature , totalMarks
3) Literals
• Sequence of characters (digits , letters ,and other character) that represent constant
values to be stored in variables.
• Five types:
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 12
Object Oriented Programming – Java DI04000021

▫ Integer literals
▫ Floating_point literals
▫ Character literals
▫ String literals
▫ Boolean literals
4) Operators
• All operator is a symbol that takes one or more arguments and operates on them to produce a
result.
5) Separators
• They are symbols used to indicate where groups of code are divided and arranged.
Sr. No. Name

1 Parentheses ( )

2 Braces { }

3 Brackets [ ]

4 Semicolon ;

5 Comma ,

6 Period .

● Declaring & initializing variables

2.2 Constant
• Constant in java refers to fixed values do not change during execution of program.
1) Integer Constant
2) Real constant
3) Single constant
4) String constant

1) Integer constant:
Integers:
a. Decimal : 0 to 9 [ ex. 123, 012 , 16789 ]
b. Octal : [ ex. 037 , o ,0435 ]
c. Hexadecimal : [ 0x2 , 0x9F , 0x ,oxbcd ]

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 13


Object Oriented Programming – Java DI04000021

2) Real constant
• Floating point / Real point constants Ex.
0.083 , -0.75 , 215. , .95 , -.71
syntax : mantissa e Exponent
• Ex.
▫ .65e4 , 12e-4 , 1.5 e+5 , 3.18E3
• Floating point contain 4 parts:
▫ A whole number
▫ A decimal number
▫ A fractional part
▫ An exponent

3) Single character constant


Ex.
„5‟ , „Y‟ , „; „ , „„
4) String constant
Sequence of character enclosed between double quotes.

Ex.
“hello java” , “1997” ,”?----” , “5+3” , “x”

Back slash character sequence (Escape sequence)

„\b‟ Back space

„\f‟ Form feed

„\n‟ New line

„\r‟ Carriage return

„\t‟ Horizontal tab

„\‟‟ Single quote

„\\‟ Double quote

Variable
• It is a data name used to store a data value.
• Variable may take different values at different times during execution of program.
Rules for declaration
1. Not start with digit
2. Upper case and lower case letters are distinct
3. Not should be a keyword
4. No white spaces
5. Variable name can be of any length
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 14
Object Oriented Programming – Java DI04000021

Declaration of variable
Syntax:
type variable1, variable2,……;
Ex: int count; float x , y ; double p1; byte b; char ch;
Giving values to variable
1. By using assignment statement Syntax : variable name=value;
Ex: i=0,x=0.0f;
int i=0; char ch=„X‟;
2. By using read statement: (readLine() method)
readLine() method reads input from keyboard as a string which is then converted to
corresponding data type using wrapper classes.
3. By passing parameter in command line as its argument

● The Scope and Lifetime of Variables

Scope of variables & default values of variables declared

Variable classified as
1. instance variable
2. Class variable
3. Local variable
1) Instance variable:
• Declared inside class
• They are creating when object are instantiated and therefore they are associated with objects.
• It takes different values for different objects.
2) Class variable
• Declared inside class
• They are global to class and belongs to the entire set of object that class creates.
• Only one memory location is created for each class variable
3) Local variable
• Variable declared and used inside methods.
• They work only inside that specific method.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 15


Object Oriented Programming – Java DI04000021

Standard default values

Type value
byte Zero:(byte) 0
short Zero:(short) 0
int Zero : 0
long Zero: 0L or 0l
double 0.0d
float 0.0f
char Null character or „\u0000‟
boolean false
Reference null

● Type Conversion and Type Casting


• Process of converting one data type to another is called type casting. When we
need casting?
It is used when there is need to store a value of one type into a variable of another type.
Syntax:
type variable1 = (type) variable2 ;
Example:
int m=5;

byte n=(byte) m; // converts int m into byte type long

count=(long) m; // converts int m into long type

• float and double type can be converted any except boolean.


• byte ,short , int and long can be converted in any type except boolean .
• Casting in smaller type may result in loss of data.
• Casting floating point into integer will loss of fractional part.

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 16


Object Oriented Programming – Java DI04000021

Casts that result in No Loss of information

From To
byte short , char , int , long , float , double

short int , long , float , double

char int , long , float , double

int long , float , double

long float , double

float double

Automatic type conversion

• It is possible to assign value of one type to a other type without casting, is known as
automatic type conversion.
• It is possible only if destination type has enough precision to store source type.
• Example:
byte b= 75;
int a = b;
Two operations :
1) Widening(promotion)
2) Narrowing
• Widening: process of assigning smaller type to larger type is widening or promotion.
Ex: byte b=5;
int a=b;
• Narrowing: process of assigning larger type to smaller type is known as narrowing.

Ex: float c=25.43f;


int a=(int) c;

• Narrowing may result in loss of information.

● Brief overview of Operators (Arithmetic, Bitwise, Rational, Logical, Assignment, Conditional, Ternary,
Increment and Decrement).

An operator is some special characters (symbol) that tells the computer to perform certain
mathematical or logical manipulations.
Types of Operators
1) Arithmetic Operators
2) Relational operators
3) Logical Operators
4) Assignment Operators
5) Increment & Decrement Operators
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 17
Object Oriented Programming – Java DI04000021

6) Conditional Operators
7) Bitwise Operators
8) Special Operators

1) Arithmetic Operators

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Divisions

 Ex: a+b, a-b, a*b, a%b, a/b


 Where a & b variables & known as operand.
 Integer Arithmetic: Where all operands are integer.

 Real Arithmetic: Where all operands are real.


 Mixed-Mode Arithmetic: Where one operand is real & the other is integer.

Ex. 15 / 10.0 produce result 1.5

While 15/10 produce result 1


2) Relational Operators
 Compare two quantities & depending on their relation.
 Relational operators are used in decision statements such as while & if to decide the
course of action of a running program.

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

3) Logical Operators
 C has three logical operators.

Operator Meaning
&& Logical AND
|| Logical OR

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 18


Object Oriented Programming – Java DI04000021

! Logical NOT

 The Logical operator && and || are used when we want to test more than one
condition and make decisions.
 Ex: a>b && x==10
 In logical AND operator is used to perform more than one condition and take one
decision.
 In logical OR operator is used to perform more than one condition and take one
decision.
 Logical NOT operator is used to negate the answer of operation.

4) Assignment Operators
 Used to assign the result of an expression to a variable.
 C has a set of “shorthand” assignment operators.

a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b

5) Increment & Decrement Operators


 Increment Operator ++
 Decrement operator --
 The increment operator ++ adds 1 to the operand, while decrement operator --
subtracts 1.
 We use the increment and decrement statements in for and while loops.
Prefix increment operator
 A prefix operator first adds 1 to the operand(variable) and then the result is assigned to
the variable on the left.
 Syntax: ++variable name
Postfix increment operator
 A postfix operator first assigns the value to the variable on the left and then
increment the operand(variable).
 Syntax: variablename++
Prefix decrement operator
 A prefix operator first subtracts 1 to the operand (variable) and then the result is
assigned to the variable on the left.
 Syntax: --variablename
Postfix decrement operator
 A postfix operator first assigns the value to the variable on the left and then
decrement the operand(variable).
 Syntax: variablename--
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 19
Object Oriented Programming – Java DI04000021

6) Conditional Operator / Turnery Operator


 Conditional operator can be used in place of if-else statement.
 It is a two-way branching statement.
 Syntax: exp1 ? exp2:exp3
 where, exp1,exp2 & exp3 are expressions.
 First exp1 is evaluated.
 If it is true then the expression exp2 is evaluated & becomes the value of an
expression.
 If exp1 is false, then exp3 is evaluated and its value becomes the value of the
expression.
1) Bitwise Operator
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One‟s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill

 Bitwise operators are used for Manipulation of data at bit level.


 Used for testing the bits, or shifting them right or left.
 Bitwise operators are used only for integer datatype.
 Not to be applied to float or double

Bitwise AND operator


 Symbol: &
 Syntax: variablename1 & variablename2;
 The bitwise AND operator is represented by a single ampersand (&) and is
surrounded on both sides by integer expressions.
 The result of ANDing operation is 1 if both the bits have a value of 1; otherwise it
is 0.
Bitwise OR operator
 Symbol: |
 Syntax: variablename1 | variablename2;
 The bitwise OR operator is represented by vertical bar(|) and is
surrounded on both sides by integer expressions.
 The result of OR operation is 1 if at least one of the bits has a value of 1; otherwise
it is 0.
 Example:
Bitwise Exclusive OR operator
 Symbol: ^
 Syntax: variablename1 ^ variablename2;
 The result of exclusive OR is 1 if only one of the bits is 1; otherwise it is 0.
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 20
Object Oriented Programming – Java DI04000021

One‟s complement
 Symbol : ~
 It complements bits 1to 0 and 0 to 1.
Right Shift with zero fill
 The right shift operation causes all the bits in the operand op to be shifted to the right by n
positions.
 The rightmost n bits in the original bit pattern will be lost and the leftmost n bit positions
that are vacated will be filled with 0s.
2) Special operators
1) instanceOf operator
2) dot operator
1. instanceOf operator :
 It is an object reference operator.
 It returns true if object on left side is instance of class given on right side.
 It defines whether object belongs to particular class or not.
 Ex:
person instanceOf Student

If object person belongs to class Student then returns true , else returns
false.
2. Dot ( . ) operator :
• It is used to access the instance variable and method of class objects.
• It is also access classes and sub package from package.
▫ [Link];

▫ [Link]();

Control Flow
● if-else (simple & nested & ladder).
The if Statement
 Use the if statement to specify a block of Java code to be executed if a condition is true.
 Syntax:
o if (condition) {
o // block of code to be executed if the condition is true
o }
 Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
 Example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:
if (20 > 18) {
[Link]("20 is greater than 18");
}
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 21
Object Oriented Programming – Java DI04000021

2. The if..else Statement


Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18)
{
[Link]("Good day.");
}
else
{
[Link]("Good evening.");
}
3. The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10)
{
[Link]("Good morning.");
}
else if (time < 18)
{
[Link]("Good day.");
}
else
{
[Link]("Good evening.");
}
● switch-case
Instead of writing many if..else statements, you can use the switch statement.
 The switch statement selects one of many code blocks to be executed:
 Syntax
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 22
Object Oriented Programming – Java DI04000021

switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
 This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this chapter
 The example below uses the weekday number to calculate the weekday name:
 Example
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}

● for loop, while loop, do-while

While Loop
 Loops can execute a block of code as long as a specified condition is reached.
 Loops are handy because they save time, reduce errors, and they make code more readable.
 The while loop loops through a block of code as long as a specified condition is true:
 Syntax
while (condition)
{
// code block to be executed

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 23


Object Oriented Programming – Java DI04000021

}
 In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:
 Example
int i = 0;
while (i < 5) {
[Link](i);
i++;
}

2. The Do/While Loop


 The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
 Syntax
do {
// code block to be executed
}
while (condition);
 The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
 Example
int i = 0;
do {
[Link](i);
i++;
}while (i < 5);

3. Java For Loop

 When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
 Syntax
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
 Statement 1 is executed (one time) before the execution of the code block.
 Statement 2 defines the condition for executing the code block.
 Statement 3 is executed (every time) after the code block has been executed.
 The example below will print the numbers 0 to 4:
 Example
for (int i = 0; i < 5; i++)
{
[Link](i);
}

● Jump statements: break, continue

Java Break
PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 24
Object Oriented Programming – Java DI04000021

 You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
 "jump out" of a switch statement.
 The break statement can also be used to jump out of a loop.
 This example stops the loop when i is equal to 4:
 Example
for (int i = 0; i < 10; i++) {
if (i == 4)
{
break;
}
[Link](i);
}
2. Java Continue
 The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues
 with the next iteration in the loop.
 This example skips the value of 4:
 Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
[Link](i);
}

1.5 Arrays
● 1D arrays: declaration, initialization, traversal.

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.

Type of Array
1. One Dimensional Array
2. MultiDimensional Array

1. One-Dimensional Array (1D Array)

A one-dimensional array stores a list of values of the same data type in a single row.

Syntax
dataType[] arrayName;

or

dataType arrayName[];

Declaration and Initialization


int[] numbers = {10, 20, 30, 40, 50};

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 25


Object Oriented Programming – Java DI04000021

Example Program
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

// Accessing elements
[Link]("First element: " + numbers[0]);

// Using loop
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
}
Output
First element: 10
10
20
30
40
50

2. Two-Dimensional Array (2D Array)

A two-dimensional array stores data in rows and columns (like a table or matrix).

Syntax
dataType[][] arrayName;
Declaration and Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Example Program
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing elements
[Link]("Element at [1][2]: " + matrix[1][2]);

// Using nested loops


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 26


Object Oriented Programming – Java DI04000021

}
}
}
Output
Element at [1][2]: 6
1 23
456
789

Multidimensional Arrays
 A multidimensional array is an array of arrays.
 Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.
 To create a two-dimensional array, add each array within its own set of curly braces:
 Example:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
 Access Elements
 To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array. This example accesses the third element (2) in the second array (1) of
myNumbers:
 Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](myNumbers[1][2]);

PREPARED BY: VPMP POLYTECHNIC, GANDHINAGAR 27

You might also like