Java Basic Notes March 14 Final

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Java – Basics

A Java program, it can be defined as a collection of objects that communicate via invoking each
other's methods
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well
as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated, and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object’s state is
created by the values assigned to these instance variables.

Values and data types


In Java, a program is a collection of classes and methods, while methods are a collection of various
expressions and statements.

Tokens in Java are the small units of code which a Java compiler uses for constructing those
statements and expressions.

1. Keywords are reserved words which may not be used as constant or variable or any other
identifier names
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while

1
2. Identifiers are names used for classes, variables, and methods
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore
(_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier
Identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Variables
A variable is a place where the program stores data temporarily. The value stored in such a location
can be changed while a program is executing

Constants/literal
String literal "Jim" delimited by ""
char literal 'a' '\t' delimited by ''
Unicode character constant \u00ae
boolean literal true, false (not an int)
int constant 4
float constant 3.14f 2.7e6F /f or F suffix
double constant 3.14d 2.7e6D (default) / d or D suffix
hexadecimal constant 0x123
octal constant 077

Special Symbols/punctuations: The following special symbols are used in Java having some
special meaning and are not used for some other purpose.
Opening and closing brackets are used as array element
Brackets [] reference These indicate single and multidimensional
subscripts.
These special symbols are used to indicate function calls
Parentheses ()
and function parameters.
These opening and ending curly braces marks the start
Braces {} and end of a block of code containing more than one
executable statement.
It is used to separate more than one statements like for
comma ,
separating parameters in function calls.
It is an operator that essentially invokes something
semi colon :
called an initialization list.
It is used to create pointer variable.
asterisk *
It is used to assign values.
assignment operator =

2
Data types
Primitive Type: is pre-defined by the programming language. The size and type of variable values
are specified, and it has no additional methods. eg. boolean, char, byte, short, int, long, float and
double
Non-Primitive Type: are created by the programmer. They are also called “reference variables” or
“object references” since they reference a memory location which stores the data. eg. Classes,
Interfaces, and Arrays

Primitive Type Description


boolean true/false
byte 8 bits
integer ranging from -128 to 127
char 16 bits (UNICODE)
unsigned ranging from 0 to 65,536 (Unicode
short 16 bits
integer ranging from -32,768 to 32,768
int 32 bits integer ranging from -2,147,483,648 to
2,147,483,648
long 64 bits
Integer from -9,223,372,036,854,775,808 to
-9,223,372,036,854,775,808
float Single-precision floating point
32 bits IEEE 754-1985
double Double-precision floating point
64 bits IEEE 754-1985

3
Type casting/conversion
Type casting is when you assign a value of one primitive data type to another type.
Implicit casting / Widening / Promotion - done automatically by assign value of a smaller data
type to a bigger data type. Both datatypes should be compatible with each other
Byte -> short -> int -> long -> float -> double
int i = 100;
long l = i; // automatic type conversion
float f = l; // automatic type conversion

Explicit casting / Narrowing - is converting a higher datatype to a lower datatype using the cast
operator “( )” explicitly. case both datatypes need not be compatible with each other.
double d = 100.04d;
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting

Strings are real objects, not pointers to memory. Java strings may or may not be null terminated.
string literal "a string literal"
concatenate string
String s = "one" + "two"; // s == "onetwo"
String s = "1+1=" + 2; // s == "1+1=2"
String s2 = "1+ " + 2 + 3; // s == "1+23"
length() returns the length of a string e.g., "abc".length() has the value 3.
String.valueOf()
To convert an int to a String, use: String s = String.valueOf(4);
Integer.parseInt()
To convert a String to an int, use: int a = Integer.parseInt("4");

Escape Codes/sequences
Code Description
\n New Line
\t Tab
\’ Single Quotation Mark
\” Double Quotation Mark

System.out.println("First line\nSecond line"); System.out.println("A\tB\tC");


System.out.println("D\tE\tF") ;
First Line
Second Line
A, B, C
D, E, F

4
Operators in Java

1. Arithmetic Operators
Operator Description Example – given a is 15 and b is 6
+ Addition a + b would return 21
- Subtraction a - b would return 9
* Multiplication a * b would return 90
/ Division a / b would return 2
% Modulus a % b would return 3 (the remainder)

2. Logical Operators
These operators are used to evaluate an expression
Operator Description
& AND gate behavior (0 0 0 1)
| OR gate behavior (0 1 1 1)
^ XOR – exclusive OR (0 1 1 0)
&& Short-circuit AND
|| Short-circuit OR
! Not

3. Relational operator
Operator Description
< Smaller than
> Greater than
<= Smaller or equal to (a<=3) : if a is 2 or 3 then
result of comparison is TRUE
>= Greater or equal to (a>=3) : if a is 3 or 4 then
result of comparison is TRUE
== Equal to
!= Not equal

4. Increment/decrement operator
Operator Description Example Description
++ Increment a++ a = a + 1 (adds one
from a)
-- Decrement a-- a = a – 1 (subtract
one from a)
+= Add and assign a+=2 a = a + 2
-= Subtract and assign a-=2 a = a – 2
*= Multiply and assign a*=3 a = a * 3
/= Divide and assign a/=4 a = a / 4
%= Modulus and assign a%=5 a = a mod 5
Input in Java
Java Scanner class allows the user to take input from the console. It belongs to java.util package.
It is used to read the input of primitive types like int, double, long, short, float, and byte.
syntax

5
Scanner sc=new Scanner(System.in); 
int num = sc.nextInt(),;
float fnum = sc.nextFloat();
String st = sc.nextLine();
char ch = sc.next().charAt(0);

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
nextLine() read String value from the user
next().charAt(0) next() function reads a string and charAt(0) function returns the first character

Comments
single-line
// This is an example of single line comment
/* This is also an example of single line comment. */

multi-line comments
/* This is an example of multi-line comments.
* line 2
* line 3.
*/

6
DECISION MAKING STATEMENTS:
These statements decide the flow of the execution based on some conditions.

1. if : the simplest decision making statement which is used to decide whether a certain statement
or block of statements will be executed or not
Syntax:
if(condition)
{
// Statements to execute if condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if
the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will
consider the immediate one statement to be inside its block. For example,
// Java code to illustrate If statement
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed as if considers one statement by default
System.out.println("I am Not in if");
OUTPUT
I am Not in if
2. if else : If the if condition is true it will execute the immediate block of statements and if the
condition is false it will execute the else statement. We can use the else statement with if statement
to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
// Java code to illustrate IF..ELSE statement
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
OUTPUT
i is smaller than 15

7
3. if ..else..if ladder : a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statemen 3;

// Java code to illustrate IF ... ELSE...IF statement


int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
OUTPUT
i is 20

4. switch . .case : is a multiway branch statement. It provides an easy way to dispatch


execution to different parts of code based on the value of the expression.
Expression can be of type byte, short, int char
Duplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence. It is optional and if
omitted, execution will continue on into the next case.

Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
---
8
---
case valueN:
statementN;
break;
default:
statementDefault;
}
// Java code to illustrate SWITCH .. CASE statement

int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}

OUTPUT
i is greater than 2
JUMP STEMENTS:
statements that are used to jump from the current executing loopand transfer control to other part of
the program
1. break : is used :
To terminate a sequence in a switch statement
To exit a loop.
as another form of goto.

// Java code to illustrate BREAK statement


// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
9
System.out.println("Loop complete.");

OUTPUT
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.

2. Continue : is useful to force an early iteration of a loop and to continue running the loop with
out processing the remaining code in its body for this particular iteration.
for (int i = 0; i < 10; i++)
{
// If the number is even skip and continue
if (i%2 == 0)
continue; // If number is odd, print it
System.out.print(i + " ");
}

OUTPUT
13579

3. Return : statement is used to transfer the control back to calling method. Compiler will always
bypass any sentences after return statement. They can also return a value to the calling method.

10
Looping Statement in Java
Looping statement are the statements execute one or more statement repeatedly several number of
times. In java programming language there are three types of loops; while, for and do-while.

For loop While loop Do while loop


Syntax: Syntax: Syntax:
For(initialization; condition; While(condition), Do
updating) { Statements; } { Statements;
{ Statements; }, } While(condition);
It is known as entry-controlled It is known as entry-controlled It is known as exit-controlled
loop, loop, loop.
If the condition is not true first If the condition is not true Even if the condition is not
time then control will never first time then control will true for the first time the
enter in a loop, never enter in a loop , control will enter in a loop.
Initialization and updating is the Initialization and updating is Initialization and updating is
part of the syntax, not the part of the syntax , not the part of the syntax
It is used when the number of It Is used if the number of  It is executed at least once
repetitions is fixed repetitions is not fixed because condition is checked
after loop body

for Loop
Flow of Execution
First step: initialization - initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the
statements inside for loop body gets executed. Once the condition returns false, the statements in for
loop does not execute and the control gets transferred to the next statement in the program after for
loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop
executes that updates the loop counter.
Fourth step: the control jumps to second step and condition is re-evaluated.

for (initialization; test Expression; update)


{
// codes inside for loop's body
}
for (int i = 1; i <= 10; i++) {
if (i<10)
System.out.print(i+", ");
else
System.out.print(i);
}
OUTPUT
1, 2, 3, 4 ,5, 6, 7, 8, 9, 10
Infinite loop
 Infinite loop is the condition that will never return false.
11
for(int i=1; i>=1; i++){
System.out.println(i);
}
The initialization step is setting up the value of variable i to 1, since we are incrementing the value
of i, it would always be greater than 1 (the Boolean expression: i>1) so it would never return false.

// infinite loop
for ( ; ; ) {
// statement(s)
}

Exercise 1
Java Program to find sum of natural numbers using FOR loop
public class Demo {
public static void main(String[] args) {
int count, total = 0;
for(count = 1; count <= 10; count++){
total = total + count;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
 
Exercise 2
Java Program to find factorial of a number using FOR loop

public class JavaExample {


public static void main(String[] args) {
//We will find the factorial of this number
int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 5 is: 120

12
Exercise 3
Java Program to print Fibonacci Series using FOR loop
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series of "+count+" numbers:");
for (int i = 1; i <= count; ++i)
{
System.out.print(num1+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}

While loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
the code in the loop will run, over and over again, as long as a variable 'i' is less than 5

Exercise 1
Java Program to find sum of natural numbers using WHILE loop
public class Demo {
public static void main(String[] args) {
int count =1, total = 0;
while( count <= 10){
total = total + count;
count++;
}
13
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55

Execise 2
Java Program to find the factorial of number using WHILE loop
public class JavaExample {
public static void main(String[] args)
{
//We will find the factorial of this number
int number = 5;
int i=1;
long fact = 1;
while(i <= number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 5 is: 120

Exercise 3
Java Program to print Fibonacci Series using WHILE loop
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1, i=1;
System.out.print("Fibonacci Series of "+count+" numbers:");
while(i <= count)
{
System.out.print(num1+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
14
}
}
}

do...while loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);

int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Exercise 1
Java Program to find sum of natural numbers using DO..WHILE loop
public class Demo {
public static void main(String[] args) {
int count =1, total = 0;
do
{
total = total + count;
count++;
} while( count <= 10) ;
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
Exercise 2
Java Program to find the factorial of number using DO..WHILE loop
public class JavaExample {
public static void main(String[] args)
{
//We will find the factorial of this number
int number = 5;
int i=1;
long fact = 1;
15
do
{
fact = fact * i;
i++;
} while(i <= number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 5 is: 120

Exercise 3
Java Program to print Fibonacci Series using DO..WHILE loop
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1, i=1;
System.out.print("Fibonacci Series of "+count+" numbers:");
do
{
System.out.print(num1+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
} while(i <= count);
}
}

16
String functions
Sr. Method & Description
1 char charAt(int index) Returns the character at the "javatpoint".charAt(4) returns 't'
specified index.
2 int compareTo(String Compares two strings "BBB". compareTo("BBB") returns
anotherString) lexicographically. 0
3 int Compares two strings "BBb".
compareToIgnoreCase( lexicographically ignoring compareToIgnoreCase("BBB) // 0
String str) case differences.
4 String concat(String str) Concatenates the specified "AAA".concat("aaa") //
string to the end of this string. "AAAaaa"
5 boolean Tests if this string ends with "AAAex".endsWith("ex") // true
endsWith(String suffix) the specified suffix.
6 boolean equals(String Compares this string to the "DDD".equals("DDD")); // true
anotherString) specified string.
7 boolean Compares this String to "DDD".equalsIgnoreCase ("DdD"));
equalsIgnoreCase(Strin another String ignoring case // true
g anotherString) considerations.
8 int indexOf(char ch) Returns the index within this "javatpoint".indexOf('t'); // 4
string of the first occurrence
of the specified character.
9 int lastIndexOf(int ch) Returns the index within this "javatpoint".lastIndexOf('t'); // 9
string of the last occurrence
of the specified character.
10 int length() Returns the length of this "javatpoint".length() // 10
string.
11 String replace(char Returns a new string resulting "javatpoint".replace('t','T') //
oldChar char newChar) from replacing all javaTpoinT
occurrences of oldChar in this
string with newChar.
12 boolean Tests if this string starts with "javatpoint".startsWith("java") //
startsWith(String the specified prefix. true
prefix)
13 boolean endsWith Tests if this string ends with "javatpoint".startsWith("point") //
(String prefix) the specified prefix. true
14 String substring(int Returns a new string that is a "javatpoint".substring(4) // tpoint
beginIndex) substring of this string.
14 String substring(int Returns a new string that is a "javatpoint".substring(7,9) // in
beginIndex, int substring of this string.
endIndex)
15 String toLowerCase() Converts all of the characters "JavatPoint".toLowerCase() //
in this String to lower case javatpoint
using the rules of the default
locale.
16 String toUpperCase() Converts all of the characters "JavatPoint".toUpperCase() //
in this String to upper case JAVATPOINT
17
using the rules of the default
locale.
17 String trin() Returns a copy of the string " JavatPoint ".toUpperCase() //
with leading and trailing “JavatPoint”
white space omitted
18 String valueOf Returns the string String.valueOf(100); // 100 as string
primitive data type x) representation of the passed String.valueOf(10.05f); // 10.5 as
data type argument. string

18
Arrays are objects and can be defined as a collection of variables of the same type defined by a
common name. Array store multiple variables of the same type that know the number and type of
their elements. The first element index is 0.

The syntax for creating an array object is:


dataType[] arrayName;
dataType can be a primitive data type like: int, char, Double, byte etc. or an object
arrayName is an identifier.

double[] data;
data is an array that can hold values of type Double.
data = new Double[10];
This declaration defines the array object and to allocate memory for an array, uses the operator:
new and specify the size within the square brackets (Instantiating an Array). The elements in the array
allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for
reference types)
data = new Double[10];
The length of data array is 10. ie. it can hold 10 elements (10 Double values in this case).Once the length of
the array is defined, it cannot be changed in the program.

int[] age = new int[5];


declares and allocates memory of an array in one statement.

Disadvantages of Array in java


Arrays are Strongly Typed.
Arrays does not have add or remove methods.
We need to mention the size of the array. Fixed length. So there is a chance of memory wastage.
To delete an element in an array we need to traverse throughout the array so this will reduce
performance.
Advantages of arrays:
Easier access to any element by using indexes provided by arrays.
Primitive type to wrapper classes object conversion will not happen so it is fast.
Easy to manipulate and store large data

19
Initialize an Array During Declaration
int[] i = {1, 2, 3, 4};
String week[]={"Sun","Mon","Tue"};
char vowel[]={'a','e','i','o','u'};

int[] age = {5, 2, 1, 3, 4};


creates an array 'age' of integer data type and initializes the values during declaration as
age[0] = 5
age[1] = 2
age[2] = 1
age[3] = 3
age[4] = 4
The length of age array is 5.
Length of an array
age.length - returns the length of 'age' array.
age.length returns 5
How to access array elements? Print array in Java
access and alter array elements by using its numeric index
for (int i = 0; i < 5; ++i)
System.out.println("Element at index " + i +": " + age[i]);
OUTPUT
Element at index 0: 5
Element at index 1: 2
Element at index 2: 1
Element at index 3: 3
Element at index 4: 4

Computes sum and average of values stored in an array 'age' of type int
int[] age = {5, 2, 1, 3, 4};
int sum = 0;
int average;
int arrayLength = age.length;
for (int i = 0; i < arrayLength; i++)
sum += age;
average = sum /arrayLength;
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
OUTPUT
Sum = 15
Average = 3

Finds the maximum and minimum of the elements of age array


int[] age = {5, 2, 1, 3, 4};
int min, max=age[0];

20
for(int i=1 ; i<age.length ; i++)
{
if(min<age[i])
min=age[i];
if(max>age[i])
max=age[i];
}
System.out.println("Min : "+min);
System.out.println(Max : "+max);

OUTPUT
Min : 1
Max : 5

Sort the array in ascending order BUBBLE SORT


5,4,2,3,1

5 4 4 4 4 4
4 5 2 2 2 2
2 2 5 3 3 3
3 3 3 5 5 1
1 1 1 1 1 5

4 2 2 2
2 4 3 3
3 3 4 1
1 1 1 4
5 5 5 5

2 2 2
3 3 1
1 1 3
4 4 4
5 5 5

2 1
1 2
3 3
4 4
5 5

21
int[] age = {5,4,2,3,1 };
int n = age.length;
for (int i = 0; i < n; i++)
for (int j = 0; j < n-i-1; j++)
if (age[j] > age[j+1])
{
// swap temp and age[i]
int temp = age[j];
age[j] = age[j+1];
age[j+1] = temp;
}

Sort the array in ascending order SELECTION SORT


5,4,2,3,1
5 1 1 1
4 4 2 2
2 2 4 3
3 3 3 4
1 5 5 5

int age[]={5,4,2,3,1}
int n = age.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int minIndex= i;
for (int j = i+1; j < n; j++)
if (age[j] < age[minIndex])
minIndex= j;
// Swap the found minimum element with the first element
int temp = age[minIndex];
age[minIndex] = age[i];
age[i] = temp;
}

Important differences between Binary Search and Linear Search


Input data needs to be sorted in Binary Search and not in Linear Search
Linear search does the sequential access whereas Binary search access data randomly.
Time complexity of linear search -O(n) , Binary search has time complexity O(log n).
Linear search performs equality comparisons and Binary search performs ordering comparisons

Searching using LINEAR SEARCH

22
Find 1
0 1 2 3 4
1 2 3 4 5

int[] age = {5,4,2,3,1 };


int x=1;
int pos=-1;
int n = age.length;
for(int i = 0; i < n; i++)
{
if(age[i] == x)
pos=i;
}
if (pos=-1)
System.out.println(x + "not found");
else
System.out.println(x + " found at "+ (pos+1)));

Searching using BINARY SEARCH

1 2 3 4 5
x=1
first 0 last 4 mid = 0+4/2 = 2
is x == a[2] (1==3) no
is x < a[2] (1<3) yes first=0 last = mid-1 =2-1 =1 mid = first+last/2 0+1/2 =0
is (x==a[0]) 1==1 yes
1 found at position 1

int[] age = {1, 2, 3, 4, 5};


int x=1;
int n = age.length;
int first=0, last = n-1, mid;
while( first<=last)
{

23
mid= (first+last)/2
if (x==age[mid])
{
System.out.println(x + " found at "+ mid+1));
break;
}
else if(x<age[mid})
last=mid-1;
else
first=mid+1;
}
if first<=last)
System.out.println(x + "not found");

Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of student class in which the address
of seven Student objects can be stored. The Student objects have to be instantiated using the
constructor of the Student class and their references should be assigned to the array elements in the
following way.
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;

24
this.name = name;
}
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1,"aman");
// initialize the second elements of the array
arr[1] = new Student(2,"vaibhav");
// so on...
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");
arr[4] = new Student(5,"mohit");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " + arr[i].roll_no +" "+ arr[i].name);
}
}
OUTPUT
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

25
ERRORS IN JAVA
1. Compile-time errors (Syntax errors)
Errors which prevents the code from compiling because of error in the syntax (violating the rules of
Java langauge). These errors will be detected by java compiler and displays the error onto the
screen while compiling.
Examples
missing a semicolon at the end of a statement
missing braces
misspelled variables
to capitalize keywords, rather than use lowercase.
split a string across lines
import the associated class into your application like import java.lang.String; to work with String
class.
class not found, etc.
2. Run time errors
These errors are errors which occur when the program is running. Run time errors are not detected
by the java compiler. It is the JVM which detects it while the program is running.
Below are example :
1. Divide an integer by zero
2. Access an element that is out of bounds of an array
3. Store a value that is of incompatiable data type in an array
4.Case an instances of base class to one of its derived class
5. Using negative size in an array
6.Conversion of string into a number
7.Using a null object to references an objects member

3. logical errors.
Errors are due to the mistakes made by the programmer. It will not be detected by a compiler nor by
the JVM. Errors may be due to wrong idea or concept used by a programmer. Logical error which
will give wrong results
Example:
Print division of two numbers as output but expected is multiplication of numbers.
A program has instructions to print numbers 1 to 5 but prints 6.

26
Mathematical library functions
Method Description
Math.sqrt() It is used to return the square root of a number.

Math.sqrt(144); //12.0

Math.cbrt() It is used to return the cube root of a number.

Math.cbrt(512); //8.0

Math.pow() It returns the value of first argument raised to the power to second argument.

Math.pow(3,3); // 27.0

Math.abs() returns the absolute value of the parameter passed to it

int i = Math.abs(-10); // 10

long l = Math.abs(-1234567l); // 1234567

float f = Math.abs(-10.5f); // 10.5

double d = Math.abs(-3.141426d);// 3.141426

Math.ceil() rounds a floating point value up to the nearest integer value.

double ceil = Math.ceil(7.343); // ceil = 8.0

Math.floor() rounds a floating point value down to the nearest integer value.

double floor = Math.floor(7.343); // floor = 7.0

Math.min() returns the smallest of two values passed to it as parameter.

Math.min(10, 20); = 10

Math.max() returns the largest of two values passed to it as parameter

Math.max(10, 20); = 20

Math.round() rounds a float or double to the nearest integer using normal math round rules

Math.round(23.445); = 23.0

Math.round(23.545); = 24.0

27
1
12
123
1234
12345

public void printNums(int n)


{
int i, j,num, rows=5;
for(i=0; i<rows; i++) // outer loop for rows
{
num=1;
for(j=0; j<=i; j++) // inner loop for rows
{
System.out.print(num+ " "); // printing num with a space
num++; //incrementing value of num
}
System.out.println(); // ending line after each row
}
}

28
1
23
456
7 8 9 10
11 12 13 14 15

public void printNum()


{
int i, j, num = 1;
for (i = 1; i <= 5; i++) // outer loop for row
{
for (j = 1; j< i + 1; j++) // inner loop for rows
{
System.out.print(num + " "); // printing num with a space
num++; //incrementing value of num
}
System.out.println(); // ending line after each row
}
}

29
5
54
543
5432
54321

public void printNum()


{
int row=5;
for (int i = rows; i >= 1; i--) // outer loop for row
{
for (int j = rows; j >= i; j--) // inner loop for rows
{
System.out.print(j+" "); // printing num with a space
}
System.out.println(); // ending line after each row
}
}

30
1
22
333
4444
55555

public void printNum()


{
int rows=5;
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(i+" ");
}
System.out.println();
}
}

31
1
21
321
4321
54321

 
public void printNum()
{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = i; j >= 1; j--)
{
System.out.print(j+" ");
}
System.out.println();
}
}

32
10101
01010
10101
01010
10101

public void prinNum()


{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
int num;
if(i%2 == 0)
{
num = 0;
for (int j = 1; j <= rows; j++)
{
System.out.print(num);
num = (num == 0)? 1 : 0;
}
}
else
{
num = 1;
for (int j = 1; j <= rows; j++)
{
System.out.print(num);

num = (num == 0)? 1 : 0;


}
}
System.out.println();
}
}

33
1
10
101
1010
10101

public void prinNum()


{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
if(j%2 == 0)
{
System.out.print(0);
}
else
{
System.out.print(1);
}
}

System.out.println();
}
}

34
A
AB
ABC
ABCD
ABCDE
ABCDEF

public void prinNum()

int alphabet = 65;

for (int i = 0; i <= 5; i++)

for (int j = 0; j <= i; j++)

System.out.print((char) (alphabet + j) + " ");

System.out.println();

35
A
BB
CCC
DDDD
EEEEE
FFFFFF

public void printAlpha()

int alphabet = 65;

for (int i = 0; i<= 5; i++)

for (int j = 0; j <= i; j++)

System.out.print((char) alphabet + " ");

alphabet++;

System.out.println();

36
*
**
***
****
*****

public static void rightTriangle(int n)

int i, j;

for(i=0; i<n; i++) //outer loop for number of rows(n)

for(j=0; j<=i; j++) // inner loop for columns

System.out.print("* "); // print star

System.out.println(); // ending line after each row

37
*
**
***
****
*****

public static void rightTriangle()

int i, j, n=5;

for(i=0; i<n; i++) //outer loop for number of rows(n)

for(j=2*(n-i); j>=0; j--) // inner loop for spaces

System.out.print(" "); // printing space

for(j=0; j<=i; j++) // inner loop for columns

System.out.print("* "); // print star

System.out.println(); // ending line after each row

38
*****
****
***
**
*

public void prinStar()

int rows = 5;

for (int i= rows-1; i>=0 ; i--)

for (int j=0; j<=i; j++)

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

System.out.println();

39
*****
****
***
**
*

public void prinStar()

int rows = 5;

for (int i= 0; i<= rows-1 ; i++)

for (int j=0; j<=i; j++)

System.out.print(" ");

for (int k=0; k<=rows-1-i; k++)

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

System.out.println();

40
*
**
***
****
*****
****
***
**
*
 
public void prinStar()
{
int rows = 5;
for (int i= 0; i<= rows-1 ; i++)
{
for (int j=0; j<=i; j++)
{
System.out.print("*"+ " ");
}
System.out.println("");
}
for (int i=rows-1; i>=0; i--)
{
for(int j=0; j <= i-1;j++)
{
System.out.print("*"+ " ");
}
System.out.println("");
}
}

41
*
**
***
****
*****
****
***
**
*

public void prinStar()


{
int rows = 5;
for (int i= 1; i<= rows ; i++)
{
for (int j=i; j <rows ;j++)
{
System.out.print(" ");
}
for (int k=1; k<=i;k++)
{
System.out.print("*");
} System.out.println("");
}
for (int i=rows; i>=1; i--)
{
for(int j=i; j<=rows;j++)
{
System.out.print(" ");
}
for(int k=1; k<i ;k++)
{
System.out.print("*");
}
System.out.println("");
}
}

42

You might also like