Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Java Notes Unit I

Uploaded by

aiden.atz78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Java Notes Unit I

Uploaded by

aiden.atz78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Features of Java:-

Simple: A very simple, easy to learn and understand language for programmers
who are already familiar with OOP concepts. Java’s programming style and
structure follows the lineage of C, C++ and other similar languages makes the use
of java efficiently.
Object-oriented: Java is object oriented. Java inherits features of C++. OOP
features of java are influenced by C++. OOP concept forms the heart of java
language that helps java program in survive the inevitable changes accompanying
software development.
Robust: The multi platformed environment of the Web places extraordinary
demands on a program, because the program must execute reliably in a variety of
systems. Thus, the ability to create robust programs was given a high priority in the
design of Java.
Secure, Portable: Java programs are safe and secure to download from internet. At
the core of the problem is the fact that malicious code can cause its damage due to
unauthorized access gained to system resources. Java achieved this protection by
confining a program to the Java execution environment and not allowing it access
to other parts of the computer. The same code must work on all computers.
Therefore, some means of generating portable executable code was needed.
Multithreaded: Java supports multithreaded programming, which allows a
programmer to write programs that performs multiple tasks simultaneously. The
Java run-time system comes with an elegant and sophisticated solution for multi-
process synchronization that helps to construct smoothly running interactive
systems.
Interpreted & High performance: Java enables the creation of cross-platform
programs by compiling into an intermediate representation called Java bytecode.
This code can be executed on any system that implements the Java Virtual
Machine. The Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a
just-in-time compiler.
Dynamic: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This
makes it possible to dynamically link code in a safe and expedient manner.
Java Programming Environment: -

• Java Environment includes large number of development tools.


• The development tools are part of the system known as Java Development Kit
(JDK).
1. Java Development Kit ( JDK ):- The Java Development Kit ( JDK ) comes
with a collection of tools that are used for developing and running Java
programs.
2. Java Runtime Environment ( JRE ):- The Java Runtime Environment (JRE)
facilitates the execution of programs developed in java. It comprises the
following:
3. Java Virtual Machine ( JVM ) : Java Virtual Machine (JVM) is an engine
that provides a runtime environment to drive the Java Code or applications. It
converts Java bytecode into machine language. This machine is called Java
Virtual Machine and it exists only inside the computer memory.
Class:- A class is a group of objects which have common properties. It is a user-
defined data type with a template that serves to define its properties. To create a class,
use the keyword class.
Defining Class:-

Syntax:
class classname {
field declaration or data members;
method declaration or member functions;
}

A class can contain any of the following variable types.


• Local variables − Variables defined inside methods, or blocks are called local
variables. Methods are used to perform certain actions, and they are also known
as functions.

• Instance variables − Instance variables are variables within a class but


outside any method.
Creating Objects: - The object is a basic building block of an OOPs language. An
object represents the class and consists of properties and behavior. Properties refer
to the fields declared within class and behavior represents the methods available in
the class.

public class Student{


public static void main(String[] args) {
//creating an object using new keyword
Student obj = new Student();
}
}

ii) Accessing Class Members:


The object name along with the ( . ) dot operator is used to access members of a class.
syntax:
objectname.variablename;
objectname.methodname(parameter-list);
Example:
public class Student{
String name = "Gopal";
int mark1 = 50;
int mark2 = 70;
int mark3 = 60;
int total;
float average;

void total() {
total = mark1+mark2+mark3;
System.out.println("Total:"+total);
}
void average() {
average = total/3;
System.out.println("Average:"+average);
}
public static void main(String[] args) {
//creating an object using new keyword
Student obj = new Student();
//invoking method using the object
System.out.println("Name of the student:"+name);
obj.total();
obj.average();
}
}

iii) Accessing class members using multiple objects:

We can also create multiple objects and store information in it through reference variable.
Example:
class Student{
String name;
int id;
}

class Student1{
public static void main(String[] args) {
//creating an object using new keyword
Student s1 = new Student();
Student s2 = new Student();

//invoking method using the object and dot operator


s1.name="Riya";
s1.id = 101;
s2.name="Anu";
s2.id = 102;
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);

}
}

Java Tokens:-
Tokens are the smallest elements of a program that is meaningful to the compiler. They
are also known as the fundamental building blocks of the program. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
6. Comments
7. Separators
Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names.
Ex:-abstract assert boolean
break byte case
catch char class
const continue default

Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of long sequence of letters and digits
with either a letter or the underscore (_) as a first character.
Ex:- MyVariable n
MYVARIABLE m
I sal
Constants/Literals:- Constants are also like normal variables. But the only difference
is, their values cannot be modified by the program once they are defined. Constants
refer to fixed values. They are also called as literals. Constants may belong to any of the
data type.
Syntax:
final data_type variable_name;

Special Symbols:
Ex:- [] () {}, ; * =
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used
separator in java is semicolon (;).

Java Data Types

Data types are the kind of data that variables hold in a programming language. A data type is an
attribute of data that tells the compiler or interpreter how the programmer plan to use the data.
There are two types of data types in Java:
• Primitive data types ( intrinsic or built-in types )
• Non-primitive data types (derived types )

Data
Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127
2
short Stores whole numbers from -32,768 to 32,767
bytes
4
int Stores whole numbers from -2,147,483,648 to 2,147,483,647
bytes
8 Stores whole numbers from -9,223,372,036,854,775,808 to
long
bytes 9,223,372,036,854,775,807
4
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
bytes
8
double Stores fractional numbers. Sufficient for storing 15 decimal digits
bytes
boolean 1 bit Stores true or false values
boolean 1 bit Stores true or false values
2
char Stores a single character/letter or ASCII values
bytes

1. Primitive Data Types :

Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase
letter. The primitive data types include char, byte, short, int, long, boolean, float, and double.

char :

The char data type is used to store a single character. The character must be surrounded by single
quotes.
char grade = 'A'; //A is a charater
System.out.println(grade);

byte:
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory.
byte num = 120;
System.out.println(num);

short:

The short data type can store whole numbers from -32768 to 32767.
short num = 6000;
System.out.println(num);

int:

The int data type is the preferred data type when we create variables with a numeric value. The
int data type can store whole numbers from -2147483648 to 2147483647.
int num = 100000;
System.out.println(num);

long:

The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that
you should end the value with an "L".
long num = 16000000000L;
System.out.println(num);

boolean:

A boolean data type is declared with the boolean keyword and can only take the values true or
false.
boolean male = true;
boolean female = false;
System.out.println(male); // Outputs true
System.out.println(female); // Outputs false

float:

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "f".
float num = 4.75f;
System.out.println(num);

double:

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
should end the value with a "d".
double num = 18.85d;
System.out.println(num);

2. Non-Primitive Data Types


Non-primitive types are created by the programmer. non-primitive types start with an uppercase
letter. The non-primitive data types include Classes, Interface, Strings, and Arrays.
Classes:
A class is a group of objects which have common properties. It is a user-defined data type with a
template that serves to define its properties. To create a class, use the keyword class. Let's learn
the class in detail in upcoming chapters.
public class Main { // Main is the class name int num = 20; void getdata(){ } void putdata(){ } }

Interfaces:
The interface keyword to create an interface. An interface is slightly different from the class. It
contains only ****constants and method declarations.
interface car // car is the interface name{ void start(); void stop(); }

Strings:
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes.
String greeting = "Hello World"; System.out.println(greeting);

Arrays:
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.
String[] cars = {"Audi", "BMW", "Ford"}; int[] num = {10, 20, 30, 40};

Java Type Casting:-


ype casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:

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


type sizebyte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a larger type to a smaller size
typedouble -> float -> long -> int -> char -> short -> byte

Widening casting is done automatically when passing a smaller size type to a


larger size type
Example:-
public class Main {
public static void main(String[] args) {
int valueInt = 8;
double valueDouble = valueInt; // Automatic casting: int to double
System.out.println(valueInt); // Outputs 8 ( displays the valueInt value )
System.out.println(valueDouble); // Outputs 8.0 (the integer 8 is automatically )
}}

Narrowing casting must be done manually by placing the type in parentheses in front of the
value.
syntax:
type variable1 = (type) variable2;
Example:
public class Main {
public static void main(String[] args) {
double valueDouble = 8.79;
int valueInt = (int) valueDouble; // Manual casting: double to int
System.out.println(valueDouble); // Outputs 8.79
System.out.println(valueInt); // Outputs 8
}}

here (int) is the used in parentheses in front of the value to convert double data type to int data
type.
Operator is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Unary Operator :- The Java unary operators require only one operand. Unary operators are used to perform
various operations

o i.e.: incrementing/decrementing a value by one


o negating an expression
o inverting the value of a Boolean

Arithmetic Operators:- Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
Assignment Operators:- Assignment operators are used to assign values to variables.
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Relational/Comparison Operators:- Comparison operators are used to compare


two values (or variables). This is important in programming, because it helps us to
find answers and make decisions. The return value of a comparison is
either true or false.
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators:- You can also test for true or false values with logical
operators. Logical operators are used to determine the logic between variables or
values.
Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result !(x < 5 && x < 10)
is true
Java Strings:- Strings are used for storing text. A String variable contains a collection of
characters surrounded by double quotes.

String Length:- A String in Java is actually an object, which contain methods that can perform
certain operations on strings. For example, the length of a string can be found with the length()
method.

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


System.out.println("The length of the txt string is: " + txt.length());

There are many string methods available, for example toUpperCase() and
toLowerCase():
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a
specified text in a string (including whitespace).
String txt = "Please study well!";
System.out.println(txt.indexOf("study"));

Basic Math methods/functions:-


The java.lang.Math class contains various methods for performing basic numeric operations such as the
logarithm, cube root, and trigonometric functions etc.
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to
second argument.
Math.sin() It is used to return the trigonometric Sine value of a Given double value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double value.
Math.tan() It is used to return the trigonometric Tangent value of a Given double value.
Decision Making and Looping: -
LOOPS:
A Loop executes the sequence of statements many times until the stated
condition becomes false. A loop consists of two parts, a body of a loop and a control
statement. The purpose of the loop is to repeat the same code several times.

1. while loop : A while loop statement in Java programming language repeatedly


executes a target statement as long as a given condition is true. When executing, if
the boolean_expression result is true, then the actions inside the loop will be
executed. When the condition becomes false, the loop will exit.

Syntax:

while(Boolean_expression) {
// Statements
}

Example:

public class Looping {

public static void main(String args[]) {


int x = 10;

while( x < 15 ) {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}
}
}
/*EXPLANATION:
The loop executes until the value of x is less than 15, the value of x is incremented
by 1. When the condition is false the loop exit */

/*OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */

2. do while loop : A do-while loop is similar to a while loop with one exception that
it executes the statements inside the body of the do-while before checking the
condition. If the Boolean expression is true, the statements in the loop execute again.
This process repeats until the Boolean expression is false.

Syntax:

do {
// Statements
}while(Boolean_expression);

Expressions:

public class Looping {

public static void main(String args[]) {


int x = 10;

do {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}while( x < 15 );
}
}
/*EXPLANATION:
The control passes to the body of the loop and then checks the condition.
If the condition is less than 15 loop executes, and then the value of x is incremented
by 1. When the condition false the loop terminates. */
/*OUTPUT

value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */

3. for loop:- A for loop ( finite loop ) is a repetition control structure that allows you
to efficiently write a loop that needs to be executed a specific number of times. A for
loop is useful when you know how many times a task is to be repeated.

Syntax:

for(initialization; Boolean_expression; update) {


// Statements
}

Example:

public class Looping {

public static void main(String args[]) {

for(int x = 10; x < 15; x = x + 1) {


System.out.print("value x : " + x );
System.out.print("\\n");
}
}
}
/*EXPLANATION:
The loop executes until the value of x is less than 15,
when the condition is false the loop exit*/

/* OUTPUT

value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */

Jump Statements:-
Jump statements are used to unconditionally transfer program control from
one point to elsewhere in the program. Jump statements are primarily used to
interrupt loops or switch-case instantly. Java supports three jump statements: break,
continue, and return.

i) break statement:
The break construct is used to break out of the middle of loops: for, do, or while
loop. When a break statement is encountered, execution of the current loops
immediately stops and resumes at the first statement following the current loop.

Example:

public class BreakStatement{


public static void main(String args[]) {
System.out.println("Welcome to ShapeAI");
for (int i = 1; i <= 10; i++) {
System.out.println("i = "+i);
if (i == 5) {
System.out.println("\\nBye");
break;//hence break statement is used to terminate the loop
}
}
}
}
/*OUTPUT:
Welcome to ShapeAI
i=1
i=2
i=3
i=4
i=5
Bye */

ii) continue Statement:


The continue statement also skips the remaining statements of the body of the loop
where it is defined but instead of terminating the loop, the control is transferred to
the beginning of the loop for the next iteration. The loop continues until the test
condition of the loop becomes false.

Example:

public class ContinueStatement{


public static void main(String args[]) {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5)
continue; // continue statement breaks the loop continues until the test
condition of the loop becomes false
System.out.print(i + " ");
}
}
}
/*OUTPUT:
1 2 3 4 6 7 8 9 10 */

iii) return Statement:


A return statement ends the execution of a function, and returns control to the calling
function. Execution resumes in the calling function at the point immediately
following the call. A return statement can return a value to the calling function.

Example:

public class ReturnStatement {


int display() {
return 5;
}
public static void main(String[] args) {
ReturnStatement e = new ReturnStatement();
System.out.println(e.display());
}
}

/*OUTPUT:
5 */

Java Decision Making And Branching: -


“Decision making and branching” is one of the most important concepts of
computer programming. Programs should be able to make logical (true/false)
decisions based on the condition provided. So controlling the execution of
statements based on certain condition or decision is called decision making and
branching.

1.If Statements
The if statement is used to test the condition. It checks boolean conditions true or
false. There are various types of if statements in Java.

• Simple if statement
• if-else statement
• if-else-if ladder
• nested if statement

i) Simple if Statement :
The Java if statement tests the condition. It executes the *if block* if the
condition is true. Where boolean_expression is a condition.

Syntax:

if(Boolean_expression/condition) {
// Statements will execute if the Boolean expression is true
}
Example:

public class Branching {

public static void main(String args[]) {


int num = 10;

if( num < 20 ) {


System.out.print("Welcome to ShapeAI");
}
}
}
/*EXPLANATION:
hence num value 10 is less than 20, it executes the statement inside if block*/

/*OUTPUT:
Welcome to ShapeAI */

ii) if-else Statement :


The Java if-else statement also tests the condition. It executes the if block, if the
condition is true otherwise else block, is executed.

Syntax:

if(Boolean_expression/condition) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Statement-X;

Example:

public class Branching {

public static void main(String args[]) {


int num = 30;

if( num < 20 ) {


System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
/*EXPLANATION:
executes the else statement hence the num value 30 is greater than 20 */

/*OUTPUT
This is else statement */

iii) if-else-if ladder Statement :


The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
Statement-X;

Example:

public class Branching{

public static void main(String args[]) {


int num = 30;
if (num == 10) {
System.out.print("Value of num is 10");
} else if (num == 20) {
System.out.print("Value of num is 20");
} else if (num == 30) {
System.out.print("Value of num is 30");
} else {
System.out.print("This is else statement");
}
}
}

/*EXPLANATION:
executes the second else if block hence the num value 30 is equal to 30 */

/* OUTPUT
Value of X is 30 */

iv) nested if statement :-


The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when the outer if block condition is

Syntax:

switch(expression) {
case value :
// Statements
break;

case value :
// Statements
break;

// You can have any number of case statements.


default : // Optional
// Statements
}
Statement-X;

Example:

public class Switching {

public static void main(String args[]) {

char grade = 'C';

switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Good");
break;
case 'C' :
System.out.println("Well done");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

/*EXPLANATION:
The given expression grade is assigned with 'C'. hence it matches with the case 'C'.
So case 'C' statement "Well done" is executed*/

/*OUTPUT:

Well done
Your grade is C */
Ternary operator (? :) :-
The meaning of ternary is composed of three parts. The ternary operator
(?:) consists of three operands. It is used to evaluate Boolean expressions. The
operator decides which value will be assigned to the variable. It is the only
conditional operator that accepts three operands. It can be used instead of the if-else
statement.

Syntax:
variable = (condition) ? expression1 : expression2
Example:-
public class TernaryOperatorExample
{
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}

Labeled Loop:-
A label is a valid variable name that denotes the name of the loop to where the control
of execution should jump. To label a loop, place the label before the loop with a
colon at the end. Therefore, a loop with the label is called a labeled loop.

1. Java Labeled “for” Loop:- Labeling a for loop is useful when we want to break
or continue a specific for loop according to requirement. If we put a break statement
inside an inner for loop, the compiler will jump out from the inner loop and continue
with the outer loop again.
if we need to jump out from the outer loop using the break statement given inside
the inner loop then we should define the label along with the colon(:) sign before the
loop.
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}

Example:-
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}

2. Java Labeled while Loop


Syntax: labelName:
while ( ... )
{
//statements to execute }
Example:-
public class LabledWhileLoop
{
public static void main(String args[])
{
int i = 0;
whilelabel:
while (i < 5)
{
System.out.println("outer value of i= " + i);
i++;
forlabel:
for (int j = 0; j < 5; j++)
{
if (j > 0)
{
//execution transfer to the for loop
continue forlabel;
} //end of if
if (i > 1)
{
//execution transfer to the while loop
continue whilelabel;
} //end of if
System.out.println("inner value of i= " + i + ", j= " + j);
} //end of for
} //end of while
} //end of main
}

For each Loop:-


In Java, the for-each loop is used to iterate through elements of arrays and
collections. It is also known as the enhanced for loop.
Syntax:-
for (type variableName : arrayName) {
// code block to be executed
}
Example:-
class Main {
public static void main(String[] args) {

// create an array
int[] numbers = {3, 9, 5, -5};

// for each loop


for (int number: numbers) {
System.out.println(number);
}
}
}

You might also like