0% found this document useful (0 votes)
50 views24 pages

Unit 1

Uploaded by

Murali Vijay
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)
50 views24 pages

Unit 1

Uploaded by

Murali Vijay
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/ 24

III Sem B.

Sc OOPS USING JAVA

Unit – 1
Introduction to Java
Introduction to Java: Basics of Java programming, Data types, Variables,
Operators, Control structures including selection, Looping, Java methods,
Overloading, Math class, Arrays in java.
What is java?
java is a high-level, general-purpose, object-oriented, and secure programming
language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is
formally known as OAK. In 1995, Sun Microsystem changed the name to Java.
The programming environment of Java consists of three components mainly
JDK
JRE
JVM
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop
applications in Java. When you download JDK, JRE is also downloaded with it.

What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.

What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run
a Java program.

MURALI M, DEPT CS, NCJ BENGALURU Page 1


Page
III Sem B.Sc OOPS USING JAVA
When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code

Features of Java
Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or
reimplemented in Java. For example, pointer and operator overloading are not used in
Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
Robust: Java makes an effort to check error at run time and compile time. It uses a
strong memory management system called garbage collector. Exception handling and
garbage collection features make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines
the access of Java classes.
Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.

Portable: Java Byte code can be carried to any platform. No implementation


dependent features. Everything related to storage is predefined, for example, the size
of primitive data types

MURALI M, DEPT CS, NCJ BENGALURU Page 2


Page
III Sem B.Sc OOPS USING JAVA
1. Class definition
This line uses the keyword class to declare that a new class is being defined.
class HelloWorld {
//
//Statements
}
2. HelloWorld
It is an identifier that is the name of the class. The entire class definition, including all
of its members, will be between the opening curly brace “{” and the closing curly
brace
“}“.
3. main method:
In the Java programming language, every application must contain a main method.
The main function(method) is the entry point of your Java application, and it’s
mandatory in a Java program. whose signature in Java is:
public static void main(String[] args) public: So that JVM can execute the method
from anywhere.
static: The main method is to be called without an object. The modifiers public and
static can be written in either order.
void: The main method doesn’t return anything.
main(): Name configured in the JVM. The main method must be inside the class
definition. The compiler executes the codes starting always from the main function.
String[]: The main method accepts a single argument, i.e., an array of elements of
type String.
Compiling the program Javac HelloWorld.java Running the program java
HelloWorld

COMMENTS IN JAVA
In Java there are three types of comments:
Single-line comments.
//Comments here( Text in this line only is considered as comment )

MURALI M, DEPT CS, NCJ BENGALURU Page 3


Page
III Sem B.Sc OOPS USING JAVA
Multi-line comments.
/*Comment starts contins conties
Comment ends*/

DATA TYPES
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Primitive data types:


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language. There are eight
primitive data types in Java

MURALI M, DEPT CS, NCJ BENGALURU Page 4


Page
III Sem B.Sc OOPS USING JAVA

Non-primitive data types :


The term non-primitive data type means that these types contain “a memory address
of the variable”.
They are also called Reference data types because they cannot store the value of a
variable directly in memory.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
VARIABLES:
A variable in Java is a container that holds the value during the execution of Java
program. In other words, Variable is the name of the memory location reserved for
storing value.

MURALI M, DEPT CS, NCJ BENGALURU Page 5


Page
III Sem B.Sc OOPS USING JAVA
Variable Declaration in Java

Types of Variables in Java

1)Local Variable
A variable that is declared and used inside the body of methods, constructors, or
blocks is called local variable in java. It is called so because local variables are not
available for use from outside.
public void mySchool()
{
// Declaration of local variables.
String schoolName; // Compilation error due to not initializing of value.
System.out.println("Name of School: " +schoolName);
}

2) Instance Variable
A variable that is declared inside the class but outside the body of the methods,
constructors, or any blocks is called instance variable in java.

MURALI M, DEPT CS, NCJ BENGALURU Page 6


Page
III Sem B.Sc OOPS USING JAVA
3) Static variable
❖ A variable which is declared with a static keyword is called static variable in
java. A static variable is also called class variable because it is associated with the
class.
❖ Static variables are always declared inside the class but outside of any methods,
constructors, or blocks.
OPERATORS:
Operators are used to perform operations on variables and values.
Java provides many types of operators which are classified based on the functionality
they provide.
Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.

2.Unary Operators
Unary operators need only one operand. They are used to increment, decrement or
negate a value.

MURALI M, DEPT CS, NCJ BENGALURU Page 7


Page
III Sem B.Sc OOPS USING JAVA
3.Assignment Operator
Assignment operator is used to assign a value to any variable.

4.Relational Operators
These operators are used to check for relations like equality, greater than, less than.

MURALI M, DEPT CS, NCJ BENGALURU Page 8


Page
III Sem B.Sc OOPS USING JAVA
6.Logical Operators
Logical operators are used to determine the logic between variables or values

7.Ternary Operator
A ternary operator evaluates the test condition and executes a block of code based on
the result of the condition. Syntax condition ? expression1 : expression2;
Here, condition is evaluated and
if condition is true, expression1 is executed.
And, if condition is false, expression2 is executed.

Control structures in Java:

if statement: It is a simple decision-making statement. It is used to decide whether the


statement or block of statements should be executed or not. Block of statements will
be executed if the given condition is true otherwise the block of the statement will be
skipped.
public class IfStatementExample
{
public static void main(String arg[])
{
int a = 5; int b = 4;
// Evaluating the expression that will return true or false if (a > b) {
System.out.println("a is greater than b");
}
}

MURALI M, DEPT CS, NCJ BENGALURU Page 9


Page
III Sem B.Sc OOPS USING JAVA
Nested if statement: Nested if statements mean an if statement inside an if statement.
The inner block of if statement will be executed only if the outer block condition is
true.
public class NestedIfStatementExample
{
public static void main(String arg[])
{
int age = 20; boolean hasVoterCard = true;
// Evaluating the expression that will return true or false if (age > 18)
{
// If outer condition is true then this condition will be check if
(hasVoterCard)
{
System.out.println("You are Eligible");
}
}
}
}

if-else statement: An if-else statement, there are two blocks one is if block and
another is else block. If a certain condition is true, then if block executes otherwise
else block executes.
public class IfElseStatementExample
{
public static void main(String arg[]) { int a = 10; int b = 50;
// Evaluating the expression that will return true or false
if (a > b)
{
System.out.println("a is greater than b");
} else
{
System.out.println("b is greater than a");
}
}
}

if-else if statement/ ladder if statements: If we want to execute the different codes


based on different conditions then we can use if-else-if. It is also known as if-else if
ladder. This statement is always be executed from the top down. During the execution
of conditions if any condition founds true, then the statement associated with that if it

MURALI M, DEPT CS, NCJ BENGALURU Page 10


Page
III Sem B.Sc OOPS USING JAVA
is executed, and the rest of the code will be skipped. If none of the conditions is true,
then the final else statement will be executed.
public class IfElseIfStatementExample
{
public static void main(String arg[]) { int a = 10;
// Evaluating the expression that will return true or false if (a == 1)
{
System.out.println("Value of a: "+a);
}
// Evaluating the expression that will return true or false else if(a == 5)
{
System.out.println("Value of a: "+a);
}
// Evaluating the expression that will return true or false else if(a == 10)
{
System.out.println("Value of a: "+a);
} else
{
System.out.println("else block");
}
}
}

Switch statement: The switch statement is like the if-else-if ladder statement. To
reduce the code complexity of the if-else-if ladder switch statement
comes. In a switch, the statement executes one statement from multiple
statements based on condition. In the switch statements, we have a number of choices
and we can perform a different task for each choice.
{
public static void main(String arg[]) {
int a = 10;
// Evaluating the expression that will return true or false
switch(a)
{ case 1:
System.out.println("Value of a: 1"); break; case 5:
System.out.println("Value of a: 5"); break; case 10:
System.out.println("Value of a: 10"); break; default:
System.out.println("else block"); break;
}
}
}

MURALI M, DEPT CS, NCJ BENGALURU Page 11


Page
III Sem B.Sc OOPS USING JAVA
Loop statements
Statements that execute a block of code repeatedly until a specified condition is met
are known as looping statements.
While Known as the most common loop, the while loop evaluates a certain condition.
If the condition is true, the code is executed. This process is continued until the
specified condition turns out to be false. The condition to be specified in the while
loop must be a Boolean expression.
Syntax:
while (condition)
{
statementOne;
}
public class whileTest
{
public static void main(String args[])
{ int i = 5; while (i <= 15)
{
System.out.println(i); i = i+2;
}
}
}

Do..while
The do-while loop is similar to the while loop, the only difference being that the
condition in the do-while loop is evaluated after the execution of the loop body. This
guarantees that the loop is executed at least once
Syntax
do{
//code to be executed
}while(condition); Example
public class Main
{
public static void main(String args[])
{
int i = 20; do
{
System.out.println(i); i = i+1;
} while (i <= 20);
}

MURALI M, DEPT CS, NCJ BENGALURU Page 12


Page
III Sem B.Sc OOPS USING JAVA
}
For
The for loop in java is used to iterate and evaluate a code multiple times. When the
number of iterations is known by the user, it is recommended to use the for loop.
Syntax
for (initialization; condition; increment/decrement)
{
statement;
}
Example public class forLoop
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}

Method in Java
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code,
Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known as
method header,

MURALI M, DEPT CS, NCJ BENGALURU Page 13


Page
III Sem B.Sc OOPS USING JAVA

Naming a Method
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()

Types of Method
There are two types of methods in Java:
1.Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
2.User-defined Method The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.
public static void findEvenOdd(int num)
{
//method body if(num%2==0)
System.out.println(num+" is even"); else
System.out.println(num+" is odd");
}
Method Overloading in Java
Method Overloading is a feature that allows two or more methods may have the same
name but different in parameters, These methods are called overloaded methods and
this feature is called method overloading.
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded. These methods have the same name but accept
different arguments.

MURALI M, DEPT CS, NCJ BENGALURU Page 14


Page
III Sem B.Sc OOPS USING JAVA
Java array:
Java array is an object which contains elements of a similar data type The elements
of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements.

Instantiating an Array in Java


When an array is declared, only a reference of an array is created. To create or give
memory to the array var-name = new type [size];
Example:

Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array OR
int[] intArray = new int[20]; // combining both statements in one

Instantiation of an Array in Java


String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

Array of objects
Java programming language is all about classes and objects as it is an object-oriented
programming .The array of objects, as defined by its name, stores an array of objects

MURALI M, DEPT CS, NCJ BENGALURU Page 15


Page
III Sem B.Sc OOPS USING JAVA

Object - Any entity that has state and behavior is known as an object.
For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.

SYNTAX OF OBJECT
CLASS_NAME OBJ_NAME=NEW CLASSNAME();

Class
A class is a template or blueprint that is used to create objects.
Class representation of objects and the sets of operations that can be
applied to such objects.
A class consists of Data members and methods.
SYNTAX
public class class_name
{
Data Members;
Methods;
}

Example:
public class Car
{

MURALI M, DEPT CS, NCJ BENGALURU Page 16


Page
III Sem B.Sc OOPS USING JAVA
public: double color; // Color of a car
double model; // Model of a car
}

Constructors in Java:
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
It is a special type of method which is used to initialize the object.

Rules for creating Java constructor


1.Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

static keyword:
Static is a keyword that acts as a non-access modifier in Java that is used mainly to
manage memory.
A Static method cannot access an instance variable.
If a Class contains any static blocks, then that block will be executed only when the
Class is loaded in JVM.
Programmers can apply the Java keyword static with different programming objects
like:
1.variables
2. methods
3. initialization - block
4. nested class

MURALI M, DEPT CS, NCJ BENGALURU Page 17


Page
III Sem B.Sc OOPS USING JAVA
JAVA MATH :
The java.lang.Math class contains many methods that allows you to perform
mathematical tasks on numbers.

MURALI M, DEPT CS, NCJ BENGALURU Page 18


Page
III Sem B.Sc OOPS USING JAVA

public class JavaMathExample1


{
public static void main(String[] args)
{
double x = 28;
double y = 4;

// return the maximum of two numbers


System.out.println("Maximum number of x and y is: " +Math.max(x, y));

// return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28


System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

} }

Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192

this KEYWORD IN JAVA


For referring current class instance variable, this keyword can be used To invoke
current class constructor, this() is used
this can be passed as message argument in a method call
In a constructor call, this can be passed as argument
For returning current class instance, this keyword is used.

MURALI M, DEPT CS, NCJ BENGALURU Page 19


Page
III Sem B.Sc OOPS USING JAVA

Example:
class Emp {
int e_id;
String name;
Emp(int e_id, String name) {
this.e_id = e_id;
this.name = name;
}
void show() {
System.out.println(e_id + " " + name);
}
public static void main(String args[]) {
Emp e1 = new Emp(1006, "Karlos");
Emp e2 = new Emp(1008, "Ray");
e1.show();
e2.show();
}
}

STRING CLASS IN JAVA


What is String in Java?
Generally, String is a sequence of characters.
But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal Java String literal is created by using double quotes.


For Example: String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first.

MURALI M, DEPT CS, NCJ BENGALURU Page 20


Page
III Sem B.Sc OOPS USING JAVA
If the string already exists in the pool, a reference to the pooled instance is returned.

Example:
String s1="Welcome";
String s2="Welcome";

By new keyword
String s=new String("Welcome");//creates two objects and one reference variable In
such case, JVM

will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool.

Example
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Method Description Return Type
charAt() Returns the character at the specified char
index (position)

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, int


ignoring case differences

concat() Appends a string to the end of another String


string

MURALI M, DEPT CS, NCJ BENGALURU Page 21


Page
III Sem B.Sc OOPS USING JAVA
equals() Compares two strings. Returns true if boolean
the strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

indexOf() Returns the position of the first found int


occurrence of specified characters in a
string

Access Modifiers in Java:


There are four types of Java access modifiers:
❖ Public
❖ Protected
❖ Default
❖ Private
Public:
❖ The access level of a public modifier is everywhere.
❖ It can be accessed from within the class, outside the class, within the package
and outside the package.
Example:
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}

Private:
❖ The access level of a private modifier is only within the class.
❖ It cannot be accessed from outside the class.
Example
class A{
private int data=40;
private void msg()
{

MURALI M, DEPT CS, NCJ BENGALURU Page 22


Page
III Sem B.Sc OOPS USING JAVA
System.out.println("Hello java");
}
}

Default:
❖ The access level of a default modifier is only within the package.
❖ It cannot be accessed from outside the package.
❖ If you do not specify any access level, it will be the default.
❖ If you don't use any modifier, it is treated as default by default.
Example
Class A{
public void msg(){
System.out.println("Hello");
}

Protected:
❖ The access level of a protected modifier is within the package and outside the
package through child class.
❖ If you do not make the child class, it cannot be accessed from outside the
package.
Example
class A{
protected void msg()
{
System.out.println("Hello");
}
}

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects.
The StringBuffer class in Java is the same as String class except it is mutable i.e. it
can be changed.
Modifier AND Type Method
public synchronized StringBuffer append(String s)
public synchronized StringBuffer insert(int offset, String s)

MURALI M, DEPT CS, NCJ BENGALURU Page 23


Page
III Sem B.Sc OOPS USING JAVA
FILE IN JAVA
❖ File handling is an important part of any application. Java has several methods for
creating, reading, updating, and deleting files.

❖ Java File Handling The File class from the java.io package, allows us to work with
files.

❖ To use the File class, create an object of the class, and specify the filename or
directory name.

Example
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename If you don't know
what a package is, read our Java Packages Tutorial.

MURALI M, DEPT CS, NCJ BENGALURU Page 24


Page

You might also like