Unit-3 Notes
Unit-3 Notes
Unit-3 Notes
Java variables
Data Types
Class
Java if else statement
Loop of Java
What is Java?
Java is a very popular high level programming language and has been used widely to create
various types of
computer applications such as database applications, desktop applications, Web based
applications, mobile applications, and games among others. A Java compiler instead of
translating Java code to machine language code, translates it into Java Bytecode (a highly
optimized set of instructions). When the bytecode (also called a Java class file) is to be run on a
computer, a Java interpreter, called the Java Virtual Machine (JVM), translates the bytecode into
machine code and then executes it.
The advantage of such an approach is that once a programmer has compiled a Java program into
bytecode, it can be run on any platform (say Windows, Linux, or Mac) as long as it has a JVM
running on it. This makes Java programs platform independent and highly portable.
Data Types and Variables:
Variables:
To store the program data we will use variables. A variable is a placeholder for data that can
change its value during program execution.
In our percentage calculator program, we will use three variables named
marks_obtained,total_marks and percentage. The variables marks_obtained and percentage are
declared of type double, since they can have fractional values (floating point numbers). Inside
the main method, we declare these variables, we also assign them values using the = operator as
shown below:
int total_marks = 400;
double marks_obtained = 346; double percentage = 0.0;
To calculate the percentage
percentage = (marks_obtained/total_marks)*100;
To display the percentage in the IDE output window
System.out.println(“Student1’s Percentage = “+percentage);
Primitive Data Types
In all, Java supports eight primitive data types, they are byte, int, long, short, float, double,
Boolean, char.
Variable names can begin with either an alphabetic character, an underscore (_), or a dollar sign
($). However, convention is to begin a variable name with a letter. They can consist of only
alphabets, digits, and underscore.
Variable names must be one word. Spaces are not allowed in variable names. Underscores are
allowed.
There are some reserved words in Java that cannot be used as variable names, for example – int.
Java is a case-sensitive language.
It is good practice to make variable names meaningful. The name should indicate the use of that
variable.
You can define multiple variables of the same type in one statement by separating each with a
comma.
String Variables: we want variables to store textual data, for example, the name of a student.
To store more than one character, we use the String class in Java. Eg. String first_name =
“Mayank”;
Control Flow: Is a sequence of instructions. Java executes the instructions in sequential order,
that is, one after the other.
Selection Structures:
In real life, you often select your actions based on whether a condition is true or false. For
example, if it is raining outside, you carry an umbrella, otherwise not.
The if Else Statement : The if statement in Java lets us execute a block of code depending upon
whether an expression evaluates to true or false.
The Switch Statement:
The switch statement is used to execute a block of code matching one value out of many possible
values. The structure of the Java switch statement is as follows:
switch (expression)
{
case constant_1 : statements; break;
case constant_2 : statements; break;
…
…
default : statements; break;
}
Repetition Structures:-
The ability of a computer to perform the same set of actions again and again is called looping.
The sequence of statements that is repeated again and again is called the body of the loop.
The test conditions that determine whether a loop is entered or exited is constructed using
relational and logical operators. A single pass through the loop is called an iteration.
For example, a loop that repeats the execution of the body three times goes through three
iterations. Java provides three statements – the while statement, the do while statement, and the
for statement for looping.
The for Statement
The for loop is the most widely used Java loop construct. The structure of the Java for statement
is as below: for (counter=initial_value; test_condition;change counter)
{
statements
}
Example: WAP to display the values from 1 to 5 using FOR loop
int i;
For (i=1; i <=5; i++)
{
System.out.println(“” + i);
}
While Statement
The while statement evaluates the test before executing the body of a loop. A while loop is an
entry controlled loop. The structure of the Java while statement is as shown:
The While Statement
while (expression)
{
statements
}
Example: WAP to print first 5 natural numbers using WHILE loop
int i = 0; while (i<=5)
{
System.out.println(“” + i); i++;
}
Do While Statement
The do while statement evaluates the test after executing the body of a loop. A do-while loop is
an exit control loop.
The structure of the Java do while statement is as shown: do
{
statements
} while (expression);
Example: WAP to print first 5 natural numbers using do while loop
int i = 0;
do
{
System.out.println(“” + i); i++;
}
while (i <=5);
ARRAY
An array is a collection of similar types of data. Arrays are used to store multiple values in a
single variable, instead of declaring separate variables for each value. To declare an array, define
the variable type
with square brackets [ ]:
Types of Array in java There are two types of array. Single Dimensional Array Multidimensional
Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java
array is always fixed.
How to declare an array in Java?
In Java, here is how we can declare an array. dataType[] arrayName;
dataType – it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName – it is an identifier
For example:
double[] data;
Here, data is an array that can hold values of type double.
Access the Elements of an Array:
Example:
public static void main(String[] args) {
String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”}; System.out.println(cars[0]);
}
}
Output: Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, we have to refer to the index number: cars[0] =
“Opel”;
Example:
public static void main(String[] args) {
String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”}; cars[0] = “Opel”;
System.out.println(cars[0]);
}
Output: Opel Array Length
To find out how many elements an array has, use the length property:
Example:
public static void main(String[] args) {
String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”}; System.out.println(cars.length);
}
Output: 4
Loop Through an Array
Using loop through the array elements with the for loop, and use the length property to specify
how many times the loop should run.
Example:
public static void main(String[] args) {
String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”}; for (int i = 0; i < cars.length; i++)
{ System.out.println(cars[i]);
}
Example:
public static void main(String args[]) { int a[]=new int[5]; a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]);
Multidimensional Array in Java
A multidimensional array is an array containing one or more arrays.
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType []arrayRefVar[];
To create a two-dimensional array, add each array within its own set of curly braces: int[][]
myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and one
for the element inside that array.
Example:
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}
Output: 7
Example:
//Java Program to illustrate the use of multidimensional array
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//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();
}
Example:
To store the marks of a student 5 students:
// TODO add your handling code here: double[]marks = {346, 144, 103, 256.5, 387.5};
double total_marks = 400; System.out.println(“\tClass Report”);
System.out.println(” “); System.out.println(“RollNo\tMarks\tPercentage\tResult”);
System.out.println(” “);
for (int i = 0; i
Example:
WAP to sort an array of Strings in alphabetic order:
public static void main(String args[]) {
String[] names = {“Shruti”, “Kunal”,
“Gungun”,”Avani”,”Ravi”,”Tripti”,”Purva”,”Aditya”,”Chandan”}; System.out.println(“Names
Array before Sorting:”);
for (int i = 0; i<names.length; i++) System.out.print(names[i] + “,”);
System.out.println(); Arrays.sort(names);
System.out.println(“Names after Sorting:”); for (int i=0; i < names.length; i++)
System.out.print(names[i] + “,”); System.out.println();
Common Coding Errors: Arrays
For example, if the array size is 5, then loop index = 5 is an off by one error since array index
can go only from 0 to 4.
double [] ] marks = new double [5]; for (int i = 0; i <= 5; i++) { System.out.print(marks[i]);
}
In this case an Array index out of bounds error occurs and the program terminates unexpectedly
with an error as below.
Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException: 5
at javaprograms.ArrayDemo.main(ArrayDemo.java:11) Java Result: 1
User Defined Methods
A method in Java is a block of statements grouped together to perform a specific task. A method
has a name, a return type, an optional list of parameters, and a body.
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions. The structure
of a Java method is as below:
return_type method_name(list of parameters separated by commas)
{
statements return statement
}
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println()
To call a method in Java, write the method’s name followed by two parentheses () and a
semicolon; In the following example, myMethod() is used to print a text (the action), when it is
called: Example:
static void myMethod() {
System.out.println(“I got FULL MARKS IN IT!”);
}
public static void main(String[] args) { myMethod();
}
A method can also be called multiple times: public class Main {
static void myMethod() {
System.out.println(“I got FULL MARKS IN IT!”);
}
public static void main(String[] args) { myMethod();
myMethod(); myMethod();
}
Call a Method
Given the length and breadth of a rectangle as parameters returns the area of the rectangle. static
double rectangle_area (double length, double breadth)
{
return (length * breadth);
When the length and breadth of the rectangle as arguments in the method call. The arguments
with which the rectangle_area method is called are copied into its parameters. In this case, 45.5
is copied into the parameter length and 78.5 is copied into the parameter breadth.
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the
method. Parameters are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full
name:
public class Main {
static void myMethod(String fname) { System.out.println(fname + ” Abraham”);
}
public static void main(String[] args) { myMethod(“Thomas”); myMethod(“Jenny”);
myMethod(“Raju”);
}
Multiple Parameters
public class Main {
static void myMethod(String fname, int age) { System.out.println(fname + ” is ” + age);
}
public static void main(String[] args) {
myMethod(“Thomas”, 10);
myMethod(“Jenny”, 18);
myMethod(“Raju”, 38);
}
Note: When you are working with multiple parameters, the method call must have the same
number of arguments as there are parameters, and the arguments must be passed in the same
order.
Return Values:
If you want the method to return a value, you can use a primitive data type (such as int, char,
etc.) instead of void, and use the return keyword inside the method:
public class Main {
static int myMethod(int x) { return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
A Method with If…Else
public class Main {
// Create a checkAge() method with an integer parameter called age static void checkAge(int
age) {
// If age is less than 18, print “access denied” if (age < 18) {
System.out.println(“Access denied – You are not old enough!”);
// If age is greater than, or equal to, 18, print “access granted”
} else {
System.out.println(“Access granted – You are old enough!”);
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
Object Oriented Programming
Java – What is OOP?
Introduction to Java
Java is one of most popular high level ‘Object Oriented’ programming language and has been
used widely to create various computer applications.
Applications of java
Database applications
Desktop applications
Mobile applications
Web based applications
Games etc.
What is JVM?
JVM stands for Java Virtual Machine which is basically a java interpreter which
translates the byte code into machine code and then executes it.
The advantage of JVM is that once a java program is compiled into byte code. It can be
run on any platform.
Byte code is an highly optimized intermediate code produced when a java program is
compiled by java compiler.
Byte code is also called java class file which is run by java interpreter called JVM.
What is NetBeans?
Java NetBeans IDE is open source IDE used for writing java code, compiling and executing java
programs conveniently.
You can write comments in a Java program in the following two ways:
Variables
Variable is a placeholder for data that can change its value during program execution.
Technically, a variable is the name for a storage location in the computer’s internal
memory and the value of the variable is the contents at that location.
Data types
Declaring variable
int x;
float degree;
int a,b,c;
char ac_no;
To take user input we use the prebuilt Scanner class. This class is available in the java.util
package.
Note: to read numeric data input, we use static method parseInt() of Integer class that takes
String as parameter and returns its equivalent as given below:
String s = user_input,next();
int num = Integer.parseInt(s);
Operators are special symbols in programming language and perform certain specific operations.
Control flow
A program is considered as finite set of instructions that are executed in a sequence. But
sometimes the program may require executing some instructions conditionally or repeatedly. In
such situations java provides:
Selection structures
Repetition structures
Selection structure
If else statement
Switch statement
if else statement
The if statement in Java lets us execute a block of code depending upon whether an expression
evaluates to true or false. The structure of the Java if statement is as below:
Sometimes, you may want to execute a block of code based on the evaluation of two or more
conditional expressions. For this, you can combine expressions using the logical && or ||
operators.
The switch statement is used to execute a block of code matching one value out of many
possible values.
It is basically used to implement choices from which user can select anyone.
Java program to create calculator using switch case
Repetition Structure
Repetition in program refers to performing operations (Set of steps) repeatedly for a
given number of times (till the given condition is true).
Repetition is also known as Iteration or Loop. Repetitions in program can be as follows:
while
do..while
for
while statement
Syntax:
Syntax:
for statement
Syntax:
Example:
Arrays are variables that can hold more than one value of the same type, name and size.
It occupies contiguous memory space when declared and each space is called Array
Elements which can store individual value.
Each Array Element is uniquely identified by a number called Array Index which begins
from 0.
The [] brackets after the data type tells the Java compiler that variable is an array that can
hold more than one value.
Syntax:
Example:
Designing a class
Syntax:
Creating Class Object
Example
Constructor
Constructor is a special method which is used to initialize the data members of the class.
The constructor has the same name as that of class.
The constructor has no return type and may or may not have parameter list.
It is invoked automatically whenever new object of class is created.
Example:
Access Modifier
Access Modifiers in java are keywords that specify the accessibility scope of data
members of class.
Java offers following Access Modifiers:
o private
o public