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

Java Introduction

Java Programming Question

Uploaded by

rizvihasan931
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Introduction

Java Programming Question

Uploaded by

rizvihasan931
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 116

Introduction to Software

Software is collections of programs such as C , C++ , Java, Python, HTML


and other programs.

Software basically two categories .

Software

System Software Application Software


it interacts with hardware for the purpose of application
components development
Eg:
Device drivers and Operating apps  WhatsApp, FB, Online
systems trading apps, banking apps

Eg:
C, C++, Java, .Net , ERP package
and others

Except Operating Systems, all are


Application software

Operating System:

Q. Can we run any program without OS ?


Ans:=
No

Except BIOS, to run all programs OS required .


BIOS  Basic Input and Output System.
BIOS is a hardware program, it is a chip level program
BIOS is responsible to boot Operating System
Booting is a process of loading OS from Hard Disk to RAM memory.

What is an Operating System ?

It is a platform, where we can run all the application software.

It is an interface between hardware and application software.

Every Operating System has its own libraries to communicate between


Application software and Hardware components.

Every program has to link with OS library before going to run.

Application Software
Front End Software Back End Software
These are to interact with end users, It is Serverside Software
it collects data from end users and
Application 2) Database
stores into backend
Application is to perform serverside /
Eg:
backend transactions
Languages, Packages ERPs
Database used to store and maitain
data
Eg:
Databases and files , HDFS ( Bigdata
storage )

Java is a Server Side Programming ( Application Server ) to Develop


Serverside Application

Front End Software / Backend Software


Languages Packages
It is a Proramming / Coding It is a readmade one, ready to use.
Packages don’t have programming
Eg: MS-Office, ERP packages, Tally
Accounting package
C, C++, JAVA, HTML, .Net
C#
Languages
Low Level Languages High Level Languages
These are machine ( processor ) These are user understandable
understandable languages languages
Eg: These are looks likes English
language
Machine Language (IGL ) and
Easy to understand.
Assembly Language (II GL )
III GL and IV GL are high level
Assembly language in the form of
languages
pneumonic codes
Assembler converts assembly
language into machine language

Software Languages
================

1) Computer Understandable Language

2) User Understandable Language

Computer Understandable Language


============================

that depends on Generation of Computers.

There are five geneartions

I Gen --> Vaccume Tubes based

II Gen --> Transister based


III Gen --> IC based

IV Gen --> Processor based ( present )

V Gen --> AI based ( future ) )

Processor based Computer Understandable Language

it is binary code ( 10011001011 )

it is a System Understandable langauge

System --> processor

AI based computer understandable language, is high level language


English

Software languages are two Categories

1) Low Level Language

2) High Level Language

1) Low Level Language:


==================

it is a System understandable language


it is in the form of binary code ( 11000010010101010 )

System --> Processor

It is a Processor understandable langauge

Processor --> 8085 and 8086

it is called as Machine Language

2) High Level Language:


===================

It is a user understandable language

it is like a English Language

it is very easy to Understand

Eg:
C, C++, Java, Python, HTML, .net C#, Scala..

Q. Which is a 1st Developed high level language ?

C - Language, is first high level language developed by Dennis


Ritchie

in the year 1972.


every High Level Language program has to convert into binary code
( 10100101110 )

High Level Language ---> binary code

Interpreter or Compiler converts from High Level Language to binary code


.

Compliers and interpreters are used to convert form high level languages
into low level language ( processor understandable language )

Difference between compiler and interpreter

S.No Interpreter Compiler


It interprets line by line and
1 Whole program at a time
executes
2 It gives the result line by line It gives whole output at a time
If any error occurs interpreter It checks all statements in the
3 stops program and shows all the errors in
Hence it shows only one error the program.

If no errors in the program, then it


4 It will not generate executable file
generates executable file
It always executes only source
5 It executes exe file
code
These are called as scripting These are called programming
6
languages languages
7 Eg: HTML, PERL, Java Script, Eg;
Python, Shell
C, C++ and .Net C#

Interpreter based languages don’t Every program converts into exe file
8
have exe file concept
Open Source, it can be modified It is not an open source , it is exe
9
any time based , it’s code can not be modified

Java  depends on both Compiler as well interpreter

In Java Errors Checking by the Compiler

If no errors , then Java compiler generates .class file

.class file is a byte code file

Java runtime by the Interpreter

Source Code  Byte Code  Binary Code  Processor  Output

Source Code  Byte Code  java compiler

Byte Code  Binary Code  java interpreter

Source code ( Test.java )  javac ( java compiler )  Byte Code file


(Test.class )  java ( interprter )  Binary Code  processor  Output

Byte code was introduced, to make java program as independent of


platform
Java depending on Both Compiler as well as Interpreter

Java runtime is an Interpreter based.

Any language, runtime is an interpreter based, no exe file.

Since Java runtime is an Interpreter based, No exe file concept in Java.

Q. Can we create exe file in Java

Ans : No

There is no Concept of exe files in Java,

In Java every thing is a .class file.

.class file is not an exe file.

Exe file is binary code file and it is a processor Understandable language

.class file is a byte code file and it is a JVM Understandable Language

Exe file is an OS dependent ,

.class file is an independent of OS

JAVA
Features of Java :
1) It is an independent of platform.

2) It is a portable ( write once run any where ).

3) It is a scalable language.

4) It provides security for local resources.

5) Object Oriented Programming language.

Platform:
Any hardware or software environment in which a program runs is known
as a Platform.
Since Java has its own runtime environment (JRE) and API, it is called
Platform.

JVM is the responsible to make java application as independent of platform


and portable

1) It is an independent of platform
Java application runs any operating system and any Hardware

2) It is a portable ( write once run any where )


Java application can be moved any platform with any changes
to current application

3) It is a scalable language
Easy to use without disturbing the existing java functionality

4) It provides security for local resources.


JVM has Security Manger which is responsible to prevent java application
to access your private information in your PC.
5) Object Oriented Programming language
In java every transaction handled by object, without object we
cannot perform any transactions, hence it is called as Object Oriented
Programing ( OOP ) language.

Difference between Exe file and .class file

Exe file .class file

It is a binary code file It is a byte code file


It is a system understandable It is a JVM understandable
language language
It contains program code + It is a Pure Java program in byte
Software Library + OS library format.
Don’t have any OS library
It contains byte code for java
program + Byte Code for Java
Library
Exe file is a prepared file for .class file is not a prepared file, it
specific OS don’t have any OS library
OS library, statically linking with OS library dynamically linking
exe file with .class file
at run time .
Exe file is already prepared one, .class file is not a prepared file ,
before moving OS after moving on to OS, JVM
prepares as per current OS
Exe file executes faster than .class Since .class file preparing at
file runtime , it executes slowly than
exe file
To run exe file , Application To run .class file, JDK should be
Software not required to install installed on OS.
What is java ?
Java is compile as well as Interpreter based.
Java compiler coverts source code into byte code file
Java Interpreter converts byte code into binary as per the Operating
system and Hardware.

What is an exe file ?


Exe file contains binary code,
It is a file with actual program code, application software library, and OS
library and hardware information
Exe file is OS dependent as it contains OS library
Exe file is prepared file for specific operating system.

Eg:
Any exe file prepared on windows will not execute on Linux and vice versa
Java byte code files not an exe file.

Java Editions:

There are Four Editions in java :

Java SE = Standard Edition


This is the core Java programming platform. It contains all of the libraries
and APIs that any Java programmer should learn (java.lang, java.io,
java.math, java.net, java.util, etc...).

Java EE = Enterprise Edition


It is platform, collection of services. We can develop Web applications
and Enterprise applications.

Java ME = Micro Edition / Mobile Edition


This is the platform for developing applications for mobile devices and
embedded systems such as set-top boxes. Java ME provides a subset of
the functionality of Java SE, but also introduces libraries specific to mobile
devices.

4 Java FX:

JavaFX is a Java library used to build Rich Internet Applications ( IoT,


Internet of Things ) The applications written using this library can run
consistently across multiple platforms. The applications developed using
JavaFX can run on various devices such as Desktop Computers, Mobile
Phones, TVs, Tablets, etc..
JavaFX, Java programmers can now develop GUI applications
effectively with rich content.

JSE Features:

1) Object-oriented programming language.

2) Java supports exception Handling

3) File I/O transactions

4) Collections

5) Strings and String Buffer Handling.

6) JDBC ( Java Data Base Connectivity ) to data base applications.

7) Networking.

8) Multi-threading.
9) Applets for Web applications -- >It was outdated concept.

10) AWT ( Abstract Windowing Tool Kit ) for GUI Applications --> It was
outdated concept.

JEE Features :-

It is a collections Services such as

1) Servlets

2) JSP

3) RMI ( Remote Method Invocation )

4) EJB ( Enterprise Java Beans )

5) Java Mail API

6) Java Message Service

7) Java Naming and Directory Interface ( JNDI )

8) JTA ( Java Transaction API )

9) XML Parser

10) Web Services

11) Restful Services


JEE Provides Below Frameworks

1) Struts Framework

2) Spring Framework

3) Hibernate Framework.

4) Hadoop Frame work

5) Spark Frame work

6) Ignite Frame work

7) Spring Boot and Micro Services

Different Versions of Java.

S.No. Version Code Name Year


1. JDK Alpha and Beta
2. JDK 1.0 Oak
3. JDK 1.1 Oak
4. J2SE 1.2 Playground
5. J2SE 1.3 Kestrel
6. J2SE 1.4 Merlin
7. J2SE 5.0/1.5 Tiger
8. Java SE 6/1.6 Mustang
9. Java SE 7/1.7 Dolphin
10. Java SE 8/1.8 code name culture is
dropped
11 Java SE 9/1.9

JDK Alpha and Beta (1995)


JDK 1.0 (23rd Jan 1996)
JDK 1.1 (19th Feb 1997)
J2SE 1.2 (8th Dec 1998)
J2SE 1.3 (8th May 2000)
J2SE 1.4 (6th Feb 2002)
J2SE 5.0 (30th Sep 2004)
Java SE 6 (11th Dec 2006)
Java SE 7 (28th July 2011)
Java SE 8 (18th Mar 2014)
Java SE 9 (21st Sep 2017)
Java SE 10 (20th Mar 2018)
Java SE 11 (September 2018)
Java SE 12 (March 2019)
Java SE 13 (September 2019)
Java SE 14 (Mar 2020)
Java SE 15 (September 2020)
Java SE 16 (Mar 2021)
Java SE 17 (September 2021)
Java SE 18 (to be released by March 2022)
Since Java SE 8 release, the Oracle corporation follows a pattern in which
every even version is release in March month and an odd version released
in September month.

Java Installation :

Installing Java

Copy JDK1.8 into C-Drive and rigth click run as Administrator  yes 
next next close

Setting Environment Variable for Java

1) JAVA_HOME
2) PATH

Win-10

Right click on This PC Icon  select properties

Select Advanced System settings


Click on Environment variables as below
Goto System variables
variable Name : JAVA_HOME

Variable value : C:\Program Files\Java\jdk1.8.0_121

Setting path :

Goto system variables

Select PATH variable and edit


Select New
Click on OK  OK  OK

Setting Java Path in Linux OS:

$gedit ~/.bashrc
go to end of .bashrc file and provide following PATH

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-i386

export PATH=$PATH: $JAVA_HOME/bin

checking for java installation and version:

How to check value of OS environment Variables at command line

Ans:

set is command

set JAVA_HOME
What is purpose of java PATH setting ?

Ans:

Operating System, to identify the location of Java Software.

Eclipse setup:

Take the eclipse zip ( archive ) and place into C-dirve  rt.click and select
extract here Open Eclipse folder  right click on eclipse icon  send to
desk top  created short cut on desk for eclipse.

On launching eclipse, it check for the JAVA_HOME, then integrates jdk with
eclise.

Working with eclipse:


Eclipse is an IDE

IDE: Integrated Development Environment.

Java Compiler, JRE, JVM are integrated to eclipse automatically, when PATH
variable is defined in the OS.

Steps to Develop Java Project/Application in Eclipse

Create Workspace

Create a Project

Create a Package

Create a Class

Create Methods
Step1:

Create Workspace

Goto Desk top and double click on Eclipse Icon, then Launch eclipse 
Select Work Space location ( browse ) and provide the name , D:\test\
SampleWS

SampleWS  is a workspace name Ok

Close below welcome screen.


Step2:

Create Project
Rt.Click on Project Explorer area  new  project  java project  next
provide project name ( test)
execution environment : JavaSE1.8

Finish
Step3:
Create a package

Expand project  rt.click on src  new  package 


Package name ( lower case ) :
<com/org>.<client_name>.<project_name>.<module_name>

com  Company

org  Organization

Eg:

com.angelprints.ecommerce.inventory

Step4:
Create a class

Rt.click on package  new  class

Provide the class name : Test ( class name should start with upper case
alphabet )
package com.nrit.mnrao.test;

public class Test {

public static void main(String[] args) {

System.out.println("Hello World");

How to run java program

Rt.click on main() program file  runAS  java Applicaton

At Console O/p:

Hello World

Changing font size :

Right click on main program file and select preference as below


Running Project :
How to write sample program in java, using Notepad

Hello World program:

D:\>test> notepad Test.java  windows

//program to display Hello World

/*
Developed On :
Developed By :
Modified On :
Modified By :
Reason to Modify :
Description :

Rights reserverd @ volkswagen


*/

import java.lang.String ;
import java.lang.System ;

public class Test


{
public static void main(String [] args )
{
System.out.println("Hello World");
}
}

Save this file as Test.java

Name of program file should be same as the class name in which main
method is defined.

To compile: D:\test> javac Test.java

Result file : Test.class

To execute: D:\test> java Test

Commenting :

to write description about the program.

// Single line commenting in java

/* multiple lines
commenting
in java
*/

import is a keyword to import java package,


eg:
java.lang, java.io, java.net, java.util, java.math, java.sql

Q. what is a package ?

package is a collection of related classes and interfaces.

All Java packages are from java library .

Q.what is java library ?

ans:

it is a collection of jar files with packages

all java packages are from java library

java library is a collection of java jar file

jar files contains packages

package contains all related classes and interfaces


C-Language Java
Library Library
header file jar files ( packages )
functions classes and iterfaces
#include<stdio.h> import java.lang.*
printf() , scanf() System and String

import java.lang.* ,

Here *  all the classes from that package

Below is an individual import

import java.lang.String ;
import java.lang.System ;

Q. What is the purpose of importing package ?


Ans:

purpose of import is to use pre-defined classes and interfaces

Note :

individual importing is recommended

.*  will import all the classes from the packages ( including un


necessary classes )

Individual import, it will import only required classes.

importing java.lang is an optional, as it is a default available package in


java applications.

Any class, which is from java.lang package , not necessary to import .

class is a keyword is used to define a classes in java.

Test : is name of the class.

How to choose class Name

Naming Conditions

These are as per the java compiler.

Naming Conventions
These are as per the coding standards .

Naming conditions of a class :

These are as per the compiler.

It contains only alphabets (a-z, A-Z ), digits ( 0 – 9 ) and under score ( _ )

Should not be used spaces and special chars, keywords.

Max length can be up to 255 chars

Naming conditions are same for all identifiers

identifiers:
=======

class name,
interface name,
variable name,
object name,
method name

Naming conventions of a class :

These are as per coding standards for easy understanding the code.

1) class name should start with upper case alphabet


2) If class name contains multiple words then every word should start with
upper case alphabets (Camel Case in java naming conventions)
Eg :
ContractEmployee
WeeklySalesReport
MyFirstExample
WordCountExample
ActionEvent, ActionListener

Java follows camel case syntax for naming the class, interface, method
and variable.
public keyword is an access specifier which represents visibility, it means
it is visible to all.
No two classes are public in the same program file.

A class must be public which name is same as the file name

static is a keyword, if we declare any method as static, it is known as


static method. The core advantage of static method is that there is no
need to create object to invoke the static method.

main method is executed by the JVM, so it doesn't require to create object


to invoke the main method. So it saves memory.

main represents start up of the program.

To compile java program, main() is not compulsory but to execute main()


should presented.

Naming conditions of method are same as the class as explained above.

Naming conventions of a method :


1)Name of the method starts with lowercase alphabets

2) if name contains multiple words, then first word starts with lowercase
and next words starts with uppercase alphabet

e.g.
getData(), setData(), getEmpInformation()
actionPerformed(), firstName(),
setEmpDeptName()
getDatabaseConnection()
actionPerformed()
getRateOfInterest()
getMinRateOfInterest()
getMaxRateOfInterest()

main() can be compiled without static but can not execute

main() can be compiler without public but can not execute

main() with private access specifier can be compled but can not execute

main() can be compiled with any access specifier but to execute it should
be public
void is the return type of the method, it means it doesn't return any
value.

main() can be compiled with any return type but to execute return should
be void.
if don't have String [] args, the it will be treated as user define method ,
not JVM main()
as pepr JVM. main() syntax should be as below
public static void main(String [] args);

String[] args is used for command line argument. We will learn it later.

System.out.println () is used print statement.

print() and println ()

println () inserts a new line char at the end of the data, where as print()
does not.

print()  to display output on the same line

println() will take output to next line

System: it is a class from java.lang package

It provides three objects

in  System.in : to read data from input buffer / keyboard


out  System.out : to write data to outpt buffer / screen
err  System.err : to Write JVM implicit error message to output buffer

A program file can have multiple classes but only one class must be public

A class must be public, which name is same as file name.

public class name and file name should be same.


Recommended code , only one class is recommended in a program file.

In the following program which main() executes ?

Program file is Test.java

class Sample
{
public static void main(String [] args )
{
System.out.println("Hello NRIT");
}
}

public class Test


{
public static void main(String [] args )
{
System.out.println("Hello World");
}
}

Ans : Test class main()

o/p: Hello World


JVM looks for the main(), in a class which name is same as the file name. (
It is a mapping between file name and class name )

Why public class name , should be same as file name ?

Ans:

JVM to identify the location of main()

Q. Can I compile empty .java file ?

Yes , an empty .java program file can be compiled but does not
generate .class file

Naming conditions are same for all identifiers .

Naming convention are as below.


Name Conventions
1) class name should start with uppercase alphabet

2) if class name contains multiple words, then every word


should start with uppercase alphabet
class name

eg:
ContractEmployee, ReserveBankOfIndia,
MonthlySalesReport
interface
Same as class name
name
1) name should start with lower case alphabet
2) if name contains multiple words, then first word is a lower
method name
case and next coming words start with upper case

variable name Same as method name


Same as method name
Object name
And Object name should be same as class name

package should be in lowercase letter e.g. java, lang, sql, util etc.
name com.sritech.mnrao.test
constants should be in uppercase letter. e.g. RED, YELLOW,
name MAX_PRIORITY etc.

What happens at runtime?


At runtime, following steps are performed:
JVM performs following:

Test.java --> javac --> Test.class --> JVM

Overview of JVM

Internal Architecture, covered at the end of this Document.

Highlevel Architecture :
Class Loader : Loading .class file into memory

Byte code verifier :


Byte code Verification
When a class loader presents the byte codes of a newly loaded Java
platform class to the virtual machine, these byte codes are first inspected
by a verifier. The verifier checks that the instructions cannot perform
actions that are obviously damaging. All classes except for system classes
are verified.
Here are some of the checks that the verifier carries out:
Variables are initialized before they are used.
Method calls match the types of object references.
Rules for accessing private data and methods are not violated.
Local variable accesses fall within the runtime stack.
The runtime stack does not overflow.

Interpreter :
It coverts java byte code to binary code and prepares as per the current
platform (Hardware ) runtime environment.
JIT :

Just-In-Time (JIT) compiler is a component of the Java Runtime


Environment that improves the performance of Java applications at run
time

The JIT compiler helps improve the performance of Java programs by


converting byte code into native machine code at run time.
Garbage Collector :
Garbage collector is a daemon thread. CPU is responsible to call Garbage
collector. If there are no threads running in the system, then CPU makes a
call to Garbage collector.
Java provides facitlity to Java developer for invoking Grabage collector
through Runtime.gc() / System.gc()
Task of Garbage Collector is to clear all un-used obejcts ( Garbage
objects )
Unreferenced objects are called as Garbage objects.
Thread Schedular:
Thread schedular is to manage different states of thread in a multi
threaded application.
Security Managar:
Security Managar is to provide the security for local system resources
from Java Application.

Interview Questions:

1) What is operating system ?

Ans:
It is a platform, where we can execute application programs and
It is an interface between Hardware and Application software.

2) What is an exe file ?

Ans:
exe file is a prepared file for specific OS. It contains binary code.
exe file contains, prog
ram code, application software libraries, OS libraries and hardware
information
exe file is a OS dependent.
3) can we create exe file in java ?

Ans :
No we can't create exe file. In java every thing is .class file, it is not
an exe file

4) What is a .class file ?

Ans;
.class file is byte code file, which contains only java program code
and Java libraries.
It don’t have any OS library and it is independent of platform

5) how java program file is an independent of platform ?

Ans;
it is independent of Platform since it does not contain any OS
libraries and Hardware information.
Since Java .class file dynamically linking OS library by the JVM , it is
an independent

6) What is difference between exe file and .class file ?

Ans:
exe file contains binary code and .class file contains byte code
exe file is prepared file for specific OS and .class is not prepared file.
After moving .class file to OS, then preparation starts as per current
OS.
Exe file contains OS library but .class file don’t have any OS Library

7) what if the difference between JDK, JRE and JVM


Ans:

JVM (Java Virtual Machine)


It is an abstract machine. It is a specification that provides runtime
environment in which java byte code can be executed.

JVM, JRE and JDK are platform dependent because configuration of each
OS differs.
But, Java is platform independent.

JDK ( Java Development Kit ):

It contains JRE + Development Tools ( javac, java, javap, javadoc, jar,


appletviewer, rmic, jps and etc )

JRE ( Java Runtime Environment )

It is used to provide runtime environment.


It is the implementation of JVM.
It contains set of libraries ( jar files ) and other files that JVM uses at
runtime.
JRE = JVM + Java Packages Classes (like util, math, lang, awt,swing etc)
+runtime libraries ( jars ).

JDK
Development Tools
JRE javac, java, javap, javadoc, jar,
appletviewer, rmic, jps and etc )
Java
Packages
JVM
Classes
( Library )

The JVM performs following main tasks:

Loads code
Verifies code
Executes code
Provides runtime environment

8) What is the purpose of JIT Compiler ?

Ans:
Just-In-Time (JIT) compiler is a feature of the run-time interpreter.
It prepares the binary code ( generated by Interpreter ) as per the
current OS Specifications.

9) Can we compile java program without main() ?

Ans: yes.

10) Can we execute java program without main() ?


Ans: No

11) what does mean, Java is portable ?

Ans:
java application build can be moved from one OS to another OS with
out any changes in the application build .

12) - Can we have multiple classes in same java program file?

Ans : Yes

13) Can we have two public classes in one java file?

Ans:
No
A class must be public which name is same as File name.

14) What is correct syntax for main method as per JVM?

A - public static int main(String[] args)

B - public int main(String[] args)

C - public static void main(String[] args)

D - None of the above.


Ans: C

15) Is an empty .java file a valid source file?


Ans:

No, not valid valid file but it can be compiled.

A Java-source file with zero class-declarations will not result in any .class
files

Data Types in Java

In java, there are two types of data types

Primitive data types ( basic data types / System defiend )

System defined data types

System --> compiler

these are from the compiler

these are also called as pre-defined, fundamental types, basic data


types
Non-primitive data types

These are user defined data types


all java classes ( OOP )
Data Type Default Value size Range of data
boolean
false 1 bit 1 ( true) or 0 ( false)

-128 to 127, -27 to


byte 0 1 byte
(27 - 1)
-32,768 to 32,767 , -215 to
short 0 2 byte
(215 - 1)

int 0 4 byte -231 to (231 - 1)

long 0L 8 byte -263 to (263 - 1)

float 0.0f 4 byte 7 significant decimal digits

double 0.0d 8 byte 15 significant decimal digits

char '\u00000' 2 byte 0 to 65535 ( unsigned char)

Why char uses 2 bytes in java and what is \u0000 ?

Java char is a unicode character. It is because java uses Unicode system


than ASCII code system.
ASCII code system accepts only ASCII chars key board set( 0 to 255 ) .
Unicode system accepts any key board set across universe.
Size of ASCII char is one byte.
Size of unicode char is two bytes.

Java is a net based product, to accept all keyboard sets across the
universe it is designed with 2 bytes.

Char with 2 bytes can accept the value ranging from 0 to 65535 ( many
keyboard sets )

1 byte = 8 bits

1 KB  ( 103 ) = 1024 bytes

1 MB  ( 106 ) = 1024 KB

1 GB  ( 109) = 1024 MB

1 TB  ( 1012) = 1024 GB

1 PB  ( 1015 ) = 1024 TB

1 EB  ( 1018 ) = 1024 PB

1 ZB  ( 1021 ) = 1024 EB

TB to ZB  is a Big Data.
Hadoop is frame work to store and Process Bigdata.

There are two modules in Hadoop

1) HDFS --> it is file system

to store bigdata

using as backend

2) MapReduce --> java programs

to process data

using like a front end

Storage of Data in memory

Numeric to Binary Conversion

byte b = 10;
2 10
2 5 -- 0
2 2 -- 1
2 1 -- 0
0 -- 1
1010

Numbers are siged type

Last bit is reserved for sign and other bits for data.

b ( size of b = 1 byte = 8 bits as below ) first bit

0 0 0 0 1 0 1 0

Last bit is for sign


 +ve
 -ve

Binary to numeric format conversion

b ( size of b = 1 byte = 8 bits as below ) first bit


26 25 24 23 22 21 20
0 0 0 0 1 0 1 0

Last bit is for sign


 +ve
 -ve

0*26 + 0*25 + 0*24 +1*23 +0*22 + 1*21 + 0*20


0 + 0 + 0 + 8 + 0 + 2
+ 0 = 10

If all data bits are 1’s , then it is a max value

b ( size of b = 1 byte = 8 bits as below ) first bit


26 25 24 23 22 21 20
0 1 1 1 1 1 1 1

Last bit is for sign


 +ve
 -ve

1 + 2 + 4 + 8 + 16 + 32 + 64 = 127

1 byte max value = 127

2 bytes of memory first bit


27 26 25 24 23 22 21 20
1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
214 213 212 211 210 29
28
Last bit is for sign
 +ve
 -ve

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024 + 2048 + 4096


+ 8192 + 16384 = 32767

bytes max value = 32767

4 bytes of memory
first bit
27 26 25 24 23 22 21
20
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
0 1 1 1 1 1 1 1
214 213 212 211 210 29
28
Last bit is for sign

1 byte max value = 127

2 bytes max value = 32,767


Character type
===========
Why char uses 2 bytes in java and what is \u0000 ?

size of the char = 2 bytes , why ?

why size of the char is 2 bytes in Java ?

there are two types of characters

1) ASCII char --> American Standard Code for Information and Interchange

size of ASCII char = 1 byte

2) Unicode --> Universally Accepted Code

size of Unicode char = 2 bytes

character is an unsigned type ( there is no sign for character )

ASCII char = 1 byte


unsigned 1 byte , what is the min value.

First bit

0 0 0 0 0 0 0 0

Last bit, is also for data ( there is no sign )


In Unsigned type , there is no sign, all bits used for data only.
If all bits are 0’s
First bit

0 0 0 0 0 0 0 0

Last bit is also for data


If all bits are 0’s then it is a min value = 0
unsigned 1 byte , what is the max value.

First bit
27 26 25 24 23 22 21 20
1 1 1 1 1 1 1 1

Last bit is also for data


If all bits are 1’s then it is a max value = 255

1*27+ 1*26+ 1* 25 + 1* 24 +1* 23 +1* 22 +1* 21 +1*


20
128 + 64 + 32 + 16 + 8 +4 + 2 + 1= 255

Unsigned 1 byte Range = 0 to 255


ASCII char Range = 0 to 255

What is ASCII value ?


On key board for every key some integer number given to convert from
char to binary format .
That number is an ASCII value.
ASCII value is ranging from 0 to 255
All keys ASCII value between 0 to 255 only
Eg:
A-Z  65 to 90
a-z  97 to 122
0-9  48 to 57

Why Uncode Char introduced in Java ?

Java is net based product, Java app works on the Internet.

If character type is ASCII char it can support char ranging from 0 to 255
only

ASCII chars only ( USA, English )  ASCII key board.

If char size is only 1 byte it supports only USA, English key board , not
other keyboard sets.

ASCII keyboard set Registered from 0 to 255 chars.

Any key board set released in the future that should be started from 256.

Sun Micro systems has developed standard for every keyboard with max
only 256 keys and same thing was Registered.

If it is ASCII char , it can take only USA, English , it does not accept other
keyboard sets.
0 to 255  Registered for USA, English.

To accommodate other keyboard sets also char designed with 2 bytes .

Char with 2 bytes of memory called as Unicode char ( Universally


accepted code )

Unsigned 2 bytes what is max value ?


2 bytes
20
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
215

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024 + 2048 + 4096


+ 8192 + 16384 + 32768 = 65535
Unsigned 2 bytes max value = 65535.
It’s Range = 0 to 65,535.

If size of the char is 1 byte it can take only USA, English.

If size of the char is 2 bytes , it can take many keyboard sets across the
world wide.
To support different languages in the Universe char designed with 2 bytes.

Size of Unicode char = 2 bytes , it’s max value = 65,535

Size of each key board = 256 keys

No of keyboard sets supporting by Unicode char = 65536/256 = 256

No of langauges that can be used with Unicode char = 256

To support different languages in the Universe char designed as 2 bytes.

If java application implemented i18n concept , it supports all regional


languages in the world
i18n = Internationalization
i18n is a char mapping between English and other language.
Program to display size and Range of Values.

public class Test


{
public static void main(String [] args)
{
System.out.println ("character size :"+Character.SIZE+"\tMin
Value : "+Character.MIN_VALUE+"\tMax Value : "+Character.MAX_VALUE);

System.out.println ("byte size :"+Byte.SIZE+"\tMin Value :


"+Byte.MIN_VALUE+"\tMax Value : "+Byte.MAX_VALUE);

System.out.println ("short size :"+Short.SIZE+"\tMin Value :


"+Short.MIN_VALUE+"\tMax Value : "+Short.MAX_VALUE);

System.out.println ("int size :"+Integer.SIZE+"\tMin Value :


"+Integer.MIN_VALUE+"\tMax Value : "+Integer.MAX_VALUE);

System.out.println ("long size :"+Long.SIZE+"\tMin Value :


"+Long.MIN_VALUE+"\tMax Value : "+Long.MAX_VALUE);

System.out.println ("float size :"+Float.SIZE+"\tMin Value :


"+Float.MIN_VALUE+"\tMax Value : "+Float.MAX_VALUE);

System.out.println ("double size :"+Double.SIZE+"\tMin


Value : "+Double.MIN_VALUE+"\tMax Value : "+Double.MAX_VALUE);
}
}

O/P:

Variable :

What is variable ?

it is a name given to some location in the program memory

it's value changes at runtime.

it is a temporary memory , it clears automatically once program stopped

it is an identifier

variable naming :
============;

how to choose name of the variable

1) Naming Conditions

2) Naming Conventions

1) Naming Conditions

These are as per the compiler.

It contains only alphabets (a-z, A-Z ), digits ( 0 – 9 ) and under score ( _ )

Should not be used spaces and special chars, keywords.

Max length can be up to 255 chars

Naming conditions are same for all identifiers

identifiers:
=========

class name,
interface name,
variable name,
object name,
method name
2) Naming Conventions

These are different for different indentiers

Varaibale name conventions

1) variable name should start with lower case alphabet

2) if variable contains multiple words , then

1st word start with lowercase , and next word start with upper case
alphabet

Eg:
empDeptName;

empSalary;

Declaration of a variable.

data_type variable_name;

eg :
int empNum;

String empName;

double empSalary;
String empDeptName;

String empGender;

int empAge

Assigning values to variables:

empNum = 1001;

empName = "mnrao";

empSalary = 50505.50;

empDeptName ="it";

empGender = "male";

empAge = 35;
Memory Management by JVM

JVM will split the memory into different parts as below

Higher Order Memory

Stack Memory

Shared Memory

Heap Memory

Static Memory

Global Memory

Text Area

Method Area
Higher order memory space :
To store all command line paramters and OS environment variable.

Stack Memory space :


To store all local variables.
Memory allocation is LIFO ( last In First Out ) based.
This memory space grows automatically as long as sharable memory
available for it
If stack filled it raises stack over flow exception.

Shared Memory space:

This memory can be shared by both stack and heap.

Heap Memory space:


This memory space is for dynamic memory management.
In this area, memory allocation and de-allocating is always at
runtime.
In heap memory space, memory allocation is randomly
This memory space grows automatically as long as sharable memory
available for it.

Global Memory space:


This memory space is to store global variables. as per the no of global
variables declaration in Java-Application.

Static Memory space:


This memory is to store the static variables. It’s size is a fixed one as per
the no of static variables declaration in Java -Application.

Text Memory Space:


This memory contains all Java-Program instructions, Java-Libraries
Stack Memory for the below Program

Stack Memory space :


To store all local variables.
Memory allocation is LIFO ( last In First Out ) based.
This memory space grows automatically as long as sharable memory
available for it
If stack filled it raises StackOverFlowException.

public class Test {

public static void main(String[] args) { Stack

// declaring variables

int empNum;

String empName;

empAge
35
double empSalary;

male
String empDeptName;

it
String empGender;

int empAge;
50505.50

// assigning values to variables


mnrao

empNum = 1001;

1001
empName = "mnrao";

empSalary = 50505.50;

empDeptName ="it";

empGender = "male";

empAge = 35;

System.out.println(empNum);

System.out.println(empName);

System.out.println(empSalary);
System.out.println(empDeptName);

System.out.println(empGender);

System.out.println(empAge);

}
}

Once control come out of main method, stack becomes empty ( all
varaibles clears from stack )

Initialization of variables:

It is an assigning values at the time of declaration

int empNum = 1001;

String empName = "mnrao";

double empSalary = 50505.50;

String empDeptName = "admin";

String empGender = "male";

int empAge = 35 ;
program for initialization

public class Test {

public static void main(String[] args) {

int empNum = 1001;

String empName = "mnrao";

double empSalary = 50505.50;

String empDeptName = "admin";

String empGender = "male";

int empAge = 35 ;

System.out.println(empNum);

System.out.println(empName);

System.out.println(empSalary);

System.out.println(empDeptName);

System.out.println(empGender);
System.out.println(empAge);

}
}

Changing value of varaibles :

package com.durga.mnrao.abc;
Stack
public class Test {

public static void main(String[] args) {

int empNum = 1001;

String empName = "mnrao";


30

double empSalary = 50505.50; empAge

female
String empDeptName = "admin"; empGender

sales
String empGender = "male"; empDeptName

60607.60
int empAge = 35 ;

System.out.println("initial values are "); scott

System.out.println(empNum);
1002
System.out.println(empName);

System.out.println(empSalary);

System.out.println(empDeptName);

System.out.println(empGender);

System.out.println(empAge);

// changing values

empNum = 1002;

empName = "scott";

empSalary = 60607.60;

empDeptName = "sales";

empGender = "female";

empAge = 30;

System.out.println("after changing value are ");

System.out.println(empNum);

System.out.println(empName);
System.out.println(empSalary);

System.out.println(empDeptName);

System.out.println(empGender);

System.out.println(empAge);

}
}

Every time of chaning value, Same location but value overwrites .

initial values are


1001
mnrao
50505.5
admin
male
35

after changing value are


1002
scott
60607.6
sales
female
30
Mutiple Variables displaying in a single statement :

+ is used for concatenation of text and variables.

+  concatenation operator

Concatenation means joining .

+  if both operands are integers , then it is addition

a+b

atleast one operand is a string, then it is a concatenation

concatenation --> joining together ( placing side by side )

package com.durga.mnrao.test;

public class Test {

public static void main(String[] args) {

// initialization of variables

int empNum = 1001;


String empName = "mnrao";

double empSalary = 50505.50;

String empDeptName = "admin";

String empGender = "male";

int empAge = 35 ;

System.out.println("initial values are ");

System.out.println("emp num = " + empNum + "\t name = "


+ empName + "\t salary = " + empSalary + "\t dept = " + empDeptName
+ "\t gender = " + empGender + "\t age = " + empAge);

// changing values , assignment .

empNum = 1002;

empName = "scott";

empSalary = 60607.60;

empDeptName = "sales";

empGender = "female";

empAge = 30;
System.out.println("after changing value are ");

System.out.println("emp num = " + empNum + "\t name = "


+ empName + "\t salary = " + empSalary + "\t dept = " + empDeptName
+ "\t gender = " + empGender + "\t age = " + empAge);

}
}

Dynamic initialization of a variable:

int a =10; // compile time initialization

int b =20; // compile time initialization

// below is the dynamic initialization

int c = a*b;

Programm to swap the two variables:

public class Test {


public static void main(String[] args) { a b
temp

int a = 10; 20 20 10

int b = 20;

System.out.println ("Before swapping");

System.out.println ("a=" + a + "\tb=" + b);

int temp = a;

a = b;

b = temp;

System.out.println ("After swapping");

System.out.println ("a=" + a + "\tb=" + b);

}
}

Before swapping
a=10 b=20
After swapping
a=20 b=10
==============
Reading data from keyboard

There are many ways to read data from the keyboard. For example:

Scanner
InputStreamReader
Console
DataInputStream etc.
BufferedReader

At this stage, we can focus only on Scanner and others will be discussed in
I/O streams.

Java Scanner class:

it is a class from java.util package:

The Java Scanner class breaks the input into tokens using a delimiter that
is whitespace by default.
It provides many methods to read and parse various primitive values.

Methods of Scanner class


Method Description
public String next() It returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and
returns the value as a string.
public byte nextByte() it scans the next token as a byte ( max 127)
public short nextShort() it scans the next token as a short value ( max 32767 )
public int nextInt() it scans the next token as an int value ( upto 8 digits )
public long nextLong() it scans the next token as a long value. ( upto 12 digits )
public float nextFloat() it scans the next token as a float value. ( small real
number )
public double nextDouble() it scans the next token as a double value. ( big real
number )
public boolean nextBoolean() Reading true / false

All methods will read data upto next token ( space or tab or \n, which is
coming fisrt), except , nextLine()

nextLine() : it will read input data upto eneter key including space and tab.
It will read any type of data.

next() : It will read input data up to space or tab or new line char, which
is coming first. It will read any type of data.

All methods, except nextLine() and next(), can read only numeric data.
Program to read different type of data from keyboard

import java.util.Scanner;

public class Test {

public static void main( String [] args) {

Scanner sc = new Scanner( System.in );

System.out.println("Enter byte value ");

byte b = sc.nextByte();

System.out.println("byte variable b = "+b);

System.out.println("Enter short value ");

short s = sc.nextShort();

System.out.println("Short variable s = "+s);

System.out.println("Enter int value ");

int i = sc.nextInt();
System.out.println("int varible i = "+i);

System.out.println("enter long value ");

long l = sc.nextLong();

System.out.println("long variable l = "+l);

System.out.println("enter real number ");

float f = sc.nextFloat();

System.out.println(" float variable f = "+f);

System.out.println("enter big real number ");

double d = sc.nextDouble();

System.out.println("double variable d = "+d);

System.out.println("Enter a String ");

String str = sc.next();

System.out.println("String value = "+str);


System.out.println("Enter boolean value ");

boolean flag = sc.nextBoolean();

System.out.println("boolean variable flag = "+flag);

sc.close();

Program to read employee information

Eg:

package com.durga.mnrao.xyz;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner( System.in );

System.out.println("Enter emp details ");


System.out.println("Enter emp number ");

int empNum = sc.nextInt();

System.out.println("enter emp name ");

String empName = sc.next();

System.out.println("Enter emp salary ");

double empSalary = sc.nextDouble();

System.out.println("enter emp dept name " );

String empDeptName = sc.next();

System.out.println("enter emp Gender ");

String empGender = sc.next();

System.out.println("Enter emp age : ");

int empAge = sc.nextInt();


System.out.println(empNum+"\t"+empName+"\
t"+empSalary+"\t"+empDeptName+"\t"+empGender+"\t"+empAge);

}
}

Enter emp details

Enter emp number


101
enter emp name
vijaya
Enter emp salary
54376.40
enter emp dept name
IT
enter emp Gender
female
Enter emp age :
22
101 vijaya54376.4 IT female 22

Type Casting:

It is a process of converting one data type to another data type

These are of two types


1) premitive data types casting ( basic to basic )

2) Non-Premitive casting ( user defined classes )

primitive data types casting

these are of two types

1) Implicit Casting and 2) Explicit casting

1) Implicit Casting

Implicit means internally ( automatically )

Implicit casting is available for the below

Small size to bigsize

Integer to real number

Small size to bigsize :

eg1:
byte b=10;
short s = b ; --> valid
eg2:
int a=10;
long b=a; --> valid
eg3:
float a=10.5f;
double b=a; --> valid

Integer to real number :

Eg:
int i = 100;

float f = i ;

eg:

int a = 1000;

double d = a;

data and type promotion as below.

byte ===> short ===> int ===> long ==>float ===> double

char ==> int ==>long==>float ===> double


2) Explicit casting:

It is reverse of implicit casting

Java developer has to convert explicitly .

it is required for below one

1) big type to Small type

2) real number type to Integer type

1) big type to Small type

eg1:
short s = 10;

byte b = (byte) s;

eg2:
int i = 100;

short s = (short )i;

eg3:
double d = 10.5;
float f = (float) d;

Eg:
short a=10;
byte b = a; --> invalid, since size of variable “ a” is 2 bytes , which
is more than size of variable “b” ( 1 byte )

such of kind of scenarios, we use explicit type casting.

short a=10;

byte b = (byte ) a ; --> it is valid

same scenario with following data

short a=130;

byte b = (byte ) a ; --> it compiles but at run time loss of data. It results in
unexpected data ( i.e leads to bugs )

here value of b is -126 .

hence explicit type casting is recommended is only for constants,


not for variables.

2) real number type to Integer type

double d = 10.5;
int i = (int) d;

long l = (long) d ;

float f= 10.5 ; --> invalid, since in java real numbers by default treats as
double.

float f = (float ) 10.5; // valid

(or)

float f = 10.5f; // valid

default data type.

Real numbers are by default treated as double type.

Integer numbers are by default treated as int type.

Result of mathematical expressions, with different data types.

1) byte + byte = int


2) short + short = int
3) int + int = int ( compiles ) but at runtime there is chance of data
over flow.
Recommended one is ( int+int = long )
4) long + long = long
5) char + char = int.
6) float + float = double
7) double + double = double
8) int + long = long
9) float + double = double
10) int + float = float

Division ( / ) operation:

int a =10;

float x = a / 3 ;

result value is  3.0

reason  in division, both operands are int type then result int.
to get real number, at leat one operand must be float / double

int a =10;

float x = a / 3f ;

result is  3.3333333
eg:

int a =10;

int b = 3;

float x = a / b ;

result value is  3.0

reason  in division, both operands are int type then result int.

solution for the above is, type casting .

float x = (float) a / b ;

(or)

float x = a / (float) b ;
Java Operators

Based on no of operands, Operators are three categoires

1) Unary Operators  Single Operand

2) Binary Operators  Two Operands

3) Ternary Operators  Three Operands

Binary Operators:

1) Arithmetic / Mathematical Operators

2) Relational Operators

3) Logical Operators
4) Assignment Operator

5) short hand assignment Operator

6) Bitwise operators

Arithmetic / Mathematical Operators

Operator Task
+ Addition
- Subtraction
* Multiplication
/ Division
% Modula’s
( remainder )
Eg:

10 % 3 =1
3%10 = 3
9%10 = 9
50%51=50

Relational Operators:
Operator Task
> Greater than
>= Greater than or equal
to
< Less than
<= Less than or equals to
== Is equal to
!= Not equal to

== --> comparison
= --> assignment.

These operators are to compare the values and returns either true or
false ( Boolean values )

Eg:
int a = 10;

int b = 5;

boolean res = a>b;

here  res value is true

Logical Operators:
Operator Task
&& And
|| Or
! Not

Using ( && ) operator:

Condition1 Operator Condition2 Result


TRUE && TRUE TRUE
TRUE && FALSE FALSE
FALSE && TRUE FALSE
FALSE && FALSE FALSE

Using ( | | ) operator:

Condition1 Operator Condition2 Result


TRUE || TRUE TRUE
TRUE || FALSE TRUE
FALSE || TRUE TRUE
FALSE || FALSE FALSE

Using not ( ! ): it is a negation

! TRUE --> FALSE

! FALSE --> TRUE

program to add, subtract and multiply two numbers.


import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("enter 1st number ");

int a = sc.nextInt();

System.out.println("enter 2nd number ");

int b = sc.nextInt();

int c = a + b;

System.out.println("addition = "+c);

c = a - b;

System.out.println("subtraction = "+c);

c = a * b;
System.out.println("Multiplication = "+c);

Short hand assignment Operators :

int a = 10;

a = a + 5; --> a +=5 ;

a = a - 5; --> a -=5;

a = a * 5; -->a *= 5;

a = a / 5 ; --> a/=5;

Unary Operator:

It works with only one operand.

1) Unary Minus ( - )
2) Increment Operator ( ++ )

3) Decrement Operator ( -- )

Unary Minus:

Eg:
int a=10;

int b = - a; ( unary minus )

here value of b is -10, value of a remains same ( 10 ) no change

int c = a – b ; ( binary minus )

Increment and decrement operators :

Increment Operator ( ++ ) :

It increases value of it's operand by 1.

Decrement operator ( - - ):

It decreases value of it's operand by 1.

Increment Operator ( ++ ) :
Pre – increment Post – increment

1) syntax : 1) syntax :
++ variable; variable++;

2)It increase value of it's Operand by 1 2)It increase value of it's Operand by 1 after
before executing statement executing statement

3) eg : 3) eg :
int a=10; int a=10;
int b = ++a: --> a=11, int b = a++: -->b=10, a=11
b=11

public class Test


{
public static void main(String[] args)
{

int a=10;

int b;

int c;

int d;

b=++a;
c=b++;

d=++c;

System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}

O/p : 11 12 12 12

public class Test{


public static void main(String[] args){
int a=10;
int b;
int c;
int d;

b=a++;
c=++b;
d=c++;
b=d++;
a=++c;
System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}

O/P : 13 11 13 12
public class Test {
public static void main(String[] args)
{
int a=10;
int b;
int c;
int d;

d=++a;
b=d++;
a=++b;
c=d++;
d=++c;

System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}
O/P :
12 12 13 13

Decrement Operator ( - - ) :

Pre – Decrement Post – Decrement


1) syntax : 1) syntax :
-- variable; variable--;

2)It decreases value of it's Operand by 2)It decreases value of it's Operand
1 before executing statement by 1 after executing statement
3) eg : 3) eg :
int a=10; int a=10;
int b = --a: --> a=9, b=9 int b = a--: -->b=10, a=9

public class Test


{
public static void main(String[] args)
{
int a=10;
int b;
int c;
int d;

b=--a;
c=b++;
d=--c;
a=++b;
d=a--;

System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}

O/P :
10 11 8 11

public class Test


{
public static void main(String[] args)
{
int a = 10;
int b;
int c;
int d;

d = a--;
b = ++d;
c = a++;
a = --b;
d = c++;

System.out.println (a + "\t" + b + "\t" + c + "\t" + d);


}
}
O/p :

10 10 10 9

You might also like