0% found this document useful (0 votes)
27 views23 pages

UNIT-I JAVA FUNDAMENTALS

Uploaded by

hod cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

UNIT-I JAVA FUNDAMENTALS

Uploaded by

hod cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Java Buzzwords or Features of Java

 Simple.
 Object-oriented.
 Distributed.
 Interpreted.
 Robust.
 Secure.
 Architecture neutral.
 Portable.

Data Types 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.

Java Primitive Data Types


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

Java is a statically-typed programming language. It means, all variables must be


declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
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

Boolean Data Type


The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false
conditions.

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit
signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited.

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point.
Its value range is unlimited. The double data type is generally used for
decimal values just like float. The double data type also should never be
used for precise values, such as currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range
lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data
type is used to store characters.

Example:

1. char letterA = 'A'

Java Variables
A variable is a container which holds the value while the Java program

is executed. A variable is assigned with a data type.


Variable is a name of memory location. There are three types of variables
in java: local, instance and static.

Types of Variables
There are three types of variables in Java

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods
in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static

It is called an instance variable because its value is instance-specific and


is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be


local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12.}//end of class

Java Arrays
Normally, 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.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java


Array
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

For-each Loop for Java Array


We can also print the Java array using for-each loop

. The Java for-each loop prints the array elements one by one. It holds an array element in a variable,
then executes the body of the loop.

//Java Program to print the array elements using for-each loop


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

//Java Program to return an array from the method


class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as
matrix form).

Example to instantiate Multidimensional Array in Java

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

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print
the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
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();
}
}}

Output:

123
245
445

Operators in Java
Operator in Java

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.

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Java Arithmetic Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Output:

15
5
50
2
0

Java Left Shift Operator Example

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Output:

1. 40
2. 80
3. 80
4. 240

Java AND Operator Example: Logical && and Bitwise &


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:

false
false

Java Ternary Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:

2
Java Control Statements | Control Flow in Java

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement

2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop

3. Jump statements
o break statement
o continue statement

There are two types of decision-making statements in Java, i.e., If statement and switch statement.

In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Simple if statement

Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}

Ex:

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20

2) if-else statement

The if-else statement

is an extension to the if-statement, which uses another block of code, i.e., else block. The else block
is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Ex:

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG
{
public static void main(String args[])
{
int a=10;
int b=20;

if(a==10){
if(b==20){
System.out.println("GeeksforGeeks");
}
}
}
}

O/P:
GeeksforGeeks
Code explanation :
 In the first step, we have imported the required packages.
 In the next step, we have created a class names GFG
 In the next step, we have written the main method.
 Within the main method, we have assigned values to variables.
 Using nested if conditions, we have printed a statement.
 Here two statements are true. Hence statement was executed successfully.
Switch Statement in Java
The switch statement is a multi-way branch statement. In simple words, the Java switch
statement executes one statement from multiple conditions.

Some Important Rules for Switch Statements

1. There can be any number of cases just imposing condition check but remember duplicate
case/s values are not allowed.
2. The value for a case must be of the same data type as the variable in the switch.
3. The value for a case must be constant or literal. Variables are not allowed.
4. The break statement is used inside the switch to terminate a statement sequence.
5. The break statement is optional. If omitted, execution will continue on into the next case.
6. The default statement is optional and can appear anywhere inside the switch block. In case, if
it is not at the end, then a break statement must be kept after the default statement to omit
the execution of the next case statement.

Syntax: Switch-case
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional

case value2 :
// Statements
break; // break is optional

// We can have any number of case statements


// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}
Ex:
// Java program to Demonstrate Switch Case
// with Primitive(int) Data Type
// Class
public class GFG {

// Main driver method


public static void main(String[] args)
{
int day = 5;
String dayString;

// Switch statement with int data type


switch (day) {

// Case
case 1:
dayString = "Monday";
break;

// Case
case 2:
dayString = "Tuesday";
break;

// Case
case 3:
dayString = "Wednesday";
break;

// Case
case 4:
dayString = "Thursday";
break;

// Case
case 5:
dayString = "Friday";
break;

// Case
case 6:
dayString = "Saturday";
break;

// Case
case 7:
dayString = "Sunday";
break;

// Default case
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}

Break statement in Java


Break Statement is a loop control statement that is used to terminate the loop. As soon as the
break statement is encountered from within a loop, the loop iterations stop there, and control
returns from the loop immediately.
Syntax:
break;
Break: In Java, the break is majorly used for:
 Terminate a sequence in a switch statement (discussed above).
 To exit a loop.
 Used as a “civilized” form of goto.

Ex:
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo {
public static void main(String args[])
{
// 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);


}
System.out.println("Loop complete.");
}
}

Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Continue statement is often used inside in programming languages inside loops control structures.
Inside the loop, when a continue statement is encountered the control directly jumps to the
beginning of the loop for the next iteration instead of executing the statements of the current
iteration.
Syntax: continue keyword along with a semicolon
continue;
Ex:
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}

Output:

1
2
3
4
6
7
8
9
10

Java For loop with Examples


Syntax:
for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

Ex:
/*package whatever //do not write package name here */
// Java program to write a code in for loop from 1 to 10
class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10
Java while loop with Examples
Syntax:
while (test_expression)
{
// statements

}
Ex:
// Java program to illustrate while loop.

class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
System.out.println("Hello World");
// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-
while loop is an Exit control loop.
Syntax:
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression);
Ex:
// Java Program to Illusterate One Time Iteration
// Inside do-while Loop
// When Condition IS Not Satisfied

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// initial counter variable
int i = 0;

do {

// Body of loop that will execute minimum


// 1 time for sure no matter what
System.out.println("Print statement");
i++;
}

// Checking condition
// Note: It is being checked after
// minimum 1 iteration
while (i < 0);
}
}
Output
Print statement
For-each loop in Java
for-each Loop Sytnax
The syntax of the Java for-each loop is:

for(dataType item : array) {


...
}

Here,

 array - an array or a collection

 item - each item of array/collection is assigned to this variable

 dataType - the data type of the array/collection

Example 1: Print Array Elements


// print array elements

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);
}
}
}
Run Code
Output

3
9
5
-5
TWO MARKS:

What are the major features of Java programming?


1. Object Oriented. In Java, everything is an Object. ...
2. Platform Independent. ...
3. Simple. ...
4. Secure. ...
5. Architecture-neutral. ...
6. Portable. ...
7. Robust. ...
8. Multithreaded.

Distinguish between the local and instant variables

Instance Variable: These variables are declared within a class but outside a
method, constructor, or block and always get a default value.
 These variables are usually created when we create an object and are
destroyed when the object is destroyed.
 We may use an access specifier, for instance, variable, and if no access
specifier is specified, then the default access specifier is used.
 Each and every object will have its own copy of instance variables.

Local Variable: These variables are declared within a method but do not get
any default value.
 They are usually created when we enter a method or constructor and are
destroyed after exiting the block or when the call returns from the method.
 Its scope is generally limited to a method and its scope starts from the line
they are declared. Their scope usually remains there until the closing
curly brace of the method comes.
 The initialization of the local variable is mandatory.

Define Array and its types of array

What is an array in Java?


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
There are two types of array.
 Single Dimensional Array.
 Multidimensional Array.

. Write the syntax for while statement with an example


public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

Describe for loop with an example.

Example

Following is an example code of the for loop in Java.

public class Test {

public static void main(String args[]) {

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


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

You might also like