Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java programming for interview, Study notes of Java Programming

"Explore the world of Java programming with this comprehensive guide, designed for both beginners and seasoned developers. This book begins with the fundamentals of Java, including variables, data types, loops, and conditionals, and gradually delves into more complex topics like object-oriented programming (OOP), exception handling, and file I/O. You’ll also learn to work with collections, streams, and multithreading, preparing you for real-world programming challenges. With step-by-step explanations, hands-on exercises, and practical examples, this book makes learning Java engaging and effective. Whether you're pursuing Java certification, building web applications, or enhancing your coding skills, this book provides all the tools you need. Discover best practices, explore advanced features, and master Java for building powerful, reliable software." This keeps the focus on key learning areas while being concise and engaging.

Typology: Study notes

2024/2025

Uploaded on 10/17/2024

harshavardini-thota
harshavardini-thota 🇮🇳

1 document

1 / 390

Toggle sidebar

Related documents


Partial preview of the text

Download Java programming for interview and more Study notes Java Programming in PDF only on Docsity!

Last modification date :- 24 th^ Nov 2015 [new version don’t prefer old copy]

Always believe practical knowledge but not theoretical.

Core java syllabus

1. Introduction 6- Basics of java First application 2. Java class 26- Variables Methods Constructors Instance blocks Static blocks 3. Flow control statements & operators 67- If,if-else,else-if,switch For,while,do-while 4. Oops 79- Class Object Inheritance Polymorphism Abstraction Encapsulation 5. Packages 132- Predefined packages User defined packages Importing packages Project modules Source file declaration 6. Modifiers Public , private , protected ,abstract,final,static,native,strictfp,volatile,transient,synchronized, (11 modifiers ) 7. Interface 143- Interface declarations Marker interface Adaptor classes Interface vs inheritance 8. String manipulations 157- String StringBuffer StringBuilder StringTokenizer 9. Wrapper class171 - Data types vs Wrapper classes All 8 wrapper classes explanations Auto boxing vsAutounboxing All possible conversions toStirng() , parseXXX(),valueOf(), XXXValue().

10. java.io package 177- introduction character Oriented Streams Byte oriented stream Writing and reading operations on file. Normal streams vs Buffered streams. File class Serialization Deserialization 11. Exception handling 184- Types of Exceptions Exception vs Error Try-catch blocks usage Finally block usage Throw keyword usage Throws keyword usage Different types of Exceptions and error 12. Multithreading 211 - Thread info Single Threaded model vs multithreaded model Main Thread vs user Thread Creation of user defined Thread Life cycle stages of Thread Thread naming Thread priority Thread synchronization Inter Thread communication Hook Thread Daemon Thread Difference between wait() notify() naifyAll() 13. Nested classes /Inner classes 229- Introduction Advantages of Inner classes Normal Inner classes Method local inner classes Anonymous inner classes Static nested classes 14. Annotations 242- Introduction Advantages of annotations Different annotations working

15. Enumeration 249- Introduction Advantages of enumeration Enum vs enum Difference between enum vs class 16. Generics. 252- 311 Type safety. 17. Collection framework 252- Introduction about Arrays Advantages of collection over arrays Collection vs Collections Key interfaces of Collections Characteristics of Collection framework classes Information about cursors Introduction about Map interface List interface implementation classes Set interface implementation classes Map interface implementation classes Comparable vs comparator Sorting mechanisms of Collection objects 18. N etworking 312- 316 Introduction Socket and ServerSocket URL info Client-Server programming **_19. Applet in java 317-

  1. AWT(Abstract Window Tool Kit) 317-_** Introduction Frame class Different layouts Components of AW T(TextField,RadioButton,Checkbox….etc) Event Handling or Event delegation Model Different types of Listeners 21. Swings341- Difference between Awt and swings Advantages of swings Different components of Swings(TextField,RadioButton,Checkbox….etc) Event handling in Swings

22. INTERNATIONALIZATION (I18N) 347-

Design application to support dif country languages Local class ResourceBundle Date in different formats Info about properties file

23. JVM architecture 358- What is JVM Structure of the JVM Components of JVM 24. Arrays 362- Introduction Declaration of Arrays Arrays storing Object data & primitive data. **_25. Interview Questions 371-

  1. Practice examples 389-
  2. Assertions
  3. Regular Expressions._**

JAVA introduction:- Author : James Gosling Vendor : Sun Micro System(which has since merged into Oracle Corporation) Project name : Green Project Type : open source & free software Initial Name : OAK language Present Name : java Extensions : .java & .class & .jar Initial version : jdk 1.0 (java development kit) Present version : java 8 2014 Operating System : multi Operating System Implementation Lang : c, cpp…… Symbol : coffee cup with saucer Objective : To develop web applications SUN : Stanford Universally Network Slogan/Motto : WORA(write once run anywhere)

Importance of core java:-

According to the SUN 3 billion devices run on the java language only.

  1. Java is used to develop Desktop Applications such as MediaPlayer,Antivirus etc.
  2. Java is Used to Develop Web Applications such as sravyajobs.com, irctc.co.in etc.
  3. Java is Used to Develop Enterprise Application such as Banking applications.
  4. Java is Used to Develop Mobile Applications.
  5. Java is Used to Develop Embedded System.
  6. Java is Used to Develop SmartCards.
  7. Java is Used to Develop Robotics.
  8. Java is used to Develop Games ……………………….. etc.

Technologies Depends on Core java:-

Adv java

structs

hibernate

spring

Selenium

Android

Cloud computing

ADF

Hadoop

MDM

Core java

Magic

Salesforse

webservices

Learning process of java:- Corejava

Adv java

JDBC Servlets jsp

Hibernate structs Web services,tools(ant,maven,svn…..) Spring

Parts of the java:-

As per the sun micro system standard the java language is divided into three parts

  1. J2SE/JSE(java 2 standard edition)
  2. J2EE/JEE(java 2 enterprise edition)
  3. J2ME/JME(java 2 micro edition)

Java keywords:-(50)

Data Types byte short int long float double char boolean (8)

Flow-Control:- if else switch case default break for while do continue (10)

Predefined constants

method-level:- void return (2)

Object-level:- new this super instanceof (4)

source-file: class extends interface implements package import (6)

True, false, null (3)

Exception handling:- try catch finally throw throws ( 5)

1.5 version:- enum assert (2)

unused:- goto const (2)

Modifiers:- public private protected abstract final static strictfp native transient volatile synchronized ( 11)

Differences between C & CPP & JAVA:-

C-lang #include<stdio.h> Void main() { Printf(“hi ratan”); }

Author: Dennis Ritchie

Implementation languages:

COBOL,FORTRAN,BCPL, B…

In c-lang the predefined support is available in the form of header files. Ex:- stdio.h , conio.h

The header files contain predefined functions. Ex:- printf,scanf…..

C-lang C

Header files stdio.h

Functions printf,scanf..etc

In above first example we are using printf predefined function that is present in stdio.h header file hence must include that header file by using #include statement. Ex:#include<stdio.h>

In C lang program execution

starts from main method

called by Operating system.

To print data use printf()

Cpp-lang #include<iostream.h> Void main() { Cout<<“hello ratan”; }

Author : Bjarne Stroustrup

implementation languages: c ,ada,ALGOL68…..

cpp language the predefined is maintained in the form of header files. Ex:- iostream.h

The header files contains predefined functions. Ex:- cout,cin….

CPP-lang CPP

Header files iostream.h

Functions cout,cin..etc

In above first example we are using cout predefined function that is present in stdio.h header file hence must include that header file by using #include statement. Ex:#include<stdio.h>

In C lang program execution

starts from main method

called by Operating system.

To print data use cout

Java – lang Import java.lang.System; Import java.lang.String; Class Test { Public static void main (String [] args) { System.out.println (“hi java”); } } Author : James Gosling

implementation languages C,CPP,ObjectiveC…

In java predefined support is available in the form of packages. Ex: java.lang, java.io,java.awt

The packages contains predefined classes&interfaces and these class & interfaces contains predefined methods. Ex:- String,System

java-lang java

packages java.lang

classes&interface String-class

methods toUpperCase() in above exampe we are using two classes(String,System) these classes are present in java.lang package must import it by using import keyword. _a) Import java.lang._* ; all lasses b)Import java.lang.System; required Import java.lang.String; classes In above two approachaes 2nd^ good

In java execution starts from main called by JVM To print data use System.out.println()

Version Name Code Name Release Date JDK 1.0 Oak 23 January 1996 JDK 1.1 (none) 19 February 1997 J2SE 1.2 Playground 4 December 1998 J2SE 1.3 Kestrel 8 May 2000 J2SE 1.4 Merlin 13 February 2002 J2SE 5.0 Tiger 29 September 2004 Java SE 6 Mustang 11 December 2006 Java SE 7 Dolphins 28 July 2011 Java SE 8 (Not available) 18 March 2014

JAVA Features :-(buzz words)

  1. Simple
  2. Object Oriented
  3. Platform Independent
  4. Architectural Neutral
  5. Portable
  6. Robust
  7. Secure
  8. Dynamic
  9. Distributed
  10. Multithread
  11. Interpretive
  12. High Performance

1. Simple:-

Java is a simple programming language because,

 Java technology has eliminated all the difficult and confusion oriented concepts

like pointers, multiple inheritance in the java language.

 Java uses c,cpp syntaxes mainly hence who knows C,CPP for that java is simple

language.

2. Object Oriented:-

 Java is object oriented technology because it is representing total data of the class in

the form of object.

 Object oriented programming (OOPs) is a methodology that simplifies software

development and maintenance by providing some rules.

Basic concept of Oops are

 Object

 Class

 Inheritance

 Polymorphism

 Encapsulation

 Abstraction

3. Platform Independent :- When we compile the application by using one operating system (windows) that Compiled file can execute only on the same operating system(windows) this behavior is called platform dependency. Example :- C,CPP …etc

When we compile the application by using one operating system (windows) that Compiled file can execute in all operating systems(Windows,Linux,Mac…etc) this behavior is called platform independency. Example :- java,Ruby,Scala,PHP …etc

4. Architectural Neutral:-

Java tech applications compiled in one Architecture/hardware (RAM, Hard Disk) and that

Compiled program runs on any architecture (hardware) is called Architectural Neutral.

5. Portable:-

In Java the applications are compiled and executed in any OS (operating system) and

any Architecture (hardware) hence we can say java is a portable language.

6. Robust:-

Any technology good at two main areas that technology is robust technology.

a. Exception Handling

b. Memory Allocation

Java is providing predefined support to handle the exceptions.

Java provides Garbage collector to support memory management.

7. Secure:-

 To provide implicit security Java provides one component inside JVM called Security

Manager.

 To provide explicit security for the Java applications we are having very good predefined

library in the form of java.security package.

8. Dynamic:-

Java is dynamic technology it follows dynamic memory allocation (at runtime the

memory is allocated).

9. Distributed:-

By using java it is possible to develop distributed applications & to develop distributed

applications java uses RMI,EJB…etc

10. Multithreaded: -

 Thread is a light weight process and a small task in large program.

 In java it is possible to create user thread & it possible to execute simultaneously is called

multithreading.

 The main advantage of multi threading is it shares the same memory & threads are

important at multimedia, gaming, web application.

11. Interpretive:-

JAVA is both interpretive and completive by using Interpreter we are converting source

code into byte code and it a interpreter is a part of JVM.

12. High Performance:-

If any technology having features like Robust, Security, Platform Independent, Dynamic and

so on then that technology is high performance.

Types of java applications:-

1. Standalone applications:  It is also known as window based applications or desktop applications.  This type of applications must install in every machine like media player, antivirus …etc  By using AWT & Swings we are developing these type of applications.  This type of application does not required client-server architecture. 2. Web applications: a. The applications which are executed at server side those applications are called web applications like Gmail, face book ,ya hoo…etc. b. All applications present in internet those are called web-applications. c. The web applications required client-server architecture. i. Client : who sends the request. ii. Server : it contains application & it process the app & it will generate response. iii. Database : used to store the data. d. To develop the web applications we are using servlets,structs,spring…etc 3. Enterprise applications:-  It is a business application & most of the people use the term it I big business application.  Enterprise applications are used to satisfy the needs of an organization rather than individual users. Such organizations are business, schools, government …etc  An application designed for corporate use is called enterprise application.  An application in distributed in nature such as banking applications.  All j2ee & EJB is used to create enterprise application. 4. Mobile applications:-  The applications which are design for mobile platform are called mobile applications.  We are developing mobile applications by sing android,IOS,j2me…etc  There are three types of mobile applications o Web- application (gmai l ,online shopping,oracle …etc) o Native (run on device without internet or browser)ex:phonecall,calculator,alaram,games These are install from application store& to run these apps internet not required. o Hybrid (required internet data to launch) ex:whats up,facebook,LinkedIn…etc These are installed form app store but to run this application internet data required.

Install the software and set the path :-

1) Download the software.

2) Install the java software in your machine.

3) Set the environmental variable.

Download the software:-

 Download the software from internet based on your operating system & processor

because the software is different from operating system to operating system &

processor to processor.

Open the Google site type the jdk8 download as shown below.

After clicking above link we will get below window then accept license agreement by clinking radio

button then choose the software based on your operating system and processor to download.

For 32 - bit operating system please click on Windows x For 64 - bit operating system please click on Windowsx

Install the java software in your machine:-

 Install the java software just like media players in your machine.

 After installing the software the installation java folder is available in the fallowing

location by default.(but it possible to change the location at the time of installation).

Local Disk c: --->program Files--->java --->jdk(java development kit),jre(java runtime nvironment)

After installing To check whether the java is installed in your system or not open the command prompt type javac command.

Process to open command prompt: Start --->run---->open:cmd---->ok

C:\Users\RATAN>javac

Whenever we are getting above information then decide in our system java is installed

but the java is not working.

Why java is not working Reason:-

C:\Users\RATAN>javac

Whenever we are typing javac command on the command prompt operating system will

pickup javac command search for that command,

a) in the internal operating system calls but javac is not available in the internal system calls list. b) If it not available in internal system calls list then immediately it won’t raise any error, it will search in environmental variables In above two cases if the javac command is not available then operating system will raise error message “javac is not recognized as an internal or external command”

To overcome above problem to make eligible javac command operating system set

environmental variables.

The location of javac command is : C:\Program Files\Java\jdk1.7.0\bin

R ight click on mycomputer --->properties----->Advanced system setting--->Environment Variables -- User variables--->new----> variable name : path Variable value : C:\programfiles\java\jdk1.6.0_11\bin; ----->ok---->ok

Now the java is working in your system to check open the new command prompt & type javac command then we will get list of commands then decide in your system java is working. In your system or your friend system to check java is installed or not open the command prompt & type javac command a) If error message displayed java is not working. ('javac' is not recognized as an internal or external command) b) If list of commands are displayed then decide java is working properly.

Steps to Design a First Application:-

Step-1:- Select an Editor. Step-2:- Write the application. Step-3:- save the application. Step-4:- Compilation Process. Step-5:- Execution process.

Step1:- Select an Editor Editor is a tool or software it will provide very good environment to develop java application. Ex :- Notepad, Notepad++,edit Plus …..etc IDE:- ( Integrated development Environment ) IDE is providing very good environment to develop the application. Ex:- Eclipse,MyEclipse,Netbeans,JDeveloper….etc IDE is a real-time standard but don’t use IDE to develop core java applications because 75% work is done by IDE & remaining 25 % work is down by developer. 75% work of IDE is:-  Automatic compilation.  Automatic package import.  It shows all the predefined methods of classes.  Automatically generate try catch blocks and throws (Exception handling)  It is showing the information about how to fix the bug………………………etc Note :- Do the practical’s of core java only by using Edit Plus software.

Step 2:- Write a program.

 Write the java program based on the java API (Application Programming Interface) rule and regulations. Open editplus --->file ---->new ----->click on java (it display sample java application)  Java is a case Sensitive Language so while writing the program you must take care about the case (Alphabet symbols). Example application:- import java.lang.System; import java.lang.String; class Test //class declaration { //class starts public static void main(String[] args) //program execution starting point { //main starts System.out.println("hi Ratan"); //printing statement } //main ends }; //class ends class A { }; class B { };

In above example String & System c lasses are present predefined java.lang package hence must import that package by using import statement.

To import the classes into our application we are having two approaches,

  1. Import all class of particular package. a. Import java.lang.*; //it is importing all classes of java.lang package.
  2. Import required classes a. Import java.lang.System; b. Import java.lang.String; In above two approaches second approach is best approach because we are importing application required classes. Note: The source file is allows declaring multiple java classes.

Step3:- save the application.  After writing the application must save the application by using (.java) extension.  While saving the application must fallow two rules o If the source file contains public class then public class name & Source filename must be same (publicClassName.java). Otherwise compiler generate error message. o if the source file does not contain public class then save the source file with any name (anyName.java) like A.java , Ra tan.java, Anu.java …….etc.

Note: - The source file allowed only one public class, if we are trying to declare multiple public classes then compiler generate error message.

example 1:- invalid //Ratan.java public class Test { }; class A { };

example 2:- valid //Test.java public class Test { }; class A { };

example 3:- invalid //Test.java public class Test { }; public class A { }; Application location:- D: (any disk) |-->rattan (any folder) |-->Sravya.java (your file name)

Step-4:- Compilation process. Compile the java application by using javac command. Syntax:- Javac filename Javac Test.java

Process of moving application saving location:-

C:\Users\hp> initial cursor location

C:\Users\hp>d: move to local disk D

D:>cd ratan changing directory to ratan

D:\ratan>javac Sravya.java compilation process

Whenever we are performing compilation the compiler will check the syntax errors.  If the application contains syntax errors then compiler will generate error message in the form of compilation error.  If the application does not contains syntax errors then compiler will generate .class files.(conversion of .java to .class )

Note: - in java .class files generated by compiler at compilation time and .class file generation based on number of classes present in source file. If the source file contains 100 classes after compilation compiler generates 100 .class files The compiler generate .class file and .class file contains byte code instructions it is intermediate code.

Process of compiling multiple files:- D: |-->ratan |-->Sravya.java |-->A.java |-->B.java |-->C.java javac A.java one file is compiled(A.java) javac B.java C.java two files are compiled *javac *.java* all files are compiled

Step-5:- Execution process.

Run /execute the java application by using java command. Syntax:- Java class-name Java Test

Whenever you are executing particular class file then JVM perform fallowing actions.  JVM wills loads corresponding .class file byte code into memory.  After loading .class file JVM calls main method to start the execution process. In above two cases if the class file or main method is not available then at runtime JVM will generate error message. If the main method is not available: “Main method not found in class A, please define the main method”. If the .class is not available : “Could not find main class ”.

Executing all generated .class files based on example given in second step:- Test class ---> class is loaded & main is present A class ---> class is loaded but main is not present B class ---> class is loaded but main is not present XXX class ---> XXX class is not present

D:\ratan>java Test Hi Ratan D:\ratan>java A Error: Main method not found in class A, please define the main method as: public static void main(String[] args) D:\ratan>java B Error: Main method not found in class B, please define the main method as: public static void main(String[] args) D:\ratan>java XXX Error: Could not find or load main class XXX

Note 1: - compiler is translator it is translating .java file to .class where as JVM is also a translator it is translating .class file to machine code.

Note 2:-Compiler understandable file format is .java file but JVM understandable file format is .class file.

Note 3:- it is possible to compile multiple files at a time but it is possible to execute only one .class file at a time.

Note 4:- The .java file contains high level language (English) but .class file contains byte code instructions.

Note 5:- The source is allowed to declaring multiple non-public classes but only one public class.

Overview of first application

Environment of the java programming development:-

First program development :-

Note: - java is a platform independent language but JVM is platform dependent.

Example-1:-  Java contains 14 predefined packages but the default package in java is java.lang package it means if we are importing or not by default this package is imported.  In below example importing classes are optional. class Test { public static void main(String[] args) { System.out.println("hi ratan"); } }

Example-2:- The class contains main method is called Main class and java allows to declare multiple main class in a single source file. class Test { public static void main(String[] args) { System.out.println("Test1 World!"); } } class Test { public static void main(String[] args) { System.out.println("Test2 World!"); } } class Test { public static void main(String[] args) { System.out.println("Test3 World!"); } } D:\morn11>java Test Test1 World!

D:\morn11>java Test Test2 World!

D:\morn11>java Test Test3 World!

Class Elements:-  Java is a class based language it means everything we are representing based on class.  The java class contains 5-elements if we know these five elements flow of execution perfectly then java is very simple language otherwise java is very difficult.

Class Test {

1. variables int a = 10; 2. methods void add() {business logic } 3. constructors Test() {business logic } 4. instance blocks {business logic } 5. static blocks static {business logic } }

Java coding conventions:-

Classes:-

 Class name start with upper case letter and every inner word starts with upper case letter.

 This convention is also known as camel case convention.

 The class name should be nouns.

Ex:- S tring S tring B uffer I nput S tream R eader ……etc

Interfaces :-

 Interface name starts with upper case and every inner word starts with upper case letter.

 This convention is also known as camel case convention.

 The class name should be nouns.

Ex: S erializable C loneable R andom A ccess

Methods :-

 Method name starts with lower case letter and every inner word starts with upper case letter.  This convention is also known as mixed case convention  Method name should be verbs. Ex:- post() char A t() to U pper C ase() compare T o I gnore C ase()

Variables:-

 Variable name starts with lower case letter and every inner word starts with upper case letter.  This convention is also known as mixed case convention. Ex :- out in page C ontext

Package :-

 Package name is always must written in lower case letters. Ex :- java.lang java.util java.io …etc

Constants:-

 While declaring constants all the words are uppercase letters. Ex: MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY

NOTE:- The coding standards are mandatory for predefined library & optional for user defined library

but as a java developer it is recommended to fallow the coding standards for user defined library also.

Java Tokens:-

 Smallest individual part of a java program is called Token.  It is possible to provide any number of spaces in between two tokens. Example:- Class Test { Public static void main ( String[] args ) { int a = 10 ; System. out. println ( “java tokens”); } }

Tokens are --------- class , test , { , ” , [ …………….etc

Java Comments:-  Comments are used to write the detailed description about application logics to understand the logics easily.  Comments are very important in real time because today we are developing the application but that application maintained by some other person so to understand the logics by everyone writes the comments.  Comments are non executable code these are ignored at compile time.

There are 3 types of comments. 1) Single line Comments:- By using single line comments it is possible to write the description about our programming logics within a single line & these comments are Starts with // (double slash) symbol. Syntax:- //description

2) Multi line Comments:- This comment is used to provide description about our program in more than one line & these commands are start with /* & ends with / Syntax: - /----satement-1 ----statement-2 */

3) Documentation Comments:- By using documentation comments it possible to prepare API(Application programming interface) documents.(e will discuss later chapte) Syntax: - /* *statement-1 *statement-2 / Example:- /project name:-green project team size:- 6 team lead:- ratan */ class Test //class declaration { //class starts public static void main(String[] args) // execution starting point { //main starts System.out.println("ratan"); //printing statement }//main ends };//class ends

Separators in java:- Symbol name usage

( ) parentheses used to contains list of parameters & contains expression.

{ } braces block of code for class, method, constructors & local scopes.

[ ] brackets used for array declaration.

; semicolon terminates statements.

, comma separate the variables declaration & chain statements in for.

. period used to separate package names from sub packages. And also used for separate a variable,method from a reference type.

Print() vs Println ():-

Print():- used to print the statement in console and the control is present in the same line.

Example:- System.out.print(“ Sravyainfotech ”) ; System.out.print(“core java”); Output:-SravyaInfotechcorejava Println():- used to print the statements in console but the control is there in next line.

Example:- System.out.println(“ Sravyainfotech ”); System.out.println(“core java”); Output: - Sravyainfotech Core java

Downloading Api document:-

To download java api document use fallowing link

http://docs.oracle.com/javase/8/docs/

click on JDK 8 documentation then you will get below page.

Accept the license agreement and download the file.

Java identifiers:- Every name in java is called identifier such as,  Class-name  Method-name  Variable-name

Rules to declare identifier:

  1. An identifier contains group of Uppercase & lower case characters, numbers ,underscore & dollar sign characters but not start with number. int abc=10; ---> valid int _abc=30; ---> valid int $abc=40; ---> valid int a-bc=50; --->not valid int 2abc=20; ---> Invalid int not/ok=100 --->invalid
  2. Java identifiers are case sensitive of course java is case sensitive programming language. The below three declarations are different & valid. class Test { int NUMBER=10; int number=10; int Number=10; };
  3. The identifier should not duplicated & below example is invalid because it contains duplicate variable name. class Test { int a=10; int a=20; };
  4. In the java applications it is possible to declare all the predefined class names & interfaces names as a identifier but it is not recommended to use. class Test { public static void main(String[] args) { int String=10; float Exception=10.2f; System.out.println(String); System.out.println(Exception); } };
  5. It is not possible to use keywords as a identifiers. class Test { int if=10; int try=20; };
  6. There is no length limit for identifiers but is never recommended to take lengthy names because it reduces readability of the code.

Java primitive Data Types:-

  1. Data types are used to represent type of the variable & expressions.
  2. Representing how much memory is allocated for variable.
  3. Specifies range value of the variable.

There are 8 primitive data types in java Data Type size(in bytes) Range default values byte 1 -128 to 127 0 short 2 -32768 to 32767 0 int 4 -2147483648 to 2147483647 0 long 8 – 9,223,372,036,854,775,808 to 9 ,223,372,036,854,775,807 0 float 4 -3.4e38 to 3.4e 0.0 double 8 -1.7e308 to 1.7e308 0.0 char 2 0 to 6553 single space Boolean no-size no-range false

Byte :-

Size : 1-byte MAX_VALUE : 127 MIN_VALUE : -128 Range : -128 to 127 Formula : -2n^ to 2n-1^ -2^8 to 28-1

26 25 24 23 22 21 20 64+32+16+8+4+2=128

Note :-

 To represent numeric values (10,20,30…etc) use byte,short,int,long.

 To represent decimal values(floating point values 10.5,30.6…etc ) use float,double.

 To represent character use char and take the character within single quotes.

 To represent true ,false use Boolean.

Except Boolean and char remaining all data types consider as a signed data types because we can represent both +ve & -ve values. Float vs double:- Float will give 5 to 6 decimal places of accuracy but double gives 14 to 15 places of accuracy. Float will fallow single precision but double will fallow double precision.

Syntax:- data-type name-of-variable = value/literal;

Ex:- int a=10;

Int ------ Data Type a ------ variable name = ------ assignment 10 ------ constant value ; ------ statement terminator

printing variables :-

int a=10;

System.out.println(a); //valid

System.out.println("a"); //invalid

System.out.println('a'); //invalid

User provided values are printed

int a = 10; System.out.println(a);//10 boolean b=true; System.out.println(b);//true char ch='a'; System.out.println(ch);//a double d=10.5; System.out.println(d);//10.5

Default values(JVM assigned values)

int a; System.out.println(a);//0 boolean b; System.out.println(b);//false char ch; System.out.println(ch);//single space double d; System.out.println(d);//0.0

Example :-//Test.java

class Test

{ public static void main(String[] args)

{ float f=10.5;

System.out.println(f);

double d=20.5;

System.out.println(d);

}

}

D:\ratan>javac Test.java

Test.java:3: error: possible loss of precision

float f=10.5;

required: float found: double

in above example decimal value(10.5) by default double value hence compiler

generating error message so to represent float value use f constant or perform type casting.

float f =10.5f; //using f constant (valid)

float f =(float)10.5; //using type casting (valid)

variable declarations:

int a=10; ----> integer variable

double d=10.5; ----> double variable

char ch='a'; ----> char variable

boolean b=true; ----> boolean variable

float f=10.5f; ----> float variable

String str=”ratan”; ----> String variable

Note: String is not a data type & it is a class present in java.lang package to represent group

of characters or character array enclosed with in double quotes.