Module 1 OOPS
Module 1 OOPS
Module 1 OOPS
• Features of OOP
• Data types, variables, Array, Operators, String functions, Control statements
• Objects and Classes in Java – Defining Classes – Methods - Access Specifiers –
Static Members – Constructors,this Keyword-Encapsulation.
Machine Code:
• Representing instruction and data using binary digit is called
Machine Language or Machine Code. Computers can understand only
machine codes.
Assembler: It converts assembly language program into machine code.
Compiler: It converts all lines into machine code and gives to
microprocessor.
Interpreter: It converts line by line and only one line at a time.
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Platform independent
• Java Virtual Machine (JVM) is the heart of entire Java program execution
process.
• It is responsible for taking the . class file and converting each byte code
instruction into the machine language instruction that can be executed by
the microprocessor
• Class loader loads the . class file into memory.
• Bytecode verifier verifies whether all byte code instructions are proper or
not.
• If it fids any instruction suspicious, the execution is rejected immediately.
• If the byte instructions are proper, then class loader allocates necessary
memory to execute the program
• JVM is platform dependent
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java Virtual Machine (JVM)
Interpreter
• The interpreter reads and converts the bytecode instructions line by line
JIT(Just-In-Time) Compiler
• The Execution Engine first uses the interpreter to execute the byte code, but
when it finds some repeated code, it uses the JIT compiler.
Ex:
• byte rno = 101;
• long sal = 340000000l;
• int x=20;
1. Arithmetic Operators
2. Increment & Decrement Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6. Conditional Operators
7. Bitwise
Dr. Venkata Operators
Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Arithmetic Operators:
• These operators performs basic arithmetic operations etc.
Operator Operators Meaning Usage
+ Addition a+b
- Subtraction a–b
* Multiplication a*b
/ Division a/b
% Modulus (remainder of a%b
Div.)
Example:
int a = 4; int b = 1;
boolean c = a < b;
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Logical Operators:
• These operators are used to construct compound conditions. A compound condition is
a combination of more than one simple condition
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example:
class HelloWorld {
public static void main(String[] args) {
int a = 5,b=6,c=4;
System.out.println(a < b && a<c);
System.out.println(a<b || a<c); }}
X=10;
X<<2=10x22
=10x4= 40
Bitwise Right Shift Operator (»)
• This operator shifts the bits of the number towards right a
specified number of positions.
• If we write x»n, the meaning is to shift the bits of x towards
right n positions
X>>n=x/ 2n
X>>2=10/22
=10/4=2
X>>2=?
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
class ope {
public static void main(String[] args)
{
int x=9,y=15,z=5;
System.out.println(x+y); //24
System.out.println(x++); //9
System.out.println(x<y); //true
System.out.println(x<y && x<z); //false
System.out.println(x<y?x:y); //10
System.out.println(x & y); //10
System.out.println(x>>2); //2
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Program to find the maximum of two numbers
class celsiustofahrenheit {
public static void main(String[] args)
{
double celsius = 33.0, fahrenheit;
Fahrenheit:91.4
• To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class
• The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc.
• To get a single character from the scanner, you can call next().charAt(0) method
which returns a single character
import java.util.Scanner;
}
}
Enter amount in dollars: 5
Rupee=401.45000000000005
if statements:
1.Simple if statement
2.if-else statement
3.if-else-if ladder
Simple if statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
if-else statement:
This statement is used to perform a task depending on whether a given condition is true
or false. Example: Movie Ticket automation
Syntax: class Ticket{
if(condition) { public static void main(String args[])
{
statement 1; //executes when condition is true int age=2;
} if(age<4)
{
else{
System.out.println(“Ticket Not Required”);
statement 2; //executes when condition is false }
} else
{
System.out.println(“ Ticket Required”);
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements
Example: Check eligibility to cast vote
import java.util.*;
class Vote{
public static void main(String args[])
{
System.out.println("Enter Age");
Scanner sc = new Scanner(System.in);
int age=sc.nextInt();
if(age<18)
{
System.out.println("Not eligible to Vote");
}
else
{
System.out.println("Eligible to Vote");
}
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements
if-else-if ladder:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 3; //executes when all the conditions are false
}
Problem:
Raju's parents are celebrating their marriage anniversary. They have arranged a small party
tonight. They have planned to serve 'Coke' and 'Badam Milk' to the guests. But they would
like to serve 'Badam Milk' to teenagers and 'Coke' to adults. Please help them in finding
teenagers and adults based on age. Write a Java program to find out the adults and teenagers
based on their age. Teenagers are those whose age is between 13 and 19 (both inclusive).
switch (expression) {
case value1: statement sequence;
break;
case value2: statement sequence;
break;
. . .
case valueN: statement sequence ;
break;
default: default statement sequence;
}
Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
import java.util.*;
class Sum
{
public static void main(String args[])
{
int i=1, sum=0,n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“Sum is=”+sum);
}
}
for loop:
• The Java for loop is used to iterate a part of the program several times.
• If the number of iteration is fixed, it is recommended to use for loop.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
class Pattern {
public static void main(String args[]) 1
{ 12
int i, j,n=5;
// outer loop to handle number of rows
123
for (i = 1; i <= n; i++) { 1234
// inner loop to handle number of 12345
columns
for (j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
for-each loop:
• The for-each loop is used to traverse array or public class ForEach {
collection in Java public static void main(String[] args) {
//Declaring an array
Syntax: int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(data_type variable : array_name
){ for(int i:arr){
System.out.println(i);
//code to be executed
}
} }
}
O/P: 12,23,44,56,78
}
}
}
for(int i=0;i<4;i++)
{
for(int i=0;i<5;i++)
{
a[i][j]=value;
}
}
import java.util.*;
class Sum
{
public static void main(String[] args) {
int sum=0;
int a[][]=new int[2][2];
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array elements");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++) O/P:
a[i][j]=sc.nextInt();
Enter Array elements
for(int i=0;i<2;i++) 1
for(int j=0;j<2;j++) 2
sum=sum+a[i][j];
3
System.out.println("Sum Of Elements:"+sum); 4
} Sum Of Elements:10
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Strings
• String represents a group of characters
• In java, a string is an object of String class
String s1="VIT" ;
String s2="AP";
System.out.println(s1.equals(s2));
String trim (): This method removes spaces from the beginning and ending of a string.
String s1=“ OOPS through JAVA ”;
System.out.println(s1.trim());
String substring (int i): This method is useful to extract sub string from a main string.
• It returns a new string consisting of all characters starting from the position 'i' until the
end of the string.
String s1="University";
System.out.println(s1.substring(3));
String substring (int i1, int i2 ): This method returns a new string consisting of all
characters starting from position i1 to i2.
• The character at i2 is excluded;
String s1="University";
System.out.println(s1.substring(3,5));
String toLowerCase(): This method converts all characters of the string into lower case.
String toUpperCase () : This method converts all characters of the string into upper case.
split()
• The split() method divides the string at the specified regex and returns an array of
substrings.
Java
String text = "Java is a fun programming language"; is
a
String[] result = text.split(" "); fun
programming
for (String str : result) {
language
System.out.println(str);
replace():
• The replace() method searches a string for a specified character, and returns a new
string where the specified character(s) are replaced.
contains()
• The contains() method checks whether a string contains a sequence of characters.
• Returns true if the characters exist and false if not.
String myStr = "Hello";
System.out.println(myStr.contains("Hel")); // true
System.out.println(myStr.contains("Ho")); // false
import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter A string");
String str=sc.next();
String rev="";
int n=str.length();
for(int i= n-1; i>=0; i--) {
rev=rev+str.charAt(i);
}
System.out.println("After Reverse="+rev);
}}
import java.util.Scanner;
public class WordCharacterCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = scanner.nextLine();
Class:
•Class is a template/blueprint from which you can create an individual object.
•It is a user-defined data type which provides a common structure to all its objects
•A class contains variables and methods
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
type method_name(parameter-list)
{
// body of method
}
Create a FitnessTracker class that includes data fields for a fitness activity,
the number of minutes spent participating, and the date. The class includes
methods to get each field. In addition, create a default constructor that
automatically sets the activity to “running,” the minutes to 0, and the date to
January 1 of the current year. Create an additional overloaded constructor
for the FitnessTracker class. This constructor receives parameters for each of
the data fields and assigns them appropriately. Create a class that
demonstrates each method works correctly.
• Encapsulation can be achieved by declaring all the variables in the class as private and
writing public methods(setter & getter) in the class to set and get the values of
variables.
• It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
• When a variable is declared as static, then a single copy of the variable is created
and shared among all objects of a class.
• When a member is declared static, it can be accessed without help of an object.
• Both methods and variables can be used as static.
• main( ) is declared as static because it must be called before any objects exist.
class Student{
int rollno; class TestStaticMethod{
String name; public static void main(String args[]){
static String college; Student.change();
Student(int r, String n){ Student s1 = new Student(111,"Karan");
rollno = r; Student s2 = new Student(222,"Aryan");
name = n; s1.display();
} s2.display();
static void change(){ }
college = "VIT-AP"; }
}
void display() {
System.out.println(rollno+" "+name+" "+college);} }