OOPJ (Java) Unit-I
OOPJ (Java) Unit-I
S. Contents Page
No No
1 Academic Calendar 1
2 Syllabus , OOPJ COs and JNTUA Approved Textbooks and Reference Text Books 2-5
3 Theory Syllabus 6-10
4 Laboratory Syllabus
5 Assignment Questions
6 Old Question Papers (JNTUA-R20)
Syllabus & OOPJ COs
UNIT I: Object Oriented Programming: Basic concepts, Principles, Program Structure in Java: Introduction,
Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data Types,
Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted Output with
printf() Method, Static Variables and Methods, Attribute Final, Introduction to Operators, Precedence and
Associativity of Operators, Assignment Operator (=), Basic Arithmetic Operators, Increment (++) and
Decrement (- -) Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary
Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop, Nested for
Loop, For–Each for Loop, Break Statement, Continue Statement.
UNIT II: Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of
Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private
Members of Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested Classes, Final
Class and Methods, Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class
Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding
Methods, Attributes Final and Static.
UNIT III: Arrays:Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer
Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array,
Dynamic Change of Array Size, Sorting of Arrays, Search for Values in Arrays, Class Arrays, Two-dimensional
Arrays, Arrays of Varying Lengths, Three-dimensional Arrays, Arrays as Vectors.
Inheritance:Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class-Object Class,
Inhibiting Inheritance of Class Using Final, Access Control and Inheritance, Multilevel Inheritance, Application
of Keyword Super, Constructor Method and Inheritance, Method Overriding, Dynamic Method Dispatch,
Abstract Classes, Interfaces and Inheritance.
Interfaces:Introduction, Declaration of Interface, Implementation of Interface, Multiple Interfaces, Nested
Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static Methods in Interface, Functional
Interfaces, Annotations.
UNIT IV: Packages and Java Library:Introduction, Defining Package, Importing Packages and Classes into
Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package and its Classes, Class
Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and Auto-unboxing, Java util Classes and
Java is a high level, object-oriented and a secure and stable programming language but it is not a pure
object-oriented language because it supports primitive data types like int, char etc.
Java is a platform-independent language because it has runtime environment i.e JRE and API.
Here platform means a hardware or software environment in which an application runs.
Java codes are compiled into byte code or machine-independent code.
This byte code is run on JVM (Java Virtual Machine).
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and
his team changed the name from Oak to Java.
HISTORY OF JAVA
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling.After that, it was called Oak
Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Java is an island of Indonesia where first coffee was produced (called java coffee).
Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
In programming, data is defined as variables and code is defined as methods. In OOP, every object is
// Constructor
public MyClass(int myField)
{
this.myField = myField;
}
// Methods
public void myMethod()
{
// Method implementation
}
}
4. Main Method
Every Java application must have a ‘main’ method as its entry point, which is declared as follows:
Example:
public static void main(String[] args)
{
// Application logic
}
5. Comments
Comments are used to explain the code and make it more understandable. Java supports both single-line and
multi-line comments.
Example
// This is a single-line comment
/*
* This is a multi-line comment.
* It can span multiple lines.
*/
6. Access Modifiers
Java provides several access modifiers (‘public’, ‘private’, ‘protected’, default) to control the visibility and
accessibility of classes, methods, and fields.
import java.util.ArrayList;
import java.util.List;
/**
* This class demonstrates a simple Java program structure.
*/
Scanner scanner = new Scanner(System.in); // Create a Scanner object for user input
System.out.print("Enter the radius of the circle: "); // Ask the user to enter the radius
double radius = scanner.nextDouble();
System.out.println("The area of the circle with radius " + radius + " is: " + area);
scanner.close(); // Close the Scanner
}
}
Explanation:
1. Import Statement: The ‘import java.util.Scanner;’ statement imports the ‘Scanner’ class from the ‘java.util’
2. Class Declaration: The ‘CircleAreaCalculator’ class is declared with the ‘public’ access modifier.
3. Main Method: The ‘main’ method is where the execution of the program begins.
4. Scanner Initialization: A ‘Scanner’ object named ‘scanner’ is created to read input from the user.
‘System.in’ specifies that input will be read from the standard input stream (typically the keyboard).
5. User Input: The program prompts the user to enter the radius of the circle using ‘System.out.print("Enter the
radius of the circle: ");’, and then reads the double input using ‘scanner.nextDouble();’.
6. Area Calculation: The area of the circle is calculated using the formula \( \text{area} = \pi \times
7. Result Output: After calculating the area, the program prints the result using ‘System.out.println("The area
of the circle with radius " + radius + " is: " + area);’.
8. Closing Scanner: The ‘scanner.close();’ statement closes the ‘Scanner’ object to release its resources.
2. Main Method: The ‘main’ method is where the execution of the program begins.
3. Sum Calculation: In this example, we calculate the sum of the first ‘n’ even numbers. We iterate over even
numbers starting from 2 up to ‘2 * n’ (inclusive), incrementing by 2 in each iteration (‘i += 2’). Inside the loop,
4. Result Output: After calculating the sum, the program prints the result using ‘System.out.println("Sum of
Loop Statements (‘for’, ‘while’, ‘do-while’): Repeatedly execute statements based on a condition.
Example:
for (int i = 0; i < 5; i++)
{
System.out.println("Iteration: " + i);
}
Branching Statements (‘break’, ‘continue’, ‘return’): Change the flow of control.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop
}
if (i % 2 == 0)
{
continue; // Skip current iteration
}
System.out.println(i);
}
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
Import Statement: ‘import java.util.Scanner;’ imports the ‘Scanner’ class from the ‘java.util’ package.
Creating Scanner Object:
Scanner scanner = new Scanner(System.in);
creates a new ‘Scanner’ object to read from the standard input (‘System.in’).
Prompting User: ‘System.out.print("Enter an integer: ");’ displays a message to prompt the user for input.
Reading Input: ‘int number = scanner.nextInt();’ reads an integer entered by the user.
Output: ‘System.out.println("You entered: " + number);’ displays the entered number.
Closing Scanner: ‘scanner.close();’ closes the ‘Scanner’ object to release resources.
Example:
Reading String Input
import java.util.Scanner;
public class StringInputExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // Create a Scanner object
Note:
It is because java uses Unicode system not ASCII code system.
The \u0000 is the lowest range of Unicode system. Unicode is a 16-bit character encoding standard.
Syntax :
char Variable_Name = Value;
/* Output:
byte: 0
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
char:
boolean: false
*/
Types of Variable
Local Variable
A variable that is declared inside the method is called local variable.
//local Variable Example
class LocalVariable
{
public static void main(String args[])
{
int a=10;
System.out.println(a);
}
}
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
//Instance variable Example
class InstanceVariable
{
int a=10;
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically.
Also, the char and Boolean data types are not compatible with each other.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x; //automatically converts the integer type into long type
float z = y; //automatically converts the long type into float type
Converting a higher data type into a lower one is called narrowing type casting.
It is also known as explicit conversion or casting up and it is done manually by the programmer.
If we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d; //converting double data type into long data type
int I = (int)l; //converting long data type into int data type
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
1. Local Variables
Local variables are declared within a method, constructor, or block of code (denoted by ‘{}’). They are only
accessible within the method, constructor, or block where they are declared.
Scope: Begins when the declaration is encountered and ends when the method, constructor, or block completes
execution or when the block's curly braces ‘{}’ are exited.
Example:
public class ScopeExample
{
public void exampleMethod()
{
int localVar = 10; // localVar is a local variable
System.out.println(localVar); // Accessible within exampleMethod()
// Other code
// localVar is not accessible outside of exampleMethod()
}
2. Instance Variables (Non-Static Fields)
Instance variables are declared within a class but outside any method, constructor, or block.
Each instance (object) of the class has its own copy of instance variables.
Scope: Exists as long as the object (instance of the class) to which it belongs exists.
In other words, it exists for the lifetime of the object.
Example:
public class ScopeExample
{
private int instanceVar; // instanceVar is an instance variable
public void exampleMethod()
{
instanceVar = 10; // Accessing instanceVar within a method
System.out.println(instanceVar);
}
// instanceVar can be accessed and modified in other methods of this class
}
Simple Text: Directly represented within double quotes. Example: ‘"Hello, Java!"‘.
Escape Sequences: Special characters and formatting represented by escape sequences.
Examples:
String message = "Hello, Java!"; // String literal
String path = "C:\\Users\\John"; // String with escape sequence for backslash
5. Boolean Literals
Boolean literals represent the two boolean values: ‘true’ and ‘false’.
They are keywords in Java and cannot be converted into any other type.
Examples:
boolean isJavaFun = true; // Boolean literal true
boolean isWorking = false; // Boolean literal false
6. Null Literal
The ‘null’ literal represents a reference that does not refer to any object.
It is often used to indicate that a reference variable does not currently refer to an object.
Examples:
String str = null; // Null literal representing no reference
Note:Literals in Java provide a straightforward way to represent fixed values of various data types directly
within your code.
Symbolic Constants in Java
In Java, symbolic constants refer to named identifiers that represent constant values which do not change during
the execution of a program.
They are typically defined using the ‘final’ keyword to indicate that their value cannot be altered once
initialized.
Using ‘final’ for Symbolic Constants
To define a symbolic constant in Java, you declare a ‘final’ variable and assign it a value.
By convention, the name of symbolic constants is usually written in uppercase letters with underscores
separating words
Examples :
1. Integer Constants
public static final int MAX_VALUE = 100;
public static final int INITIAL_COUNT = 0;
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
Java final method
Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}
Arithmetic Multiplicative / %
Additive + -
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary Ternary ?:
Assignment Assignment = += -= *= /= %=
The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Java Right Shift Operator Example
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
Output:
2
5
2
Example:
class BoolLogic
{
public static void main(String arg[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement.
The switch statement works with byte, short, int, long, enum types, String and some wrapper types like
Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
Points to Remember
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
case value3:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
However, loop statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop
Java Simple for Loop
A simple for loop is the same as C/C++.
We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
ForExample.java ///which prints table of 1
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.print(i);
}
}
}
Output: 1 2 3 4 5
Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
BreakExample.java //Java Program to demonstrate the use of break statement inside the for loop.
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++) //using for loop
{
if(i==5) //breaking the loop
{
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately.
The Java continue statement is used to continue the loop.
It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
ContinueExample.java //Java Program to demonstrate the use of continue statement inside the for loop.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5 || i==7 || i==3)
{
continue; //it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
4
6
8
9
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is continued when it
reaches to 5.