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

Module1 and Module 2 Notes OOPS with Java (Updated on 08-10-2024)

The document provides an overview of Java, detailing its history, features, and applications as an object-oriented programming language. It explains the process of compiling and running Java code, the differences between procedure-oriented and object-oriented programming, and key concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it includes practical examples of Java programming, including code snippets for basic operations.
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)
1 views

Module1 and Module 2 Notes OOPS with Java (Updated on 08-10-2024)

The document provides an overview of Java, detailing its history, features, and applications as an object-oriented programming language. It explains the process of compiling and running Java code, the differences between procedure-oriented and object-oriented programming, and key concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it includes practical examples of Java programming, including code snippets for basic operations.
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/ 164

Module-1

An Overview of Java
Java is object oriented programming language. Java was originally developed by James Gosling
at Sun Microsystems. It was released in May 1995 as a core component of Sun Microsystems'
Java platform.

Java has become the most robust programming language because of its amazing features like
platform independence, high performance, Object orientation, support for automatic garbage
management, and many more. Some of the applications of Java in the real world are Desktop
GUI Applications, Mobile Applications, Web applications, Gaming applications, Business
applications, Embedded systems, Cloud applications and Scientific applications, etc.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Java code is converted to machine-readable bytecode through a process called compilation,
which uses a program called a compiler. The bytecode is then interpreted by the Java
Virtual Machine (JVM) and translated into machine code specific to the platform the
application is running on. Here's a breakdown of the steps:

Compile the Java code


Use the Java compiler (javac) to translate the human-readable Java source code into
bytecode. The bytecode is saved with a .class extension. The compiler also acts as an error
detection tool, checking for syntax errors and generating a list of any errors found.
Run the bytecode
Use the java command to invoke the JVM and execute the bytecode. The JVM interprets
the bytecode and translates it into machine code that the host computer can understand
Run the application
The machine code is platform-specific, so the application will run on the intended
platform
The JVM is part of the Java Runtime Environment (JRE). The JRE also includes Java class
libraries and a class loader.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
 Step 1: Writing the code in NetBeans IDE. As you can see in the diagram step 1 is to actually
type the code. In this image above you can see we have our code file as abc.java
 Step 2: Once you have written the code you save itand click Run (if you are using Netbeans IDE
otherwise you compile the code in the command prompt by using the command javac abc.java).
This invokes the Java Compiler. The compiler checks the code for syntax errors and any other
compile time errors and if no error is found the compiler converts the java code into an
intermediate code(abc.class file) known as bytecode. This intermediate code is platform
independent (you can take this bytecode from a machine running windows and use it in any
other machine running Linux or MacOS etc). Also this bytecode is an intermediate code, hence it
is only understandable by the JVM and not the user or even the hardware /OS layer.
 Step 3: This is the start of the Run Time phase, where the bytecode is loaded into the JVM by
the class loader(another inbuilt program inside the JVM).
 Step 4: Now the bytecode verifier(an inbuilt program inside the JVM) checks the bytecode for
its integrity and if not issues are found passes it to the interpreter.
 Step 5: Since java is both compiled and interpretted language, now the interpreter inside the
JVM converts each line of the bytecode into executable machine code and passed it to the
OS/Hardware i.e. the CPU to execute.

The language was initially called Oak after an oak tree that stood outside
Gosling's office. Later the project went by the name Green and was finally
renamed Java, from Java coffee, a type of coffee from Indonesia.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Difference between Procedure Oriented and Object Oriented Programming
Languages
Procedure Oriented Programming Language Object Oriented Programming Language
It emphasis on doing things in terms of
It emphasis on data instead of procedure.
procedure i.e. algorithms.
Larger programs are divided into smaller
Larger programs are divided into objects.
programs called functions.
Data is not hidden i.e. data can be moved from Data is hidden. i.e. only functions inside
within or outside the functions. the class can operate on the data.
Follows top down programming approach Follows bottom up programming approach

Difficult in the extension of written code. Written code can be extended easily.

Reusability of the written code is difficult. Reusability of the code is easier.


Difficult to add new data and functions into New data and functions can be added so
existing program. easily.
Access specifier are "public", "private",
No access specifier observed.
"protected".
It overloads functions, constructors, and
Neither it overload functions nor operators.
operators.
Inheritance achieved in three modes public
Their is no provision of inheritance.
private and protected.
Data is hidden in three modes public,
There is no proper way of hiding the data, so
private, and protected. hence data security
data is insecure
increases.
Global data is shared among the functions in Data is shared among the objects through
the program. the member functions.
C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Procedure Oriented Programming Language:

What is POP?

Procedural Programming can be defined as a programming model which is derived


from structured programming, based upon the concept of calling procedure.
Procedures, also known as routines, subroutines or functions, simply consist of a
series of computational steps to be carried out.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Object Oriented Programming

What is OOP?

Object-oriented programming (OOP) is a computer programming model that


organizes software design around data, or objects, rather than functions and
logic.

Object-oriented programming (OOP) is a style of programming characterized by


the identification of classes of objects closely linked with the methods (functions)
with which they are associated. It also includes ideas of inheritance of attributes
and methods.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
1. Process-Oriented Model

2. Object-Oriented Model

https://www.mycplus.com/tutorials/object-oriented-
programming/polymorphism/
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Abstraction:

Abstraction is the process of hiding the internal details of an application from


the outer world. Abstraction is used to describe things in simple terms. It's used to
create a boundary between the application and the client programs.

Example:

A key concept in object-oriented programming (OOP) is abstraction. It


involves hiding an object's implementation details and only showing the user the
information that is absolutely necessary. This makes it simpler to read and
maintain the code. Consider the class "Car," for instance.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
The Three OOP Principles:

1. Encapsulation
2. Inheritance
3. Polymorphism

1. Encapsulation

Encapsulation is one of the core concepts in object-oriented programming


and describes the bundling of data and methods operating on this data into
one unit.

2. Inheritance

Inheritance is the concept in OOPs in which one class inherits the attributes
and methods of another class. The class whose properties and methods are
inherited is known as the Parent class. And the class that inherits the properties
from the parent class is the Child class.

3. Polymorphism

Polymorphism is one of the core concepts in OOP languages and describes the
concept of using different classes with the same interface.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Creating Programs in Java

We can create a program using Text Editor (Notepad) or IDE (NetBeans)


// This is a simple Java program.

// FileName : "C:\CSK_J>HelloWorld.java".

class HelloWorld {

// Your program begins with a call to main().

// Prints "Hello, World" to the terminal window.

public static void main(String args[])

System.out.println("Hello, World!");

Compiling the Program in Java

To compile the program, we must run the Java compiler (javac), with the name of the
source file on the “command prompt” like as follows
C:\>csk_j>javac HelloWorld.java
If everything is OK, the “javac” compiler creates a file called “ HelloWorld.class”
containing the byte code of the program.

Running the Program in Java

C:\>csk_j>java HelloWorld [Enter Key]

Helo World!

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
The process of Java programming can be simplified in three steps:
 Create the program by typing it into a text editor and saving it to a file –
HelloWorld.java.
 Compile it by typing “javac HelloWorld.java” in the terminal window.
 Execute (or run) it by typing “java HelloWorld” in the terminal window.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Java Program Addition Of Two Numbers – 4 Ways | Programs

https://javatutoring.com/java-program-addition-of-two-numbers/

History of Java:

Latest version:

https://www.codejava.net/java-se/java-se-versions-
history#:~:text=This%20article%20gives%20you%20an,Java%20version%20on%20your
%20computer).

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Know it:

James Gosling, inventor of the Java programming language and the virtual
machine, skipped many of his high school math and physics classes. His
teachers knew it, but they still gave him A’s. That‟s because, said Gosling, they
knew why he was missing the classes. He was working for the physics
department at the University of Calgary writing software for satellites.

“That attitude was a huge influence on me,” said Gosling. “They understood
that learning happens where it happens and that I was getting more out of these
out-of-school activities than I would ever get from their formal teaching.”

As a young teen, Gosling caught the computer bug because of all these
machines could do. “I loved toys,” he said, especially nine-track tape drives,
flatbed plotters, and a paper-tape reader spotted on a tour of the University of
Calgary. He was 14 and enthralled by the large computer there with 8k of RAM
with all its “whirring and blinking things.”

Soon, Gosling was sneaking into the college‟s computer lab and teaching
himself to write software. Looking back on his own march into the computer
field, he believes today’s students should “do what’s fun,” he said.

He’d definitely like more students to enter the computer software field.
“Lots of kids have a fairly negative view of the profession for reasons that
don‟t make any sense. They saw the dot-com bust and thought everyone got
fired. Relatively few did, and those that did lose jobs found other software
engineering jobs elsewhere,” Gosling said.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
“What happened was not a collapse of the software industry. It was a
winnowing-out of some goofy business models. Things that worked survived.
There are more people writing computer software now then there were before
the bust. The Internet didn‟t get turned off. Students are scared of trying the
profession because they fear it doesn‟t have a future, when in fact it‟s a very
healthy, enjoyable, and well-paying profession. ”

1. Java code to find addition of two given integers 10 and 20.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Java code to find read and display two integers on terminal.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
import java.util.Scanner;

public class MatrixProgram {

public static void main(String args[]) {


System.out.println("Please enter the rows in the matrix");
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
System.out.println("Please enter the columns in the matrix");
int c = sc.nextInt();

int[][] first=new int[r][c];


int[][] second=new int[r][c];

System.out.println("\nEnter the first matrix elements\n");


readMatrix(first,sc);

System.out.println("\nEnter the second matrix elements\n");


readMatrix(second,sc);

sc.close();

System.out.println("\nFirst Matrix\n");
printMatrix(first);

System.out.println("\nSecond Matrix\n");
printMatrix(second);

sum(first,second);

private static void sum(int[][] first,int[][] second){


int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
sum[r][c] = first[r][c] + second[r][c];
}
}

System.out.println("\nSum of Matrices:\n");
printMatrix(sum);

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
private static void readMatrix(int[][] matrix,Scanner sc){
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
System.out.println(String.format("Enter [%d][%d] integer", r, c));
matrix[r][c] = sc.nextInt();
}
}

private static void printMatrix(int[][] matrix){


for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[i].length;j++){
System.out.print(matrix[i][j]+"\t");
}

System.out.println();
}

}
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Lexical =relating to the words
Lexical Issues
In Java, lexical issues refer to problems related to the lexical structure or rules of
the programming language. Here are some common lexical issues in Java:
Reserved Keywords: Java has a set of reserved keywords that cannot be used as
identifiers (variable names, method names, class names, etc.)

Now we will see atomic elements of java. Java programs are a collection of white space
identifiers, comments, literals, operators, separators, and
keywords. The operators are described in the next article

Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation

rules. For example, the Example program could have been written all on one line or in any other

strange way you felt like typing it, as long as there was at least one whitespace character between

each token that was not already delineated by an operator or separator. In java, whitespace is a

space, tab, or new line.

Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be any

descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign

characters. They must not begin with a number, lest they be confused with a numeric literal. Again,

java is case-sensitive, so VALUE is a different identifier the Value.Some examples of valid identifiers

are:

AvgTemp, count, a4, $test, this_is_ok

Invalid variable names include:

2count, high-temp, Not/ok

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Literals
Using a literal representation of it creates a constant value in java. For example, here are some

literals:

100, 98.6 'X' "This is a test"

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a

character constant, and the last is a string. A literal can be used anywhere a value of its type is

allowed.

Comments
Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Ex:

// This is a comment

System.out.println("Hello World");

Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

Ex:

/* The code below will print the words Hello World

to the screen, and it is amazing */

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
System.out.println("Hello World");

Java Keywords
Java Reserved Keywords
Java has a set of keywords that are reserved words that cannot be used as variables,
methods, classes, or any other identifiers:

Keyword Description

abstract A non-access modifier. Used for classes and methods: An


abstract class cannot be used to create objects (to access it, it
must be inherited from another class). An abstract method can
only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from)

assert For debugging

boolean A data type that can only store true and false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated by try statements

char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

double A data type that can store whole numbers from 1.7e−308 to
1.7e+308

else Used in conditional statements

enum Declares an enumerated (unchangeable) type


OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Keyword Description

exports Exports a package with a module. New in Java 9

extends Extends a class (indicates that a class is inherited from another


class)

final A non-access modifier used for classes, attributes and methods,


which makes them non-changeable (impossible to inherit or
override)

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

float A data type that can store whole numbers from 3.4e−038 to
3.4e+038

for Create a for loop

goto Not in use, and has no function

if Makes a conditional statement

implements Implements an interface

import Used to import a package, class or interface

instanceof Checks whether an object is an instance of a specific class or an


interface

int A data type that can store whole numbers from -2147483648 to
2147483647

interface Used to declare a special type of class that only contains


abstract methods

long A data type that can store whole numbers from -


9223372036854775808 to 9223372036854775808

module Declares a module. New in Java 9

native Specifies that a method is not implemented in the same Java


source file (but in another language)

new Creates new objects

package Declares a package

private An access modifier used for attributes, methods and

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Keyword Description

constructors, making them only accessible within the declared


class

protected An access modifier used for attributes, methods and


constructors, making them accessible in the same package and
subclasses

public An access modifier used for classes, attributes, methods and


constructors, making them accessible by any other class

requires Specifies required libraries inside a module. New in Java 9

return Finished the execution of a method, and can be used to return a


value from a method

short A data type that can store whole numbers from -32768 to
32767

static A non-access modifier used for methods and attributes. Static


methods/attributes can be accessed without creating an object
of a class

strictfp Restrict the precision and rounding of floating point calculations

super Refers to superclass (parent) objects

switch Selects one of many code blocks to be executed

synchronized A non-access modifier, which specifies that methods can only be


accessed by one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

transient A non-accesss modifier, which specifies that an attribute is not


part of an object's persistent state

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value

volatile Indicates that an attribute is not cached thread-locally, and is

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Keyword Description

always read from the "main memory"

while Creates a while loop

Note: true, false, and null are not keywords, but they are literals and reserved
words that cannot be used as identifiers.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Discuss Structure of Java program and its elements.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Data Types in Java
Data types are divided into two groups:

 Primitive data types — includes byte, short, int, long , float, double,
char, boolean

 Non-primitive data types — Examples of non-primitive types


are Strings, Arrays, Classes, Interface, etc.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
https://selinnurgolen.medium.com/data-types-in-java-e27568694e15

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
char
The char data type is used to store a single character. The character must be surrounded by single
quotes, „A‟ , „b‟, „5‟, „ „,etc.
Size: 1 byte (8 bits)
Range of values: -128 to 127
Example:
public class Main {
public static void main(String[] args)
{
char a = 65, b = 66, c = 67;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Output:
A
B
C

int

Integer types, stores whole numbers, positive or negative without decimals.

Size: 4 bytes (32 bits)

Range of Values: -2,147,483,648 to 2,147,483,647

Byte

The byte data type can store whole numbers from -128 to 127.

Size: 1 byte (8 bits)

Range of Values: -128 to 127.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Example:

class demo {
public static void main(String args[])
{
byte a = 126;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
}
}
Output:
126
127
-128
-127
short

The short data type can store whole numbers from -32768 to 32767

Size: 2 bytes (16 bits)

Range of Values: -32,768 to +32,767

long

The range of values supported by long is more than range of values supported by int type.

Size: 8 bytes (32 bits)

float

This data type helps to store numbers with fractional part. It manages 7 digits of accuracy in
fractional part.

Size: 4 bytes (32 bits)

double

This data type helps to store numbers with fractional part. It manages 16 digits of accuracy in
fractional part.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Size: 8 bytes (64 bits)

boolean

The variable of the type Boolean can store a value either true or false.

public class Main {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}

Output:

true

false

String

Strings are defined as an array of characters.

// Declare String without using new operator

String s = "CentralPark";

// Declare String using new operator

String s1 = new String("CentralPark");

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Variables in Java

Variables are the data containers that save the data values during Java program execution. Every
Variable in Java is assigned a data type that designates the type and quantity of value it can hold.
A variable is a memory location name for the data. In Java, all variables must be declared
before use.

Declaration of Java Variables:

Syntax:

datatype <variable_name>

Here,

datatype : Type of data that can be stored in this variable.


variable_name: Valid identifier.

Examples (1):

int salary;

float percentage;

char ch;

Examples (2):

float simpleInterest; // Declaring float variable

int time = 10, speed = 20; // Declaring and initializing integer variable

char var = 'h'; // Declaring and initializing character variable

Rules to Declare a Variable


1. A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
two special characters such as _ underscore and $ dollar sign.
2. The first character must not be a digit.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive.
6. There is no limit on the length of a variable name but by convention, it should be between
4 to 15 chars.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Types of Variables in Java

1. Local Variables
2. Instance Variables
3. Static Variables(Class Variables)

1. Local Variables

These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.

The scope of these variables exists only within the block in which the variables are declared,
i.e., we can access these variables only within that block.

// Java Program to implement Local Variables


class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output:
Local Variable: 10

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
public class LocalVariable {
public static void main(String[] args)
{
// x is a local variable
int x = 10;

// message is also a local


// variable
String message = "Hello, world!";

System.out.println("x = " + x);


System.out.println("message = " + message);

if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
System.out.println(result);
}

// Uncommenting the line below will result in a


// compile-time error System.out.println(result);

for (int i = 0; i < 3; i++) {


String loopMessage= "Iteration "+ i; // loopMessage is a local variable
System.out.println(loopMessage);
}

// Uncommenting the line below will result in a


// compile-time error
// System.out.println(loopMessage);
}
}
Output:
x=10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
2. Instance Variables

Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.

 As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
 Initialization of an instance variable is not mandatory. Its default value is dependent
on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for
Wrapper classes like Integer it is null, etc.
 Instance variables can be accessed only by creating objects.

Example:
// Java Program to demonstrate
// Instance Variables
import java.io.*;

class GFG {

// Declared Instance Variable


public String geek;
public int i;

public GFG()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Shubham Jain";
}

// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();

// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is " + name.i);

}
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output
Geek name is: Shubham Jain
Default value for int is 0

3. Static Variables

Once the object of class is created, data storage is created and methods become available.
Sometimes, we need a method that is not associated with any particular object of the class and
can call even if no objects are created.
For this purpose, we can fulfill both needs with the help of static keyword in Java.
When we declare a member as static, it means that it is not tied to any particular object of
that class. It can be accessed before any objects of its class are created and without
reference to any object.
We can declare methods, variables, and blocks to be static. The most common example of a
static member inside a class is main( ) method.
main( ) method is declared as static because it must be called before any objects exist.
Let us take an example program where we will declare a variable as static and access it by using
class name and object reference variable.

Program code 1:
package staticVariable;
public class Student
{
// Declare a static variable id having data type int and assign it the value 20.
static int id = 20;

// Main method.
public static void main(String[] args)
{
// Create an object of the class Student.
Student s = new Student();
// Call static variable using object reference variable s and store it by variable x with data type int.
int x = s.id;

// Print on the console.


System.out.println(x);
// Now call static variable id using the class name.
System.out.println(Student.id);
}
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output:
20
20
As you can see in the above program, we have printed the value of id by using object reference
and class name.

Static variables are also known as class variables. These variables are declared similarly to
instance variables. The difference is that static variables are declared using the static keyword
within a class outside of any method, constructor, or block.

 Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.

Example for static variable:

Output:
1
2
3

Example:
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// Java Program to demonstrate

// Static variables

import java.io.*;

class GFG {

// Declared static variable

public static String geek = "Shubham Jain";

public static void main(String[] args)

// geek variable can be accessed without object

// creation Displaying O/P GFG.geek --> using the

// static variable

System.out.println("Geek Name is : " + GFG.geek);

// static int c=0;

// above line,when uncommented,

// will throw an error as static variables cannot be

// declared locally.

Output

Geek Name is : Shubham Jain

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Differences Between the Instance Variables and the Static Variables

Each object will have its own copy of an instance variable, whereas we can only have one copy
of a static variable per class, irrespective of how many objects we create. Thus, static variables
are good for memory management.

Changes made in an instance variable using one object will not be reflected in other objects as
each object has its own copy of the instance variable. In the case of a static variable, changes will
be reflected in other objects as static variables are common to all objects of a class.

We can access instance variables through object references, and static variables can be accessed
directly using the class name.

Instance variables are created when an object is created with the use of the keyword „new‟ and
destroyed when the object is destroyed. Static variables are created when the program starts and
destroyed when the program stops.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Syntax: Static and instance variables

class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

https://www.geeksforgeeks.org/variables-in-java/
public class scope {
static int y=100;
public static void method1()
{
int x=20;
System.out.println("x="+x);
y++;
}
public static void main(String [] args)
{
int x=10;
System.out.println("x="+x);
System.out.println("y="+y);
method1();
System.out.println("x="+x);
System.out.println("y="+y);
}
}
Output:
x=10
y=100
x=20
x=10
y=101

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Arrays in Java

A group of related data elements of similar type is called array.

Arrays in Java work differently than they do in C/C++.

Arrays in Java

 In Java, all arrays are dynamically allocated.


 Arrays may be stored in contiguous memory [consecutive memory locations].
 Since arrays are objects in Java, we can find their length using the object property length.
This is different from C/C++, where we find length using sizeof.
 A Java array variable can also be declared like other variables with [ ] after the data type.
 The variables in the array are ordered, and each has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method parameter.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Creating, Initializing, and Accessing an Arrays

One-Dimensional Array

“A linear list of data elements of similar type stored in computer‟s continuous memory with a
common name but with different index starts from 0 and ends with array_size-1.”

The general form of a one-dimensional array declaration is

Syntax:

datatype var-name[];

datatype[] var-name;

Example:

// both are valid declarations


int intArray[];
int[] intArray;
// array might of the type byte , short, boolean, long, float, double, char etc.

int a[]; or int [] a;


float b[]; or float [] b;
char ch[]; or char [] ch;

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Note:

Although the first declaration establishes that int Array is an array variable, no actual array
exists. It merely tells the compiler that this variable (int Array) will hold an array of the integer
type. To link int Array with an actual, physical array of integers, you must allocate one using
new and assign it to int Array.

var-name = new type [size];

Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in oneint[]
int Array = new int[20];

int a[]; or int [] a;


a=new int[10]; // array of the size 10.

float b[]; or float [] b;


b=new float[20]; // array of the size 20

char ch[]; or char [] ch;


c=new ch[15]; // array of the size 15

Array Literal in Java


In a situation where the size of the array and variables of the array are already known, array
literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java.
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total
array size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);

// Java program to illustrate creating an array


// of integers, puts some values in the array,
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Multidimensional Arrays in Java
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other arrays. These are also known as Jagged Arrays. A multidimensional
array is created by appending one set of square brackets ([]) per dimension.

Syntax of Java Multidimensional Array

There are 2 methods to declare Java Multidimensional Arrays as mentioned below:

Syntax:
-- datatype [][] array_variable;
-- datatype array_variable[][];

// Java Program to demonstrate


// Java Multidimensional Array
import java.io.*;

// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);

// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Multidimensional Array Declaration

int[][] intArray = new int[10][20]; //a 2D array or matrix

int[][][] intArray = new int[10][20][10]; //a 3D array

// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
Output
2 7 9
3 6 1
7 4 2

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example, the below
program passes the array to method sum to calculate the sum of the array’s values.

// Java program to demonstrate


// passing of array to method

public class Test {


// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum += arr[i];

System.out.println("sum of array values : " + sum);


}
}
Output
sum of array values : 15

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Returning Arrays from Methods
As usual, a method can also return an array. For example, the below program
returns an array from method m1.

// Java program to demonstrate


// return of array from method

class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}

Output
1 2 3

https://www.geeksforgeeks.org/arrays-in-java/

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Operators in Java

1. Arithmetic Operators in java


Arithmetic operators are used to perform arithmetic operations on
primitive data types. JAVA has some arithmetic operators:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Example:

import java.util.Scanner;

public class mat_operations


{
public static void main(String args[])
{
int a, b, res;
Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");


a = scan.nextInt();
b = scan.nextInt();

res = a + b;
System.out.println("Addition = " +res);

res = a - b;
System.out.println("Subtraction = " +res);

res = a * b;
System.out.println("Multiplication = " +res);
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
res = a / b;
System.out.println("Division = " +res);
}
}

Output:
Enter Two Numbers : 34 79
Addition = 113
Subtraction = -45
Multiplication = 2686
Division = 0

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
2. Relational Operators

The Java Relational operators are used by programmer to compare two


values before processing the inputs to get desired results. The result of
relational expression will be either True (1) or False(0).

Programming Examples:

public class relatiop {


public static void main(String[] args) {
int num1 = 12, num2 = 4;
System.out.println("num1 == num2 = " + (num1 == num2) );
System.out.println("num1 != num2 = " + (num1 != num2) );
System.out.println("num1 > num2 = " + (num1 > num2) );
System.out.println("num1 < num2 = " + (num1 < num2) );
System.out.println("num1 >= num2 = " + (num1 >= num2) );
System.out.println("num1 <= num2 = " + (num1 <= num2) );
}
}
Output:
num1 == num2 = false
num1 != num2 = true
num1 > num2 = true
num1 < num2 = false
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
num1 >= num2 = true
num1 <= num2 = false

3. Logical Operators

These helps to combine two or more relational expressions in to a single


expression to take certain decisions while solving problems by writing programs
in Java. The result of relational expression will be either True (1) or False (0).

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
public class Test {

public static void main(String args[]) {


boolean a = true;
boolean b = false;

System.out.println("a && b = " + (a&&b));


System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output:
a && b = False
a || b = True
!(a && b) = True

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
4. Assignment Operator (=)
To assign a value to a variable, use the basic assignment operator (=). It is the
most fundamental assignment operator in Java. It assigns the value on the right
side of the operator to the variable on the left side.
Examples:
int x = 10;
float ans=12.09;
char ch=’A’;
Shorthand Assignment Operator (+=)
To add a value to a variable and subsequently assign the new value to the same
variable, use the addition assignment operator (+=). It takes the value on the right
side of the operator, adds it to the variable's existing value on the left side, and
then assigns the new value to the variable.

Example
int x = 10;
x += 5;

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
public class AssignmentOperatorsExample {
public static void main(String[] args) {
int x = 10;
int y = x;
System.out.println("y = " + y);
x += 5;
System.out.println("x += 5: " + x);
x -= 3;
System.out.println("x -= 3: " + x);
x *= 2;
System.out.println("x *= 2: " + x);
x /= 4;
System.out.println("x /= 4: " + x);
x %= 3;
System.out.println("x %= 3: " + x);
}
}
Output:

y = 10
x += 5: 15
x -= 3: 12
x *= 2: 24
x /= 4: 6
x %= 3: 0

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
5. Increment and Decrement Operators:

These are unary operators. These help us to increment or decrement a variable by


1.

The increment operator ++ increases the value of a variable by 1. Similarly, the


decrement operator -- decreases the value of a variable by 1.

a=5

++a; // a becomes 6

a++; // a becomes 7

--a; // a becomes 6

a--; // a becomes 5

++ and -- operator as prefix and postfix


If you use the ++ operator as a prefix like: ++var, the value of var is incremented
by 1; then it returns the value.
If you use the ++ operator as a postfix like: var++, the original value of var is
returned first; then var is incremented by 1.
Example:
class Operator {
public static void main(String[] args) {
int var1 = 5, var2 = 5;

// 5 is displayed
// Then, var1 is increased to 6.
System.out.println(var1++);

// var2 is increased to 6
// Then, var2 is displayed
System.out.println(++var2);
}
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output:
5
6

6. Conditional operator (?:)

It is ternary operator. It makes the use of two operators and three operands. It
does the work of if …else statement.

Syntax:

Expression-1?Expression-2:Expression-3;

If expression-1 is True then it executes Expression-2; otherwise, Expression-3.

Example:

int a=5,b=10,ans;

ans=(a>b?a:b);

System.out.println(“Largest number is”+ans);

Output:

Largest number is 10

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Example-2:

public class condiop {

public static void main(String[] args) {

String out;

int a = 6, b = 12;

out = a==b ? "Yes":"No";

System.out.println("Ans: "+out);

Output:

Ans=No

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Bitwise operators:

The operators, which are used to perform low level operations with binary digits
are called bitwise operators. These helps to write system level programs. i.e. shift
the binary digits(bits) to right or left by specified number positions, to change the
bit state from True to False or vice-versa and to negate, etc. We can apply these
to the integer types – long, int, short, char, and byte.

Bitwise operators work on a binary equivalent of decimal numbers and perform


operations on them bit by bit as per the given operator.

Bitwise AND Operator (&) in Java

This operator is used to perform bitwise AND operation between two integral
operands. The AND operator is represented by a symbol & which is called
ampersand. It compares each bit of the left operand with the corresponding bit of
right operand.
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
package javaProgram;

public class BitwiseANDExample {

public static void main(String[] args)

int a = 10, b = 11;

System.out.println("(10 & 11): " +(a & b));

Output:

(10 & 11): 10


OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Bitwise OR Operator ( | ) in Java

This operator is used to perform OR operation on bits of numbers. It is


represented by a symbol | called pipe symbol.
In OR operation, each bit of first operand (number) is compared with the
corresponding bit of the second operand.

package javaProgram;

public class BitwiseORExample {

public static void main(String[] args)

int a = 20, b = 10;

System.out.println("(20 | 10): " +(a | b));

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
}

Output:

(20 | 10): 30

Bitwise Exclusive OR (XOR) Operator (^)

The operator ^ performs exclusive OR (XOR) operation on the bits of


numbers. This operator compares each bit first operand (number) with the
corresponding bit of the second operand.
Exclusive OR operator is represented by a symbol ^ called cap. Let us consider
the truth table of the XOR operator to understand exclusive OR operation.

package javaProgram;

public class BitwiseXORExample {

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
public static void main(String[] args)

int a = 20, b = 10;

System.out.println("(20 ^ 10): " +(a ^ b));

Output:

(20 ^ 10): 30

Bitwise NOT operator (~)

The bitwise NOT operator in Java is basically an inverter. It returns the reverse
of its operand or value. It converts all 1s to 0s, and all the 0s to 1s. Therefore, it
is also called unary operator or bit flip or one’s complement operator.
package javaProgram;

public class BitwiseOperatorsEx {

public static void main(String[] args)

int a = 2, b = 10;

System.out.println("(2 & 10): " +(a & b));

System.out.println("(2 | 10): " +(a | b));

System.out.println("(2 ^ 10): " +(a ^ b));


OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
System.out.println("~10: " +~b);

Output:

(2 & 10): 2

(2 | 10): 10

(2 ^ 10): 8

~10: -11

Note:

In Java, the bitwise NOT (~) operator is applied to the binary representation of the integer. Java uses 32-
bit signed integers (in two's complement form) to represent numbers, which means that after applying
~, the result will typically be negative if the original number was positive.

int a = 2, b = 10;

System.out.println("~10: " + ~b);

Step 1: Binary representation of 10

The decimal number 10 in 32-bit binary is:

Copy code
00000000 00000000 00000000 00001010

Step 2: Apply the bitwise NOT operator (~)

The ~ operator flips every bit. So, applying ~ to 10 will result in:

Copy code
11111111 11111111 11111111 11110101

This is the binary representation of -11 in two's complement form.

Step 3: Explanation of two's complement

In two's complement:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
 The leftmost bit is the sign bit: 1 indicates a negative number, and 0 indicates a positive
number.
 To find the negative value, invert all the bits and add 1.

For 11111111 11111111 11111111 11110101:

 Invert all the bits: 00000000 00000000 00000000 00001010


 Add 1: 00000000 00000000 00000000 00001011 (which equals 11 in decimal).

Thus, the result is -11.

Output:

The output of the code will be:

makefile
Copy code
~10: -11

Java instanceof Operator

The instanceof operator in Java is used to check whether an object is an instance of a particular
class or not.

Its syntax is

objectName instanceOf className;

Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns
false.

class Main {

public static void main(String[] args) {

// create a variable of string type


String name = "Programiz";

// checks if name is instance of String


boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);

// create an object of Main


Main obj = new Main();

// checks if obj is an instance of Main


boolean result2 = obj instanceof Main;
System.out.println("obj is an instance of Main: " + result2);
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
}
}
Run Code

Output

name is an instance of String: true


obj is an instance of Main: true

bitwise left shift operator (<<):

 It is used to shift the bits of a value to the left by adding zeroes to the empty

spaces created at the right side after shifting.

 The bits of first operand are shifted to the left by the number of positions

specified by the second operand.

Example:

class learn {

public static void main(String[] args) {

int a=40,ans;

ans=a<<1;

System.out.println(ans);

Output:

80

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
bitwise left right operator (>>):

 It is used to shift the bits of a value to the right by adding zeroes to the empty

spaces created at the left side after shifting.

 The bits of first operand are shifted to the right by the number of positions

specified by the second operand.

Example-1

Empty places get replaced by 0. As a result, 14 >> 1 = 0000 0111 (which 7).

Example-2

14 >> 2 can be calculated as:

14 0000 1110
14 >> 2 00 0011

Therefore, 14 >> 2 = 0000 0011 (which equals 3). That is, the binary
equivalent of 14 is shifted two bits to the right.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
class HelloWorld {

public static void main(String[] args) {

int a=40,ans;

ans=a>>1;

System.out.println(ans);

Output:

20

Example-3

public class AssignmentOperatorsExample {


public static void main(String[] args) {
int x = 10;
int y = x;
System.out.println("y = " + y);

// Addition assignment operator


x += 5;
System.out.println("x += 5: " + x);

// Subtraction assignment operator


x -= 3;
System.out.println("x -= 3: " + x);

// Multiplication assignment operator


x *= 2;
System.out.println("x *= 2: " + x);

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// Division assignment operator
x /= 4;
System.out.println("x /= 4: " + x);

// Modulus assignment operator


x %= 3;
System.out.println("x %= 3: " + x);

// Left shift assignment operator


x <<= 2;
System.out.println("x <<= 2: " + x);

// Right shift assignment operator


x >>= 1;
System.out.println("x >>= 1: " + x);

// Bitwise AND assignment operator


x &= 5;
System.out.println("x &= 5: " + x);

// Bitwise OR assignment operator


x |= 2;
System.out.println("x |= 2: " + x);

// Bitwise XOR assignment operator


x ^= 1;
System.out.println("x ^= 1: " + x);
}
}
Output:

y = 10
x += 5: 15
x -= 3: 12
x *= 2: 24
x /= 4: 6
x %= 3: 0
x <<= 2: 0
x >>= 1: 0
x &= 5: 0
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
x |= 2: 2
x ^= 1: 3

Precedence and Associativity of operators

Precedence:

Each operator is having a priority value for its execution by machine. It


determines the order in which operations are performed in an expression.

For example, in Java, 1 + 2 * 3 is treated as 1 + (2 * 3). This is because the


multiplication operator has a higher precedence than the addition operator.
Associativity:

Associativity is the order in which operators are executed, either left to right or
right to left. If the operators are having same precedence value then it
determines the direction in which an expression is evaluated in a program.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Java Type Casting

Type casting is a powerful feature in Java that allows us to convert variables from
one data type to another.

Implicit type casting, also known as widening conversion, is done automatically


by the compiler when there is no loss of data.

Explicit type casting in Java, on the other hand, requires manual intervention and
is used when there is a possibility of data loss.

Understanding type casting is essential for writing efficient and error-free Java
programs.

In Java, there are two types of casting:

Implicit type casting(conversion): lower to higher data type conversion takes


place.

Widening Casting (automatically) - converting a smaller type to a larger type size


OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
byte -> short -> char -> int -> long -> float -> double

Explicit type casting(conversion): lower to higher or higher to lower data type


conversion takes place.

Narrowing Casting (manually) - converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte

Example-1

public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
System.out.println(myDouble); // Outputs 9.0

Output:
9
9.0

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

}
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output:

9.78

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Control Statements:

As we know, machine executes given set of instructions sequentially from top to


bottom. It is necessary for the programmer to change this execution flow as per
the need to solve a given complex problem and is possible by control statements
supported by Java. They are

Java Selection Statements

1. if statement
a. simple if
b. if…else
c. nested if
d. else if ladder
2. switch statement
3. conditional operator statement

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Selection Statements
In sequential control, all the statements are executed in the order in which they
are written sequentially in a program from top to bottom. However, it is
necessary for the programmer to execute or skip certain set of statements based
on certain conditions and is possible by using branching statements. These
branching statements are also called as conditional or decision making
statements.
Java supports the following types of selection statements for the
programmers to take decisions.
1. if (One way conditional statement)

2. if else (Two way conditional statement)

3. nested if (Multi way conditional statement)

4. else if ladder (Multi way conditional statement)

1. if
This is one-way selection statement. It helps the programmer to execute or skip
true block of statements based on given condition. The syntax, flowchart and
examples are as follow.

Syntax:
if (condition)
{
true block of statements;
}
Statements-X;

In the above syntax, the given


condition will be evaluated for TRUE or
FALSE by machine, if it is True, then the
true block statements are executed;
otherwise, no.
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Programming Examples on “if”

// Java program to illustrate If statement

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("10 is less than 15");

System.out.println("Outside if-block");
}
}
Output
10 is less than 15
Outside if-block

// Java program to illustrate If statement

class IfDemo {
public static void main(String args[])
{
String str = "GeeksforGeeks";
int i = 4;

// if block
if (i == 4) {
i++;
System.out.println(str);
}

// Executed by default
System.out.println("i = " + i);
}
}
Output
GeeksforGeeks

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
i = 5

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
2) if else: It is two way selection statement. It executes either true block of statements or false
block of statements based on a given condition. It is used by programmers to select one from
two alternatives.
Syntax:
if (condition)
{
True block of statements;
}
else
{
False block of statements;
}
Statement-X;

In the above syntax, the given condition will be


evaluated for TRUE or FALSE by machine, if it is
True, then the True Block of Statements are
executed; otherwise, False Block of Statements are
executed.

Programming Examples on “if…else”


public class IfElseExample {
public static void main(String[] args) {
boolean a = true;
boolean b = false;

if (a) {
System.out.println("a is true");
} else {
System.out.println("a is false");
}

if (b) {
System.out.println("b is true");
} else {
System.out.println("b is false");
}
}
}
Output
a is true
b is false
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "Good evening."

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
3. Nested if: It is a multi-way selection statement. In this type, the programmer
uses simple if or if … else statement within another if statement. Hence, it is
called nested if statement. It helps to select one from many alternatives based on
given conditions. The syntax, flowchart and examples are as follow.
Syntax:
if (exprn-1)
{
if (exprn-2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
Statement3;
}
Statement-X;

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Programming Examples on “nested if”

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG
{
public static void main(String args[])
{
int a=10;
int b=20;

if(a==10){
if(b==20){
System.out.println("GeeksforGeeks");
}
}
}
}
Output
GeeksforGeeks
import java.util.*;
import java.lang.*;

class GFG
{
public static void main(String args[])
{
int a=10;
int b=20;

if(a==10){

if(b!=20){
System.out.println("GeeksforGeeks");
}

else{
System.out.println("GFG");
}
}
}
}
Output
GFG

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
4. The else .. if ladder or cascaded if statement: It is another multi way selection statement
available in C to select one from many alternative. It helps the programmer to use another if
else statement only within the else part of the previous if else statement. So, it is called else if
ladder or cascaded if statement. The syntax, flowchart and examples are as follow.
Syntax:
if (expression-1)
statement1;
else if (expression -2)
statement2;
else if (expression -3)
statement3;
else
default statements;
statement-X;

In the above syntax, the


expression-1 will be evaluated by
machine for True or False, if it is True
then Statement-1 executes followed by
statement-x. Otherwise; other
expressions will be evaluated for
True/False to execute concerned block
for the True condition. If, all the
expressions are False then default
statement will be executed by
machine.

Programming Examples on “else if ladder”


// Java program to illustrate if-else-if ladder

import java.io.*;

class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;

// condition 1
if (i == 10)
System.out.println("i is 10\n");

// condition 2
else if (i == 15)
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
System.out.println("i is 15\n");

// condition 3
else if (i == 20)
System.out.println("i is 20\n");

else
System.out.println("i is not present\n");

System.out.println("Outside if-else-if");
}
}
Output:
i is 20
Outside if-else-if

// Java program to illustrate if-else-if ladder


import java.io.*;
class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;

// condition 1
if (i < 10)
System.out.println("i is less than 10\n");

// condition 2
else if (i < 15)
System.out.println("i is less than 15\n");

// condition 3
else if (i < 20)
System.out.println("i is less than 20\n");

else
System.out.println("i is greater than "
+ "or equal to 20\n");

System.out.println("Outside if-else-if");
}
}
Output:
i is greater than or equal to 20

Outside if-else-if
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
The Switch Statement:
It is another multi way statement. It helps the programmer to select one from many
alternatives. It is mainly used by programmers to provide menu options for the end users of a
program to select one from displayed menu options.
Syntax:
switch (value)
{
case value1:
statements block1;
break;
case value2:
statements block2;
break;
case value3:
statements block3;
break;



default:
default statement;
break;
}
Statement-X;

In the above syntax, the passed value will be compared against all the case values one after
another from top to bottom, wherever it matches that associated block of statements executes
; otherwise, default statement executes.

 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

int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
Outputs "Thursday" (day 4)
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
Outputs "Looking forward to the Weekend"
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Loop Statements in Java:

As we know, the statements from written computer program executes


sequentially from top to bottom. However, it is necessary for the programmer to
execute certain block of statements repeatedly till certain condition satisfies
while solving complex problems by using a machine and is possible by loop
control statements. The loop statements are also called as iterative statements.
Java supports the following
1. The while loop (entry controlled or pre-test loop)
1. The do … while loop (exit controlled or post test loop)
2. The for loop (entry controlled or pre-test loop)

1. The while loop: It is one of the entry controlled loop statement. It repeats the
given true-block of statements repeatedly till the given condition is true.
Whenever, the condition becomes false then loop terminates.
The while loop is also called as pre-test loop or event controlled loop.
The syntax, flowchart and examples are as follow.
Entry

Syntax:
Expressio False
while (expression) n

{ True
true - block loop
true - block loop statements; statements

}
Statements-X;
Statement-X

In the above syntax, the given expression will be checked for True or False.
If, it is True, then loop statements are executed repeatedly till the condition
becomes False.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// Java program to find factorial of n using while.

import java.util.Scanner;
class loop1
{
public static void main(String [] args)
{
int n,i; O/p:
Scanner obj=new Scanner(System.in); Enter the value of n: 5
System.out.println(“Enter the value of n: ”); Factorial is 120
n=obj.nextInt();
i=1;
while (i<=n)
{
prod=prod*i;
i=i+1;
}
System.out.println (“Factorial is”+ prod);
}
}

File name: loop1.java

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
2) The do…while loop: It is exit controlled loop statement available in C. It helps the
programmer to repeat certain block of true statements repeatedly till the given condition is
True. Whenever, the given condition becomes False then the loop terminates.
The major difference between while and do…while is that, if the given condition is False
for the first time, then the body of the do while works at least once, whereas no execution of
while loop.
The do while is also called as post test or event controlled loop.
The syntax, flowchart and examples are as follow.
Syntax
do

{
Entry
true block of loop statements;

} while (expression);
true block of loop
statement-X; statements

In the above syntax, the statements from


True
true block of loop statements are executed repeatedly Expressio
n
till the given expression is true.
False

Statement-X

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Differences between while and do while loop
Sl.
While loop do … while loop
No.
It is entry controlled loop statement. It is exit controlled loop statement. It
It repeats the given true block of loop repeats the given true block of loop
statements repeatedly till the given statements repeatedly till the given
1
condition is True. When the condition condition is True. When the condition
becomes False then the loop becomes False then the loop
terminates. terminates.
If the given condition is False for the If the given condition is False for the
2 first time, then no execution of while first time, then body of do while
loop body. works at least once.
Syntax of while loop Syntax of do … while loop
while (condition) do
{ {
3
loop statements; loop statements;
} } while (condition);
statement-x; statement-x;
Flowchart Flowchart

It is also called as pre test or event It is also called as post test or event
6
controlled loop. controlled loop.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
3) The for loop: It is counter controlled loop statement available in C. It helps the programmer
to repeat given true bock of loop statements repeatedly till the given expression is True.
Whenever, the given condition becomes False then loop gets terminated. If the number of
iterations well known by programmers then they prefer the use of for loop statement.
Syntax:
Entry
for (initialization; expression; increment/decrement)

{
for i = 1 to n step 1 False

True block of loop statements;


True

} True Block of
Statements
Statement-x;

Statements-X

Where,
Initialization  Counter will be assigned with initial value. e.g. i=1,i=0,etc.
Expression  The conditional expression on which number of iterations depends. E.g. i<n, i<=n,
etc.
increment/decrement  increment or decrement expression for the counter. E.g. i++, j++, i--, j-
-,etc.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Nested loops: The programmer can use one loop statement within another loop statement and
is called nested loop. It informs the machine to do repetitive work repeatedly. It is used by
programmer to solve complex problems that include complex repetitive steps. The ANSI C
supports 32 times of nesting of loops.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
For-each loop in Java
Last Updated : 16 Feb, 2023

Prerequisite: Decision making in Java


For-each is another array traversing technique like for loop, while loop, do-while loop
introduced in Java5.

It starts with the keyword for like a normal for-loop.


Instead of declaring and initializing a loop counter variable, you declare a variable that is the
same type as the base type of the array, followed by a colon, which is then followed by the
array name.
In the loop body, you can use the loop variable you created rather than using an indexed array
element.

It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:

for (type var : array)


{
statements using var;
}
Simple program with for each loop:

/*package whatever //do not write package name here */

import java.io.*;

class Easy

public static void main(String[] args)

// array declaration

int ar[] = { 10, 50, 60, 80, 90 };

for (int element : ar)

System.out.print(element + " ");


}
}
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output
10 50 60 80 90
The above syntax is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}

Break and Continue Statements

As we know, the loop control statements like while, do while and for are
used by programmers to repeat certain block of statements repeatedly till the
given condition is True. However, it is necessary for the programmers to exit from
loop body before the condition satisfies or to skip certain statements from loop
body based on certain conditions. This is possible by making the use of break and
continue statements available in Java. These are also called as loop interrupt
statements.

The break statement:


This is one of the loop interruption statements. It is used by C programmers
to exit from the body of while, do-while and for loop statements based on certain
condition. i.e loop terminates before the expression of loop becomes False. It is
usually used in association with the if statement. A break is also used to exit from
particular case of switch statement .
Syntax:
while (expression) do for(exp1;exp2;exp3)
{ { {
statements; statements; statements;
if (condition) if (condition) if (condition)
break; break; break;
statements; statements; statements;
} } while (expression); }
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
statement-x; statement-x;
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ statement-x;
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
In the given syntax, whenever the given if (condition) becomes True then
loop terminates followed by statement-x.
Examples:

i=1; O/p: for(i=1; i<=100 ; i++) O/p:


while(i<=100) 1 { 1
{ 2 if ( i = = 5) 2
if ( i = = 5) 3 break; 3
break; 4 4
System.out.println(i); System.out.println(i);
i++; }
}

Write a c program to check whether the unknown number ‘n’ is prime or not
prime.
System.out.println("\n Enter n:");
n=obj.nextInt(); O/p:
for(i=2;i<=n/2;i++)
if(n%i==0) Enter n: 7
{ prime number
flag=0;
break;
} Enter n: 20
} not prime number
if(flag = =1)
System.out.println("prime number");
else
System.out.println("not prime number");
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
The continue statement: It is another loop interrupt statement available in Java. It
helps the programmers to skip certain statements from the body of loop
statements like while, do while and for based on certain conditions.
Syntax:

while (expression) for(exp1;exp2;exp3)


{ {
statements; statements;
if (condition) if (condition)
continue; continue;
statements block2; /* skip */ statements block2; /* skip */
} }
statement-x; statement-x;

In the above syntax, whenever the given if (condition) becomes True then
statements bock-2 are not going to execute.

Examples:

i=1; O/p: for(i=1; i<=5 ; i++) O/p:


while(i<=5) 1 { 1
{ 2 if ( i = = 3) 2
if ( i = = 3) Infinite continue; 4
loop System.out.println(i);
continue; 5
System.out.println(i);
i++; }
}

To find sum of even numbers between 1 to n by using continue inside loop.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Introduction to Class
A class is a blueprint for the object. Before we create an object, we first need to
define the class.

We can think of the class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows, etc. Based on these descriptions we
build the house. House is the object.

Since many houses can be made from the same description, we can create many
objects from a class.

Classes and Objects


In Java, classes and objects are basic concepts of Object Oriented Programming
(OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior.

What is class?
A class in Java is a set of objects which shares common characteristics/ behavior
and common properties or attributes. It is a user-defined blueprint or prototype
from which objects are created.

For example, Student is a class while a particular student named Ravi is an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
 Nested Class
 Interface

Class Declaration in Java


Syntax:
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Where,
Access Specifies: private, public, protected.

Defining objects in Java:

Syntax:
ClassName object = new ClassName();

Example:
add n=new add();

// Java Program for class example

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
class Student {
int id;
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// Java program to illustrate the concept
// of classes and objects

// Class Declaration

public class Dog {


// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}

// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// method 4
public String getColor()
{
return color;
}

public String toString()


{
return ("Hi my name is " + this.getName() +
".\nMy breed, age and color are " + this.getBreed()
+ ", " + this.getAge() + ", " + this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Output:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Different ways to create Objects
 Using new keyword: It is the simplest way to create object. By using this
method, the desired constructor can be called.

Defining objects in Java:

Syntax:
ClassName object = new ClassName();

Example:
add n=new add();

Java Code:

import java.util.Scanner;
public class sum {
public static void main(String[] args) {
// TODO code application logic here
class add
{
int a,b,sum;

Scanner obj=new Scanner(System.in);

add n=new add();


System.out.println("Enter two integers ");
n.a=obj.nextInt();
n.b=obj.nextInt();
n.sum=n.a+n.b;
System.out.println("Addition of two integers = "+n.sum);
}
}

}
Output:
Enter two integers
100
50
Addition of two integers = 150
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
// Java program to illustrate the
// creating and accessing objects
// using new keyword

// base class
class Dog {

// the class Dog has two fields


String dogName;
int dogAge;

// the class Dog has one constructor


Dog(String name, int age)
{
this.dogName = name;
this.dogAge = age;
}
}

// driver class
public class Test {
public static void main(String[] args)
{
// creating objects of the class Dog
Dog ob1 = new Dog("Bravo", 4);
Dog ob2 = new Dog("Oliver", 5);

// accessing the object data through reference


System.out.println(ob1.dogName + ", " + ob1.dogAge);
System.out.println(ob2.dogName + ", " + ob2.dogAge);
}
}

Output:
Bravo, 4
Oliver, 5

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Example:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Output:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
More About Defining objects:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Example 2: To pass object as parameter.

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Call by Value:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Call by Reference:

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Static variables in Java
When a variable is declared as static, then a single copy of the variable is created
and shared among all objects at the class level. Static variables are, essentially,
global variables. All instances of the class share the same static variable.
he static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.

The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
Understanding the problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
24. }
Output:
111 Karan ITS
222 Aryan ITS

OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ
OOPs with Java Notes compiled as per VTU Sby Prof. Chidanand S Kusur, Dept. of CSE, BLDEA’s CET, Vijayapur-03.
https://www.youtube.com/channel/UChfntyymbl_LduCpRAbqmmQ

You might also like