0% found this document useful (0 votes)
5 views74 pages

Unit 1

The document provides an overview of Java, including its features, architecture, and components such as the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It also covers Java program structure, data types, typecasting, operators, input/output methods, and control flow statements. The content is aimed at introducing the basics of Java programming to learners.

Uploaded by

newmovies1638
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)
5 views74 pages

Unit 1

The document provides an overview of Java, including its features, architecture, and components such as the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It also covers Java program structure, data types, typecasting, operators, input/output methods, and control flow statements. The content is aimed at introducing the basics of Java programming to learners.

Uploaded by

newmovies1638
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/ 74

Java Basics

Unit 1

-Ms. Vishakha Bagwe


Overview of java
? Programming language & platform.
? Developed by sun microsystems(now Oracle owns).
? James Gosling is known as the Father of Java.
? Main features of Java are:-
1. Object oriented
2. Portable
3. Platform independent
4. Interpreted

-Ms. Vishakha Bagwe


Why Java is called a Platform?

? An environment(hardware or software) in which a program runs is called a


Platform.
? Java has its runtime environment (JRE) which is a platform.

-Ms. Vishakha Bagwe


Features of Java

Simple
Object-Orient
Dynamic
ed

Distributed Portable

Multithreaded
Features Platform
Independent
of Java
High
Secured
Performance

Interpreted Robust
Architecture
Neutral
-Ms. Vishakha Bagwe
Architecture and its components

-Ms. Vishakha Bagwe


Compiling and Executing Java
program
Source code Is read by Compiler Produces Bytecode
(.java) (javac) (.class)

Is interpreted by

Results in
Program
Execution JVM

Windows
Mac OS
Linux
-Ms. Vishakha Bagwe
Components of Java Architecture

? The Java architecture includes the three main components:


• Java Virtual Machine JVM
• Java Runtime Environment JRE
• Java Development Kit JDK

-Ms. Vishakha Bagwe


JDK(Java Development Kit)
? Software development environment used for
applets and java applications.
? Developers can use it on any platform.
? More than one version of JDK can be installed
on the same computer.
? Consists of a compiler(javac) which converts
java code into bytecode.
? Also includes JRE, an interpreter(java).

-Ms. Vishakha Bagwe


JRE(Java Runtime Environment)

? Also written as Java RTE, it is a piece of software designed to run other


softwares.
? Contains set of libraries(awt, io, math, util, etc), JVM and other supporting
files.
? JRE provides the user with environment to only run the java program(or
application) not develop.
? All JDK versions comes along with JRE, so no need to download and install
JRE separately.

-Ms. Vishakha Bagwe


JVM(Java Virtual Machine)

? It is an engine that provides a runtime environment. It converts Java


bytecode into machine language.
? JVM comes with JIT(Just-in-Time) compiler that converts Java source code
into low-level machine language.
? It provides basic java functions like memory management, security,
garbage collection, and more.
? It is independent from hardware and the operating system. So, you can
write a java program once and run anywhere.

-Ms. Vishakha Bagwe


Java Class File

? A class file is the compiled form of a .java file. When we compile the Java
source code (.java file), it generates a .class file.
? The javac command is used to convert the Java source file into the class
file. The java command is used to run a Java program stored in a .class file.

-Ms. Vishakha Bagwe


The Java API

? API stands for application program interface.


? A programmer writing an application program can make a request to the
Operating System using API (using graphical user interface or command
interface).
? It is a set of routines, protocols and tools for building software and
applications.
? It may be any type of system like a web-based system, operating-system or
a database System.

-Ms. Vishakha Bagwe


Java program structure Documentation
Section

? Documentation Section
✔ The documentation section is an important section but optional Package Statement
for a Java program.
✔ It includes basic information about a Java program.
Import Statement
✔ The information includes the author's name, date of creation,
version, program name, company name, and description of
the program.
Interface Statement
✔ It improves the readability of the program.
✔ Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the Class Definitions
program.
✔ To write the statements in the documentation section, we
use comments. The comments may be single-line, multi-line. Main method { main
-Ms. Vishakha Bagwe
method definition }
? Package Declaration
✔ The package declaration is optional.
✔ It is placed just after the documentation section.
✔ There can be only one package statement in a Java program. It must be
defined before any class and interface declaration.
✔ We use the keyword package to declare the package name.

? Import Statements
✔ The package contains the many predefined classes and interfaces.
✔ The import statement represents the class stored in the other package.
✔ We use the import keyword to import the class.
✔ It is written before the class declaration and after the package statement.
✔ We use the import statement in two ways, either import a specific class or
import all classes of a particular package.
-Ms. Vishakha Bagwe
? Interface Section
✔ It is an optional section. We use the interface keyword to create an interface.
✔ An interface is a slightly different from the class.
✔ It contains only constants and method declarations.
✔ Another difference is that it cannot be instantiated.
✔ We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword.

? Class Definition
✔ Without the class, we cannot create any Java program.
✔ A Java program may contain more than one class definition. We use
the class keyword to define the class.
✔ It contains information about user-defined methods, variables, and constants.
✔ Every Java program has at least one class that contains the main() method.
-Ms. Vishakha Bagwe
? Main Method
✔ The execution of all Java programs starts from the main() method.
✔ In other words, it is an entry point of the class.
✔ It must be inside the class. Inside the main method, we create objects and
call the methods
✔ public static void main(String[] args)
{
}

-Ms. Vishakha Bagwe


Main method of Java

? public: It is an access specifier. We should use a public keyword before the


main() method so that JVM can identify the execution point of the program. If
we use private, protected, and default before the main() method, it will not be
visible to JVM.
? static: You can make a method static by using the keyword static. We should
call the main() method without creating an object. Static methods are the
method which invokes without creating the objects, so we do not need any
object to call the main() method.
? void: In Java, every method has the return type. Void keyword acknowledges
the compiler that main() method does not return any value.

-Ms. Vishakha Bagwe


Contd…

? main(): It is a default signature which is predefined in the JVM. It is called by


JVM to execute a program line by line and end the execution after completion
of this method.
? String args[]: The main() method also accepts some data from the user. It
accepts a group of strings, which is called a string array. It is used to hold the
command line arguments in the form of string values.
? Here, agrs[] is the array name, and it is of String type. It means that it can
store a group of string. Remember, this array can also store a group of
numbers but in the form of string only. Values passed to the main() method is
called arguments. These arguments are stored into args[] array, so the name
args[] is generally used for it.

-Ms. Vishakha Bagwe


Java Tokens

? The Java compiler breaks the line of code into text (words) is called Java
tokens. These are the smallest element of the Java program.
? The Java compiler identified these words as tokens.
? These tokens are separated by the delimiters. It is useful for compilers to
detect errors. Remember that the delimiters are not part of the Java tokens.

-Ms. Vishakha Bagwe


? Example,
1. public class Demo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("java code");
6. }
7. }
? In the above code snippet, public, class, Demo, {, static, void, main, (,
String, args, [, ], ), System, ., out, println, java code, etc. are the Java
tokens.
? The Java compiler translates these tokens into Java bytecode. Further, these
bytecodes are executed inside the interpreted Java environment.

-Ms. Vishakha Bagwe


Java Statements
? In Java, a statement is an executable instruction that tells the compiler what
to perform.
? It forms a complete command to be executed and can include one or more
expressions.
Expression • Expression is the combination of values, variables, operators,
and method calls.

Statements • (6+7), num=2, count++, etc.

Declaration • We declare variables and constants by specifying their data type and
name.
• int quantity;

Statements • int quantity=10;


• int quantity, length;

• Decide the flow (order or sequence of execution of statements) of a

Control Java program.


• Types:
• Conditional or Selection statement- if, if..else, switch case
Statements • Loop or Iterative statement- for, while, do-while
• Flow control or Jump statement- return, continue, break
-Ms. Vishakha Bagwe
Datatypes in Java

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

-Ms. Vishakha Bagwe


Primitive datatypes

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

-Ms. Vishakha Bagwe


Non-Primitive datatypes
Data Type Description
Strings A string is an object that represents a sequence of
characters. The java.lang.String class is used to create
a string object.
Arrays Arrays store one or more values of a specific data type
and provide indexed access to store the same. A
specific element in an array is accessed by its index.
Classes A class in Java is a blueprint which includes all your
data. A class contains fields(variables) and methods
to describe the behavior of an object.
Interfaces Like a class, an interface can have methods and
variables, but the methods declared in interface are
by default abstract (only method signature, no body).

-Ms. Vishakha Bagwe


Typecasting

? Type casting is a method or process that converts a data type into another
data type in both ways manually and automatically. The automatic conversion
is done by the compiler and manual conversion performed by the
programmer.

Narrowing Type casting

double float long int short byte

Widening Type casting

-Ms. Vishakha Bagwe


Widening Type Casting

? Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place
when:
• Both data types must be compatible with each other.
• The target type must be larger than the source type.

-Ms. Vishakha Bagwe


Narrowing Type Casting

? Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up.
? It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error.

-Ms. Vishakha Bagwe


Operators in Java

? Operators in Java can be classified into 5 types:


1. Arithmetic Operators +, -, *, /, %
2. Assignment Operators =, +=, -=, *=, /=, %=
3. Relational Operators ==, !=, >, <, >=, <=
4. Logical Operators &&, ||, !
5. Unary Operators +, -, ++, --, !
6. Bitwise Operators ~, <<, >>, &, ^

-Ms. Vishakha Bagwe


Java Scanner Class (Input from user)

? The object of Scanner class of the java.util package is used to read input
data from different sources.
import java.util.Scanner;
? Java Scanner Methods to Take Input
? nextInt()
? nextFloat()
? nextLine()
? next()

Classname objectname=new Classname();

-Ms. Vishakha Bagwe


? Then, we need to create an object of the Scanner class. We can use the
object to take input from the user.
// create an object of Scanner
Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

-Ms. Vishakha Bagwe


Java Output (Display output to user)

? In Java, you can simply use


System.out.println(); or System.out.print();
? print()- It prints string inside the quotes.
? println()- It prints string inside the quotes similar like print() method. Then the
cursor moves to the beginning of the next line.

-Ms. Vishakha Bagwe


Control Flow Statements
Java if (if-then) Statement

• Syntax:
if (condition) {
// statements
}
Here, condition is a boolean expression such as age >= 18.

if condition evaluates to true, statements are executed


if condition evaluates to false, statements are skipped
• Example:
class Ifexample {
public static void main(String[] args) {

int number = 10;

// checks if number is less than 0


if (number < 0) {
System.out.println("The number is negative.");
}

System.out.println("Statement outside if block");


}
}
Java if...else (if-then-else) Statement

● Syntax:

if (condition) {
// codes in if block
}
else {
// codes in else block
}

Here, the program will do one task (codes inside if block) if the
condition is true and another task (codes inside else block) if the
condition is false.
Example:
class Ifelseexample {
public static void main(String[] args) {
int number = 10;
// checks if number is greater than 0
if (number > 0) {
System.out.println("The number is positive.");
}
// execute this block
// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}
System.out.println("Statement outside if...else block");
}
}
Java if...else...if Statement
Syntax:
Here, if statements are executed from the top towards
if (condition1) {
the bottom. When the test condition is true, codes
// codes
} inside the body of that if block is executed. And,

else if(condition2) { program control jumps outside the if...else...if ladder.


// codes
If all test expressions are false, codes inside the body
}
of else are executed.
else if (condition3) {
// codes
}

else {
// codes
}
Example }
public class IfElseIfExample {
else if(marks>=70 && marks<80){
public static void main(String[] args) {
System.out.println("B grade");
int marks=65;
}

else if(marks>=80 && marks<90){


if(marks<50){
System.out.println("A grade");
System.out.println("fail");
}else if(marks>=90 && marks<100){
}
System.out.println("A+ grade");
else if(marks>=50 && marks<60){
}else{
System.out.println("D grade");
System.out.println("Invalid!");
}
}
else if(marks>=60 && marks<70){
}
System.out.println("C grade");
}
Java Nested if statement

The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when outer if block condition is
true.
Syntax:
if(condition){

//code to be executed

if(condition){

//code to be executed

}
Example:
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Switch-case statement
The Java switch statement executes one statement from multiple conditions. It
is like if-else-if ladder statement.
○ There can be one or N number of case values for a switch expression.
○ The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
○ The case values must be unique. In case of duplicate value, it renders
compile-time error.
○ Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the
switch expression. If a break statement is not found, it executes the next
case.
○ The case value can have a default label which is optional.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Example: case 6: monthString="6 - June";
//Java Program to demonstrate the example of Switch statement
break;
//where we are printing month name for the given number
case 7: monthString="7 - July";
public class SwitchMonthExample {
break;
public static void main(String[] args) {
case 8: monthString="8 - August";
//Specifying month number
break;
int month=7;
case 9: monthString="9 - September";
String monthString="";
break;
//Switch statement

switch(month){ case 10: monthString="10 - October";

//case statements within the switch block break;

case 1: monthString="1 - January"; case 11: monthString="11 - November";

break; break;

case 2: monthString="2 - February"; case 12: monthString="12 - December";


break; break;
case 3: monthString="3 - March"; default:System.out.println("Invalid Month!");
break; }
case 4: monthString="4 - April";
//Printing month of the given number
break;
System.out.println(monthString);
case 5: monthString="5 - May";
}
break;
}
Iterations
For loop

Java for loop is used to run a block of code for a certain


number of times.
Syntax:
for(initialization; condition; increment/decrement){

//statement or code to be executed


}
Example:
import java.util.*;
public class Multiplication
{
public static void main(String []args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int n=sc.nextInt(); //Declare and initialize the number
System.out.println("The multiplication table of "+n+" is: ");
//Print the multiplication table
for(int i=1;i<=10;i++)
{
System.out.println(n+" * "+i+" = "+ (n*i));
}
}}
While loop

Java while loop is used to run a specific code until a


certain condition is met.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
Example:
class SumWhile {
public static void main(String args[])
{
int x = 1, sum = 0;
// Exit when x becomes greater than 10
while (x <= 10) {
sum = sum + x; // summing up x
// Increment the value of x for next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
Do..while loop

The do...while loop is similar to while loop. However, the body of


do...while loop is executed once before the test expression is
checked.
Syntax:
do{

//code to be executed / loop body

//update statement

}while (condition);
Example: Sum of Natural Numbers up to a Given Number
public class Sumdowhile {
public static void main(String args[])
{
int x = 7, sum = 0;
do { // The line will be printed even if the condition is false
sum += x;
x--;
} while (x > 0);
System.out.println(“Sum: ” + sum);
}}
For-each loop
The for-each loop is used to traverse array in Java. It is
easier to use than simple for loop because we don't need
to increment value and use subscript notation.
It works on the basis of elements and not the index. It
returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example 1:
//Java For-each loop example which prints the elements of
the array

class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};

//Printing array using for-each loop


for(int i:arr){
System.out.println(i);
}
Example 2:
// Calculate the sum of all elements of an array
class Sumarray {
public static void main(String[] args) {
// an array of numbers
int[] num = {3, 4, 5, -5, 0, 12};
int sum = 0;
// iterating through each element of the array
for (int n: num) {
sum += n;
}
System.out.println("Sum = " + sum);
}
}
Labeled Statements
Break statement

When a break statement is encountered inside a loop, the


loop is immediately terminated and the program control
resumes at the next statement following the loop.
The Java break statement is used to break loop or switch
statement. It breaks the current flow of the program at
specified condition.
Syntax:
break;
Example:
public class BreakExample {

public static void main(String[] args) {

//using for loop


for(int i=1;i<=10;i++){

if(i==5){
break; //breaking the loop
}
System.out.println(i);
}
} }
Continue statement

The continue statement skips the current iteration of a loop


(for, while, do...while, etc).
After the continue statement, the program moves to the
end of the loop. And, test expression is evaluated
Syntax:
continue;
Example:
public class ContinueExample {
public static void main(String[] args) {

for(int i=1;i<=10;i++){ //for loop


if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
} }
}
Return Statement
In Java, every method is declared with a return type such as int, float,
double, string, etc.
These return types required a return statement at the end of the
method. A return keyword is used for returning the resulted value.
The void return type doesn't require any return statement. If we try to
return a value from a void method, the compiler shows an error.

○ The return type of the method and type of data returned at the
end of the method should be of the same type. For example, if a
method is declared with the float return type, the value returned
should be of float type only.
Example:
public class ReturnTest
{
int square(int num){
int sq=num*num;
return sq; // return a square value.
}
public static void main(String[] args)
{
// Create an obejct of class Test.
ReturnTest t = new ReturnTest();
// Call the method using object reference variable. Since the return type of
this method is int, we will store it using a variable of type int.
int squareOfNumber = t.square(20);
// Displaying the result.
System.out.println("Square of 20: " +squareOfNumber);
}
}
Arrays
Introduction
An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
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.
Types of Array

There are two types of array.

○ Single Dimensional Array


○ Multidimensional Array
Single dimensional array- Syntax

How to declare an array in Java?

In Java, here is how we can declare an array.

dataType[] arrayName;

dataType []arrayName;

dataType arrayName[];

Example:

int rollno[];
Instantiation of an Array in Java
arrayName = new dataType[size];

To define the number of elements that an array can hold, we have to allocate memory for
the array in Java. For example,

// declare an array

int rollno[];

// allocate memory

rollno = new int[10];

In Java, we can declare and allocate the memory of an array in one single statement. For
example,

int rollno[] = new int[10];


How to Initialize Arrays in Java?

//declare and initialize and array

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

Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java, using
the index number. For example,
// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Important points to remember

Note:

● Array indices always start from 0. That is, the first element of an
array is at index 0.
● If the size of an array is n, then the last element of the array will be
at index n-1.
Access Elements of an Array in Java

We can access the element of an array using the index number. Here is the
syntax for accessing elements of an array,

// access array elements


array[index]
Example:
class Arraydemo {

public static void main(String[] args) {

int[] age = {12, 4, 5, 2}; // create an array

// access each array elements

System.out.println("Accessing Elements of Array:");

System.out.println("First Element: " + age[0]);

System.out.println("Second Element: " + age[1]);

System.out.println("Third Element: " + age[2]);

System.out.println("Fourth Element: " + age[3]);

}}
We can use loops to access all the elements of the array at once
class Arrdemo {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5};

// loop through the array using for loop

System.out.println("Using for Loop:");

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

System.out.println(age[i]);

}
Multidimensional arrays

A multidimensional array is an array of arrays. Each element of a multidimensional


array is an array itself.

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayName;
2. dataType [][]arrayName;
3. dataType arrayName[][];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column


//Java Program to illustrate the use of multidimensional array

Initialize a 2d array in Java class Testarray{

public static void main(String args[]){


int[][] a = { //declaring and initializing 2D array
{1, 2, 3}, int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

{4, 5, 6}, //printing 2D array

{7, 3, 5}, for(int i=0;i<3;i++){

for(int j=0;j<3;j++){
};
System.out.print(arr[i][j]+" "); }

System.out.println();

}}

You might also like