0% found this document useful (0 votes)
33 views82 pages

Object-Oriented Programming in Java Notes

Create word space in every sentence.

Uploaded by

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

Object-Oriented Programming in Java Notes

Create word space in every sentence.

Uploaded by

hgf190916
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BALASORECOLLEGEOFENGINEERING&TECHNOLOGY,

SERGARH,BALASORE

LectureNotes on

Subject:ObjectOrientedProgrammingusingJava

(AsperthelatestsyllabusofBPUT,Rourkela,Odisha)

Year-2nd Sem-3rd

Preparedby-:
[Link] Abani Kumar Dash

Department:CSE
Checked By(Name
and Designation)
MODULEWISEDISTRIBUTIONOF LOADS

Module Chapterwith title Assigned Actual Range of Marks of


Hours Sessions Questionstobeasked
(as per Needed (BPUT)
BPUT)

1 1. Anintroductionto Programming 10Hrs 13Hrs 10-25

2. IntroductiontoJAVA

3. UnderstandingJavaProgramsand
a step forward

1. IntroductiontoClassand Objects
2 2. Inheritance
3. StringManipulations
8Hrs 12Hrs 20-40

1. Dataabstraction
3 2. Multithreading 9Hrs 12Hrs 40-60

1. IOstreams 60-80
4 2. APPLET 10Hrs 12Hr

1. Swings 80-100
5 8Hrs 10Hrs
2. JAVAFX

Total- 45 Hrs 59Hrs 100


SYLLABUS
Books:
1. Herbertschildt(2010),Thecompletereference,7thedition,TataMcgrawHill,NewDelhi
2. ProgrammingwithJava, [Link],McGraw-HillEducation,6thEdition.
3. Head First Java, O’riellypublications2. [Link](2009), AnIntroductionto ObjectOriented
Programming, 3rd edition, Pearson Education, India.
4. J. Nino, F. A. Hosch(2002), AnIntroduction to programming and OO designusing Java,John
Wiley & sons, New Jersey.
Course:ObjectOrientedProgrammingusingJava Code:

ROP3B201

Department: Mechanical

COURSEOBJECTIVES:

1. Understandthebasicobjectorientedprogrammingconceptsandapplythemin
2. problemsolving.
3. Demonstratethebehaviorofprogramsinvolvingthebasicprogramming.
4. Illustrateinheritanceconceptsforreusingtheprogram&polymorphism.
5. Demonstrateontheexceptionhandling&multithreading.
6. UnderstandthebasicsofjavaconsoleandGUIbasedprogramming

COURSEOUTCOMES:

Uponthesuccessfulcompletionofthiscoursestudentswillbeableto:

[Link] world
entities.

[Link] constructs like


control structures, constructors, string handling methods.

[Link] the implementation of inheritance ( single,hierarchical and multilevel)


byusingextendand usedynamicandstaticpolymorphismtoprocessobjectsdepending on
their class.

[Link](fullyqualified name and


import statements) & describe the concept of interface and abstract classes to define
generic classes.

[Link] mechanismstoavoidabnormalterminationof program


using checked and unchecked exceptions &multithreading concepts.

[Link] usingAWTandswings.
Module-1 Chapter–01
AnIntroductiontoProgramming
Lecture-1
LearningObjectives:

Thestudentswillbeableto understand:
Differenttypesofprogramminglanguages
Descriptionofcompilerandinterpreter

Differenttypesofprogramminglanguages
Programmerswriteinstructionsinvariousprogramminglanguagestoperformtheircomputationtaskssuchas:
a) MachinelevelLanguage
b) AssemblylevelLanguage
c) HighlevelLanguage

[Link] levelLanguage:
 Machinecodeormachinelanguageisasetofinstructionsexecuteddirectlybyacomputer'scentral processing
unit (CPU).
 Each instruction performs a very specific task, such as a load, a jump, or an ALU operation on a unit of
data in a CPU register or memory.
 EveryprogramdirectlyexecutedbyaCPUismadeupofa seriesofsuchinstructions.

b) AssemblylevelLanguage:
 An assembly language (or assembler language) is a low-level programming language for a
computer,orother programmable device.
 Herethereisaverystrong(generallyone-to-one)correspondencebetweenthelanguageandthe architecture's
machine code instructions.
 Assemblylanguageisconvertedintoexecutablemachinecodebyautilityprogramreferredtoasan assembler; the
conversion process is referred to as assembly, or assembling the code.
c) HighlevelLanguage:
 High-level language is any programming language that enables development of a program in much
simpler programming context and is generally independent of the computer's hardware architecture.
 High-level languages has a higher level of abstraction from the computer, and focuses more on the
programming logic rather than the underlying hardware components such as memory addressing and
register utilization.
 The first high-level programming languages were designed in the 1950s. Now there are dozens of different
languages, including Ada , Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal, and Prolog.
 Suchlanguagesareconsideredhigh-levelbecausetheyareclosertohumanlanguagesandfartherfrom machine
languages.
 Incontrast,assemblylanguagesareconsideredlow-levelbecausetheyareveryclosetomachinelanguages.
 Thehigh-levelprogramminglanguagesarebroadlycategorizedintotwocategories:
o Procedureorientedprogramming(POP)language.
o Objectorientedprogramming(OOP)language.
DescriptionofCompilerandInterpreter

Compiler Interpreter
 Itscansentireprogramfirstthen  Itscanstheprogramline-byline&translate
translates it into machine code into machine code
 Compilershowsallerrors&warning at  Interpretershowsoneerroratatime
same time
 Errorsoccursafterscanningthewhole  Erroroccursafterscanningeachline
program  Debuggingis faster
 Debuggingisslow  Executiontimeis less
 Executiontimeis less  Interpreterisusedbylanguagesuchasjava,
 Compilerisusedbythelanguagelike C, python ,etc.
C++ , etc.

[Link]

[Link]
Module-1 Chapter–01
AnIntroductiontoProgramming
Lecture-2
LearningObjectives:

Thestudentswillbeableto understand:
AdvantagesofObjectOrientedProgramming(OOPs)
ProcedureOrientedProgrammingLanguageandit’sdemerits
WhyOOPs?
BasicconceptsofOOPs

AdvantagesofObjectOrientedProgramming(OOPs)

ProcedureOrientedProgrammingLanguage

 In the procedureoriented approach, the problem is viewed as sequence ofthings to be done such asreading
calculation and printing.
 Procedure oriented programmingbasically consistof writing alistof instruction or actionsfor the
computer to follow and organizing these instruction into groups knownas functions.

Fig.3 ConceptsofPOP
 Thedisadvantageoftheprocedureoriented programminglanguagesis:
1. Globaldataaccess
2. Itdoes notmodelrealwordproblemverywell
3. Nodatahiding

Fig.4 Working ofPOP


 Characteristicsofprocedureorientedprogramming:

1. Emphasis isondoingthings(algorithm)
2. Largeprogramsaredividedintosmallerprogramsknownasfunctions.
3. Mostofthefunctionsshareglobaldata
4. Datamoveopenlyaround the systemfromfunctiontofunction
5. Functiontransforms data fromoneformtoanother.
6. Employstop-downapproach inprogramdesign
WhyOOPs?
“Objectorientedprogrammingasanapproachthatprovidesawayofmodularizingprogramsby
Creatingpartitioned memoryarea forbothdataand functionsthat canbeusedastemplatesfor creatingcopies of such
modules on demand”.

[Link]
 Featuresofthe ObjectOrientedprogramming.
o Emphasisisondoingratherthanprocedure.
o Programsaredividedintowhatareknownasobjects.
o Datastructuresaredesigned suchthat theycharacterizethe objects.
o Functionsthatoperateonthedataofanobjectaretiedtogetherinthedatastructure.
o Dataishiddenand can’tbeaccessedbyexternalfunctions.
o Objectsmaycommunicatewitheachotherthroughfunctions.
o Newdataand functionscanbe easilyadded.
o Followsbottom-upapproachinprogramdesign.
[Link]
Module-1 Chapter–01
AnIntroductiontoProgramming
Lecture-3
LearningObjectives:

Thestudentswillbeableto understand:
BasicconceptsofOOPs
Object
Class
DataEncapsulation
DataHiding
DataAbstraction
Variousconceptsofobjectorientedprogrammingare:

Object

 Objects are basic entities in anobject oriented system. Anobject is a realworld entitywhichposses
certain properties (also called attributes) and behavior (also called operation).
 Objects may represent a person, place, flower, a bank account, a table of data or any other item
that a program has to handle.
 Ina program, properties ofanobject arerepresented using variables whichare also knownas data (or
data members) and behaviors are represented using functions which are also known as member
functions.
 Objectsarealsoknownasinstanceofaclass.

 FewExamplesofobject are:

Fig.1.4.1. Objects

 Astudentobjecthasproperties likename, rollno,DOB, emailetc.

 Abookobjecthaspropertiesliketitle,authorname,[Link]
properties likeradius, coordinatesofcenteretc.

Class
 Collectionofsimilarobjectswhichpossessescommonproperties(alsocalledattributes)and behavior(also
called operation) is known as class.
 Itisatemplateorblueprintfromwhichobjectsarecreated.
 Fewexamplesofclass:

Fig.1.4.2Class

DataEncapsulation

 Thewrappingofdatamembersandmemberfunctionsintoasingleunitisknownasdata encapsulation.

 Thedataisnotaccessibletotheoutsideworldandonlythosefunctionswhicharewrappedinthe class can


access it.

 Thesefunctionsprovidetheinterfacebetweentheobjectsdataandtheprogram.

Fig.1.4.3Data Encapsulation
Data hiding:The insulationofdata and methods of a class fromdirect access byother classes is known as
data hiding. Essentially, access privileges members of a class is assigned to other classes with the help of
access specifiers (like default, private, protected & public) and OOP principles likeinheritance,
polymorphism etc.

Data abstraction: The act of representing the essential features of an entity by omitting their complete
details is known as data abstraction. Class supports the principle of data abstraction with the concept of
abstract classes and hence class is also known as abstract data type (ADT).
Module-1 Chapter–01
AnIntroductiontoProgramming
Lecture-4
LearningObjectives:

Thestudentswillbeableto understand:
1.4.7Inheritance
Inheritance:
 Inheritance is a mechanism by which objet of one class acquires the properties of object of another
class.
 The class fromwhich properties are taken into a new class is known as parent class or super class.
The class which takes properties froman existing class is known as child class or sub class.
 ItisanimportantpartofOOPs(ObjectOriented programmingsystem).
 Themainadvantagesofinheritanceare:
o Code Reusability
o CodeMinimization
o MaintainingclassHierarchy
o WellProgramming Constructetc

 There are various types of inheritance (like single, hierarchical, multi level and hybrid etc) in java
which arediscussed later in this course.
 Injava inheritance isachievedthroughthekeywordextends.
 Asimpleexampleofhierarchicalinheritance:

Fig.1.4.7Concept on Inhertance

 Here,classCarandTruckinheritsthepropertiesoftheclassvehicle.

 ClassVehicleiscalledsuperclassandclassCarand Truckarecalled subclasses.


Polymorphism

 Thewordpolymorphismmeanshavingmanyforms(Polymeansmanyandmorphmeansforms).
 Insimple words, wecandefine polymorphismas the abilityofanentityto exhibit multiple behaviors or
definitions depending upon the working environment.
 Performingsametaskindifferentwaysiscalled polymorphism.
 Real life example of polymorphism: A person at the same time can have different characteristics.
Like a man at the same time is a father, a husband, an employee. So, the same person has different
behavior in different situations.
 ImplementationofPolymorphismistwotypes:
o Overloadingmaybeoperatoroverloadingorfunctionoverloading(Compiletimepolymorphism)
&operator overriding (Run-time polymorphism)
o Exampleofpolymorphisminprogramming:
o Samefunctionareacanbeusetofindareaofarectangle,circle,squareetc(thismechanism is known as
ofunctionormethodoverloading)whichisshowninthebelowdiagram:

Fig.1.4.7MethodOverloading
MessagePassing
 Asingleobjectmaynotbebeneficialbyitself.
 [Link] methods or
functions on that object.
 ThisprocessiscalledMessagePassing.

Fig. 1.4.8Message Passing


Module-1 Chapter–02
IntroductiontoJava
Lecture-5
LearningObjectives:

Thestudentswillbeableto understand:
HistoryofJava
JavaBuzzwords

Historyof JAVA
 History of Java is very interesting. Java was originally designed for interactive television, but it was
too advanced technology for the digital cable television industry at the time.
 ThehistoryofjavastartswithGreenTeam. Javateammembers (also knownasGreenTeam), initiated this
project to develop a languagefor digital devices such as set-top boxes, televisions, etc.
 However,[Link],JavatechnologywasincorporatedbyNetscape.
JamesGosling
JamesGoslingisthefounderofjava.
 JamesGosling,MikeSheridan,andPatrickNaughtoninitiatedtheJava
 language [Link]
Green Team.

 Why Oak? Oak is a symbol of strength and chosen as a national treeof


many countries like U.S.A., France, Germany, Romania, etc.
 In1995,Oakwas renamedas"Java"because itwas alreadyatrademark
OakTree [Link] something thatreflectedthe
essenceofthetechnology:revolutionary,dynamic,lively,cool,unique, and
easyto spell and fun to say.
 Java isanislandofIndonesia wherefirstcoffeewasproduced(called java
coffee).
 InitiallydevelopedbyJamesGoslingatSunMicrosystems(which isnow a
subsidiary of Oracle Corporation) and released in 1995.
 JDK1.0releasedinJanuary23,1996.

Coffee
JavaBuzzwords/FeaturesofJava

FeaturesofjavaiscalledJavaBuzzwords.

The buzzwordsof Java are :

PlatformIndependent

 Being platform-independent means a program compiled on one machine can be executed on any
machine in the world without anychange. Java achieves platform independence by using the concept
of the BYTE code.
 Java compiler converts the source code into anintermediate codecalled the byte code and this byte
code is further translated to machine-dependent form by another layer of software called JVM (Java
Virtual Machine).

[Link]

SimpletoImplement
 Javaissimplebecause: Itscodingstyleisverycleanandeasyto understand.
 It removescomplexitybecause it doesn’t use complexand difficult featuresofother languages like C and
C++, which are as follows:
o ConceptofExplicitPointers
o Storageclasses
o Preprocessorsandheaderfiles
o MultipleInheritance
o OperatorOverloading
o GotoStatements
CompiledandInterpreted
 Usually,[Link] of Compiled
Languages with the flexibility of Interpreted Languages.
 Javacompiler(javac)compilesthe javasourcecodeintothebytecode.
 JavaVirtualMachine(JVM) thenexecutesthis bytecodewhichisexecutableonmanyoperating systems and is
portable.
 Thediagrambelowshowstheabove process:

[Link]&Interpreter

Portable
 Javaprogramwritteninoneenvironmentcanbeexecuted/implementedinanotherenvironment.
 InC/C++,thesourcecodemayrunslightlydifferentlyondifferent hardwareplatforms, but Java
simplifies it.
 YoucanrunJava bytecodeonanyhardwarethat hasacompliant JVMwhichcanconvertthebytecode
according to that particular machine.

ArchitecturalNeutral
 Thisbuzzword meansthat theprogramwrittenononeplatformorOS isindependentofother platforms or
environments and can run on any other Operating System without recompiling them.
 Inotherwords,it isbasedonthe ‘Write-once-run-anywhere’(WORA)or‘Write-once-run
everywhere’ (WORE) approach.
 Byte-codeis notdependentonanymachinearchitectureandJavaVirtualMachine(JVM) caneasily
translate bytecode into a machine-specific code.
 Thisfeatureisveryusefulwhenwedevelop appletsordownload applicationsfromtheInternet.

Object-Oriented
 Java strongly supports the concepts ofObject-Oriented Programming due to which it is called a pure
object-oriented [Link] supports major Object-Oriented programming features like
Encapsulation, Abstraction, and Inheritance.

Robust
 Javaisrobustasitiscapableofhandlingrun-timeerrors,supportsautomaticgarbagecollection and
exception handling, and avoids explicit pointer concept.
 [Link] during both
compile and runtime.
Secure
 Securityisan important issue for anyprogramming language asthere isa threat ofmaliciousactivities and
[Link] check memoryaccessandalso ensuresthat noviruses enter an
applet.
 Java isa moresecurelanguageascomparedtoC/C++,asit doesnot allowaprogrammerto explicitly create
pointers.
 ThusinJava,wecannotgainaccesstoaparticularvariableifwedonotinitializeitproperly.

Fig.1.6.6JavaSecure Mechanism

Distributed
 Javaisdistributedbecauseitencouragesuserstocreatedistributed applications.
 InJava,wecansplitaprogramintomanypartsandstorethesepartsondifferentcomputers.
 AJavaprogrammersitting ona machinecanaccessanotherprogramrunning ontheothermachine.
 Thisfeature inJavagivesthe advantageofdistributedprogramming,whichisveryhelpfulwhenwe
develop large projects.
 Javahelpsusto achievethis byprovidingtheconceptofRMI(RemoteMethod Invocation) andEJB
(Enterprise JavaBeans).

Multi-threading
 Athreadisanindependentpathofexecutionwithinaprogram,executing concurrently.
 Multithreadedmeanshandlingmultipletaskssimultaneouslyorexecutingmultipleportions(functions) of
the same program in parallel.
 Thecodeofjava isdivided into smallerpartsandJava executesthemin a
sequential and timely manner.
MODULE-1 CHAPTERNO–02
IntroductiontoJava
Lecture-6
LearningObjectives:

Thestudentswillbeabletounderstand:

Myfirst javaprogram
PrerequisitesofJava Program
WritingJavaProgram
ExecutingJavaProgram

Myfirstjavaprogram
TocreateasimpleJavaprogram,youneedtocreateaclassthatcontainsthemainmethod.
classMyfirstjava{
publicstaticvoidmain(Stringargs[]){ [Link]("Hello
Java");
}
}

PrerequisitesofJavaProgram

ForexecutinganyJavaprogram, thefollowingsoftwareorapplicationmustbeproperlyinstalled.

 InstalltheJDKifyoudon'thaveinstalledit,downloadtheJDKandinstallit.
 Setpathofthejdk/bin directory.
 CreatetheJavaprogram.
 CompileandruntheJavaprogram

WritingJavaProgram
ThedifferentparametersusedinJavaprogramsare:
 classkeywordisusedto declareaclassinJava.
 [Link].
 staticis a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the staticmethod is that there is noneed to create an object to invoke the staticmethod. The
main() method is executed bythe JVM, so it doesn't require creating an object to invoke the main()
method. So, it saves memory.
 [Link]'treturnany value.
 mainrepresentsthestartingpointoftheprogram.
 String[]argsorStringargs[][Link] section.
 [Link]() is used to print statement. Here, System is a class, out is an object of the
PrintStream class,println()isamethodof thePrintStream [Link] working of
[Link]()statement in the coming section.

Stepstobeinvolvedinwritingajavaprogram

 To writethe simple program, you need toopennotepad bystart menu -> All Programs -> Accessories ->
Notepad and write a program.
 Write the programofJava in notepad and saved it as [Link]. Inorder to compile and runthe above
program, you need to open the command prompt bystart menu -> All Programs -> Accessories ->
command prompt.
 To compile and run the above program, go to your current directory first and type the commands for
compiling and running a java program.

ExecutingJavaProgram

Theexecutionprocessin javaprogramhastwosteps:

a) ToCompileaJavaProgram:Forcompilinga java programthe followingsyntaxisused Javac

[Link]

b) ToRunaJavaProgram:Thisprocessinvolvesthefollowingsyntaxtobeused.

Javafilename
MODULE-1 CHAPTERNO–02
IntroductiontoJava
Lecture-7
LearningObjectives:

Thestudentswillbeableto understand:

JVM
JVMArchitecture

JavaVirtualMachine(JVM)

A Virtual Machine is a software implementation of a physical machine. Java was developed with the
concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler compiles the
[Link] file, then that .class file is inputinto the JVM, which loads and executes the class
file. Below is a diagramof the Architecture of the JVM.

JVMArchitecture
Asshowninthebelowarchitecturediagram,theJVMisdivided intothreemainsubsystems: Sub
System 1 : Class Loader
SubSystem2:RuntimeDataArea Sub
System 3 : Execution Engine

SubSystem1:ClassLoader
Java'sdynamic class loading functionality is handled bythe ClassLoader subsystem. It loads, links and
initializes the class file when it refers to a class for the first time at runtime, not compile time.
Loading
Classeswill beloadedby thiscomponent. BootStrap ClassLoader,Extension ClassLoader,andApplication
ClassLoader are the three ClassLoaders that will help in achieving it.
 BootStrapClassLoader–Responsibleforloadingclassesfromthebootstrapclasspath,
nothingbut [Link]. Highest priority will be given to this loader.
 ExtensionClassLoader–Responsibleforloadingclasseswhichareinsidetheextfolder(jre\lib).
 ApplicationClassLoader–ResponsibleforloadingApplicationLevelClasspath,path
mentionedEnvironment Variable, etc.
Fig 2.7.1:JVMArchitecture
Linking
 Verify – Bytecode verifier will verify whether the generated bytecode is proper or
not if verificationfails we will get the verification error.
 Prepare –Forall staticvariablesmemory willbeallocatedand assignedwith default values.
 Resolve–Allsymbolicmemoryreferencesarereplacedwiththeoriginal referencesfrom
MethodArea.

Initialization
This is the final phase of ClassLoading; here, all static variables will be assigned with the original values,
andthe static block will be executed.

Subsystem2:RuntimeDataArea

TheRuntimeDataAreaisdividedinto fivemajorcomponents:
MethodArea–Alltheclass-leveldatawillbestoredhere, includingstaticvariables. There isonly one
method area per JVM, and it is a shared resource.

Heap Area – All the Objects and their corresponding instance variables and arrays will be stored
here. There is also one Heap Area per JVM. Since the Method and Heap areas share memory for
multiple threads, the data stored is not thread-safe.

Stack Area – For every thread, a separate runtime stack will be created. For every method call,one
entry will be made in the stack memory which is called Stack Frame. All local variables willbe
created in the stack memory. The stack area is thread-safe since it is not a shared resource. The
Stack Frame is divided into three subentities:

 LocalVariableArray –Relatedtothemethodhowmanylocalvariablesare involved


and the corresponding values will be stored here.
 Operandstack–Ifanyintermediateoperationisrequiredtoperform,operand
stackactsasruntime workspace to perform the operation.
 Framedata–[Link] caseof
anyexception,thecatchblock informationwillbemaintainedinthe framedata.

PC Registers – Each thread will have separate PC Registers, to hold the address of current
executing instruction once the instruction is executedthe PC register will be updated with the next
instruction.
Native Methodstacks – Native Method Stack holds native method information. For
everythread, aseparate native method stack will be created.

ExecutionEngine

The bytecode, which is assigned to theRuntime Data Area, will be executed by the Execution Engine.
The Execution Engine reads the bytecode and executes it piece bypiece.
Interpreter – The interpreter interprets the bytecode faster but executes slowly. The
disadvantage of the interpreter is that when one method is called multiple times, every time a
new interpretation is required.

JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The
Execution Engine will be using the help of the interpreter in converting byte code, but when it
finds repeated code it uses the JIT compiler, which compiles the entire bytecode and changes it
to native code. This native code will be used directly for repeated method calls, which improve
the performance of the system.

 IntermediateCodeGenerator–Producesintermediatecode
 CodeOptimizer–Responsibleforoptimizingtheintermediatecodegeneratedabove
 TargetCodeGenerator–ResponsibleforGeneratingMachineCodeorNativeCode
 Profiler–Aspecialcomponent,responsibleforfindinghotspots,[Link]
methodiscalledmultiple times or not.

Garbage Collector: Collects and removes unreferenced objects.. Garbage collection of theJVM
collects the objects that are created.

Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries and
provides the Native Libraries required for the Execution Engine.

Native Method Libraries: This is a collection of the Native Libraries, which is required for the
Execution Engine.
MODULE-1 CHAPTERNO–03
JAVADATATYPES& VARIABLES
Lecture-8
LearningObjectives:

Thestudentswillbeableto understand:

SimpleJavaprogram
Datatypes
JavaTokens
Variables
SimpleJAVAprogram

FirstJAVAProgram
Program1.1:Writeaprogramtoprintamessage“WelcometotheJAVAworld”
Solution:
//[Link]
class First
{
publicstaticvoidmain(Stringargs[])
{
[Link]("WelcometotheJAVAworld");
}}
Output:
WelcometotheJAVA world

Howtocompile &execute theabove


programCompilation:
Tocompiletheaboveprogram,usethefollowingsyntaxonthe
command line:javac java_filename.java

Herewewillusethefollowing command tocompileourprogram:

[Link]
If successfully compiled, the compiler creates a file called [Link] that contains byte code
version of our java program.
Execution:
Now to run a java program, use the
following syntax:java java_filename
Herewewillusefollowingcommandtorun the
program:java First
Inapurelyobjectorientedprogrammingsystem,allourcodesremaininsideaclassdefinition.
Explanationoftheaboveprogram
classFirst
Therefore,our [Link] usedtodefineaclass&First
is thenameofour class.
{
Herethisopening braceindicatesthebeginningoftheclassdefinitionblock.
Publicstaticvoidmain(String args[])

AllJavaapplications beginexecutionfrommain()function.(Thisis justlikeC/C++.)


 The public keyword is an access specifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then thatmember
may be accessed by code outside the class in which it is declared.
 The keyword static allows main ( ) to be called without having to instantiate a particular
instance of the class.
 The keyword void simply tells the compiler that main ( ) does not return a value. As
stated, main ( )is the method called when a Java application begins. Keep in mind that
Java is case-sensitive. Thus, Main is different from main.
 Stringargs[]declaresaparameternamedargs,whichisanarray ofinstancesof the class String.
This args parameter is essential when we enter some input through the command line
while executing a program.
{
 Herethisopening braceindicatesthebeginning ofmain methoddefinitionblock.
[Link]("WelcometotheJAVAworld");

Thislineoutputsthestring “WelcometotheJAVAworld”followed byanewlineonthescreen.


Outputis actually accomplishedby the built-in println()method. In this case,println()displays the
stringwhich is passed to it.
}
Herethisclosing braceindicatestheend ofmainmethoddefinitionblock.

DataTypes

[Link] create
variable you reserve some space in memory. Based on the datatype ofa variable, the operating system
allocatesmemoryanddecideswhat canbestoredinthereserved [Link],byassigningdifferent
datatypestovariables, youcanstoreintegers, decimals, or charactersinthesevariables. Therearetwodata types
available in Java:
Primitivedatatypes:Theprimitivedatatypesincludeboolean,char,byte,short,int,long, floatand double.
Non-primitivedatatypes:Thenon-primitivedatatypesincludeClasses,Interfaces,andArrays.

3.2.1PrimitiveDataTypes

Thereareeight primitivedatatypessupportedbyJava. Primitivedatatypesarepredefinedbythe languageand named


[Link] detail about the eight primitive data types.
JavaPrimitiveDataTypes

Category DataType DefaultValue Defaultsize

Boolean boolean false 1bit

Character Char '\u0000' 2byte

Integer Byte 0 1byte


short 0 2byte
Int 0 4byte
Long 0L 8byte
Float/Real Float 0.0f 4byte
double 0.0d 8byte

Note:Ingeneral,ifnbitsarerequiredforadatatype,thenitsrangeis−2n–1 to2n–1−1.

boolean

booleandatatyperepresentsonebitofinformation.

 Thereareonlytwopossiblevalues:trueandfalse.
 This datatypeisusedforsimpleflagsthattracktrue/falseconditions.
 Defaultvalueisfalse.
 Example:booleanone=true

char

chardatatypeisasingle16-bitUnicodecharacter whichdefault sizeis2bytes.


 Minimumvalueis'\u0000'(or0).
 Maximumvalueis'\uffff'(or65,535inclusive).
 Chardatatypeisusedtostoreanycharacter.
 Example:charletterA='A'

SolvedQuestion

Whycharuses2byteinjavaunlikeC/C++which uses1 byteofmemoryonlyandwhatis \u0000?


Solution:It isbecausejavausesUnicodesystem,notASCII(AmericanStandard Codefor
InformationInterchange)[Link] representsacharactersetwhichcanbeusedto represent all
languages available world. \u0000 is the lowest range of Unicode system.
byte:
bytedatatypeisdefaultsizeis1byte.
 Minimumvalueis-128(-2^7)
 Maximumvalueis127(inclusive)(2^7-1)
 Defaultvalueis0
 Bytedatatypeisusedtosavespaceinlargearrays,mainlyinplaceof integers, since a
byte is four times smaller than an int.
 Example:bytea=100,byteb=-50

short:

Shortdatatypeisdefaultsizeis2bytes..

 Minimumvalueis-32,768(-2^15)
 Maximumvalueis32,767(inclusive)(2^15-1)
 Short data type can also be used to save [Link] is 2
times smaller than an int
 Defaultvalueis0.
 Example:shorts=10000, shortr=-20000

int:

intdatatypeisdefaultsizeis4bytes.

 Minimumvalueis-2,147,483,648.(-2^31)
 Maximumvalueis2,147,483,647(inclusive).(2^31-1)
 Intisgenerallyusedasthedefaultdatatypeforintegralvaluesunlessthereisa concern about
memory.
 Thedefaultvalueis0.
 Example:inta=100000,intb=-200000

long:
Longdatatypeisdefaultsizeis8bytes.

 Minimumvalueis-9,223,372,036,854,775,808.(-2^63)
 Maximumvalueis9,223,372,036,854,775,807(inclusive).(2^63-1)
 This type is usedwhenawiderrangethanintisneeded.
 Defaultvalueis0L.
 Example:inta= 100000L,intb=-200000L

float:

 Float datatype isdefaultsizeis 4 bytes.


 Floatismainlyusedtosavememoryinlargearraysoffloatingpoint numbers.
 Defaultvalueis0.0f.
 Floatdatatypeisneverusedforprecisevaluessuchascurrency.
 Example:floatf1=234.5f

double:

 doubledatatypeisdefaultsize is8 bytes.


 Thisdatatypeisgenerallyusedasthedefaultdatatypefordecimal values,
generally the default choice.
 Doubledatatypeshouldneverbeusedforprecisevaluessuchas currency.
 Defaultvalueis0.0d.
 Example:doubled1= 123.4
JavaTokens

Thesmallestunitof codeappearinginaprogramwhichisrecognizedby thecompileriscalledastoken.A token in a java


program are of following types:

Identifiers

These are names assigned to variables, methods, classes, packages & interfaces. Following are the rulesto
construct an identifier:
 Anidentifier contains alphabets (A− Z,a−z), digits (0−9), underscore(_)ordollar ($) only.
 The firstcharacterinanidentifiermustbeanalphabetor underscore(_)ordollar($).
 Blankspacesarenotallowedwithinanidentifier.
 Keywordscan’tbe identifiers.
 Identifiernamearecasesensitive.
 There is no limit on the length of a Java identifier.
Examplesofsome valid identifiersare𝒙,𝒂𝟏,$𝒂, 𝑰𝒏𝒅𝒊𝒂,$𝒎𝒚𝑽𝒂𝒓𝒊𝒂𝒃𝒍𝒆etc.

Literalsorconstant

LiteralsinJavaareasequenceofcharacters(digits,letters,andothercharacters)thatrepresent constant values to be


stored in variables. Java offers following types of literals:
 Integer literals: These are numeric values without a decimal point. Examples of
integerliterals are
1,−34,1098etc.
 Floatingliterals:[Link] literals are
1.99,−34.07,2000.99 etc.
 Characterliterals:Anysinglecharacterenclosedinasinglequote(‘’)is termed
asacharacter
[Link] are‘A’,‘+’,‘’,‘.’etc.
 Stringliterals:Oneormorecharacterenclosedinadoublequote(“”)istermedas a string
literal.
Examplesofstringliteralsare"𝐽𝑎𝑣𝑎𝑃𝑟𝑜𝑔𝑟𝑎𝑚𝑚𝑖𝑛𝑔","5“,"𝐻𝑒𝑙𝑙𝑜𝐽𝑎𝑣𝑎"etc
 Booleanliterals: TheseareliteralswhichacquireBooleanvaluestrueorfalse.
 Null literals: The null in Java is a literal of the null type. It cannot be cast to a
primitive type such asint. float etc, but canbe cast to areference type. Also, nulldoes
not have the value 0 necessarily.
JavaKeywords:
[Link] as constant
or variable or any other identifier names.

Abstract assert boolean break Byte


Case catch char class Const
Continue default do double Else
Enum extends final finally Float
For goto if implements Import
Instanceof int interface long Native
New package private protected Public
Return short static strictfp Super
Switch synchronized this throw Throws

Variables
[Link]
Javahasaspecifictype,whichdeterminesthesizeandlayoutofthe variable'smemory; therange of values
that can be stored within that memory; and the set ofoperationsthatcanbeappliedto [Link]
must declare all variables before they can be used. The basic form of a variable declaration is shown
here:

datatypevariable[=value][,variable[=value]...];

Heredata typeis oneof Java's datatypes and variable is thename of [Link] declare
more than one variable of the specified type, you can use a comma-separated list. Following
are valid examples of variable declaration andinitialization in Java:

inta,b,c; //Declaresthreeints,a,b,[Link]=10,b=10;
//Exampleofinitialization
byteB=22;//[Link]=3.14159;//declaresand assignsa value ofPI.
char a = 'a';// the char variable a is initialized with value 'a'

TherearethreekindsofvariablesinJava:
 Localvariables
 Instancevariables
 Class/staticvariables

Localvariables:
 Localvariablesaredeclaredinmethods,constructors,orblocks.
 Accessmodifierscannotbeusedfor local variables.
 Localvariablesarevisibleonlywithinthedeclaredmethod,constructor or
block.
 There is no defaultvalue for local variablesso local variablesshould
bedeclaredandaninitialvalueshouldbeassignedbeforethefirstuse.
Example
Here, age is a local variable. This is defined inside pupAge() method andits scope is limited
tothis method only.
publicclassTest
{public void aishaniAge() {
int age = 0;
age=age+7;
[Link]("Aishaniageis:"+age);
}
publicstaticvoidmain(Stringargs[]){Test test = new Test();
[Link]();
}
}

Thiswouldproducethefollowingresult:
Aishaniageis:7

Instancevariables:

 Instance variables are declared in a class, but outside a method, constructor or


any block.
 Instance variables are created when an object is createdwiththeuseofthe keyword
'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more thanone
method,constructororblock,oressentialpartsofan object's state that must be
present throughout the class.
 Instancevariablescanbedeclaredinclasslevelbeforeorafteruse.
 Accessmodifierscan begivenforinstance variables.
 The instance variables are visible for all methods, constructors and blockin the
class. Normally, it is recommended to make these variables private (access level).
However visibility for subclasses can be given for these variables with the use of
access modifiers.
 Instance variables have default values. For numbers the default value is 0, for
[Link] be assigned during
the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the
class. Howeverwithinstaticmethodsanddifferentclass( when instance
variablesaregivenaccessibility)shouldbecalledusing the fullyqualifiedname
.[Link].
Example

import [Link].*;
public class Employee{

//this [Link];
//[Link];
//Thenamevariableisassignedintheconstructor.
public Employee (String empName)
{
name=empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal)
{salary=empSal;
}
//Thismethodprintstheemployeedetails.
publicvoidprintEmp(){[Link]("name:"+name);[Link]("salary:"+ salary);
}
publicstaticvoidmain(Stringargs[])
{EmployeeempOne=newEmployee("Ransika");[Link](1000);
[Link]();
}
}
Thiswouldproducethefollowingresult:
name:Ransikasalary:1000.0

Class/staticvariables:

Classvariablesalso knownasstatic variablesaredeclared withthe static keywordina class, but outside a method,
constructor or a block.

 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.
 Staticvariablesarestoredinstaticmemory.
 Itisrareto usestatic variablesother thandeclaredfinalandusedaseither publicor private
constants.
 Staticvariablesarecreatedwhentheprogramstartsand destroyed whentheprogramstops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 [Link],thedefaultvalueis0;for
Booleans,itisfalse;andforobjectreferences,itisnull.
 [Link] values can
be assigned in special static initializer blocks.
 Staticvariablescanbeaccessedbycallingwiththeclassname.
[Link].

Whendeclaringclassvariablesaspublicstaticfinal,thenvariablesnames(constants)areallinupper case. If the static


variables are not
publicandfinalthenamingsyntaxisthesameasinstanceandlocalvariables.

Example

[Link].*;public
class Employee{
//salaryvariableisaprivatestaticvariableprivatestaticdoublesalary;
//DEPARTMENTisaconstant
public static final String DEPARTMENT ="Development"; public
static void main(String args[]){
salary=1000;
[Link](DEPARTMENT+"averagesalary:"+salary);
}
}
Thiswouldproducethefollowingresult:
Developmentaveragesalary:1000

Note:Ifthevariablesareaccessfromanoutsideclasstheconstantshouldbe accessed as
[Link]
MODULE-1 CHAPTERNO–03
OPERATORS
Lecture-9

LearningObjectives:
Thestudentswillbeableto understand:
Operators
PrecedenceofJavaOperators

OperatorsinJava

Operator injavaisasymbolthatisusedtoperformoperationsononeormoreoperands.

Varioustypesofoperatorsinjavaare
ArithmeticOperators
Arithmetic operators are used in mathematical expressions in the same waythat they are used in algebra.
The following table lists the arithmetic operators:Assume integer variable A holds 10 and variable B
holds 20, then:

Operator Description Example


+ Addition-Addsvaluesoneithersideof A+Bwillgive30
theoperator
- Subtraction- Subtract sright hand A-Bwillgive-10
operand from left hand operand
* Multiplication-Multipliesvalues oneither A*Bwillgive200
sideoftheoperator
/ Division-Divideslefthandoperandby B/Awillgive2
righthandoperand
% Modulus-Dividesleft handoperandbyrighthand B%Awillgive0
operand and returns remainder

++ Increment-Increases the value of B++gives21


operandby1
-- Decrement-Decreases thevalueofoperandby1 B--gives19

Example
The following simple example program demonstrates the arithmetic operators. Copyandpastethe
[Link]:
publicclassTest{
publicstaticvoidmain(Stringargs[])
{
inta=10;
intb=20;
intc=25;
intd=25;
[Link]("a+b="+(a+b));
[Link]("a - b = "+(a - b));
[Link]("a * b = "+(a * b));
[Link]("b / a = "+(b / a));
[Link]("b%a="+(b%a));
[Link]("c % a = "+(c % a));
[Link]("a++ = "+(a++));
[Link]("a-- ="+(a--));
// Check the difference in d++ and ++d
[Link]("d++ = "+(d++));
[Link]("++d="+(++d));
}
}

Thiswouldproducethefollowingresult:
a + b =30
a-b=-10
a*b=200
b/a=2
b%a=0
c%a=5
a++=10
a--=11
d++=25
++d=27
RelationalOperators

TherearefollowingrelationaloperatorssupportedbyJavalanguage:Assumevariable
Aholds10andvariableBholds20,then:
Operator Description Example

== Checksifthevaluesoftwooperandsareequal or not, (A==B)isnot


ifyes then condition becomes true.
true.
!= Checksifthevaluesoftwooperandsare equalor not, (A != B) is
if values are not equal then condition becomes
true.
true.
> Checks if the value of left operand is greater (A>B)isnot true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operandislessthan (A < B) is
thevalueofrightoperand,ifyesthencondition
true.
becomes true.
>= Checks if the value of left operand is greaterthan (A >= B) is not
or equal to the value of right operand, if yes true.
thenconditionbecomestrue.
<= Checksif thevalueofleftoperandislessthan or (A <= B) is
equal to the valueofrightoperand,ifyes then
true.
condition becomes true.

Example
The following simpleexample programdemonstrates the relational [Link]
[Link] program.:
publicclassTest{
publicstatic voidmain(Stringargs[])
{int a=10;intb=20;[Link]("a == b = "+(a == b));
[Link]("a!=b="+(a!=b));
[Link]("a>b="+(a>b));
[Link]("a < b = "+(a < b));
[Link]("b >= a = "+(b >= a));
[Link]("b<=a="+(b<=a));
}}
Thiswouldproducethefollowingresult:
a == b=false
a != b
=truea>b=fal
se
a<b=true
b >= a=true
b<=a=false
BitwiseOperators
Javadefinesseveralbitwiseoperators,whichcanbeappliedtotheintegertypes,long,int,short,char,
[Link]-by-bitoperation.
Assumeifa=60;andb=13;
Thefollowingtableliststhebitwiseoperators:
AssumeintegervariableAholds60andvariableBholds13,then:

Operator Description Example


<< Binary Left Shift Operator. The left operands A<<2willgive240
value is moved left by the number of bits
whichis11110000
specifiedbytheright operand.

>> Binary Right Shift Operator. The leftoperands A>>2willgive15


value is moved right by the number of bits
whichis1111
specifiedbytheright operand.

>>> Shift right zero fill operator. The left operands A>>>2willgive15
value is moved right by the number of bits
whichis00001111
specifiedbytherightoperandandshifted
valuesarefilledupwithzeros.

Example

publicclassTest
{publicstaticvoidmain(Stringargs[])
{
inta=60;/*60=00111100*/
intb=13; /*13=00001101*/
intc=0;
c=a<<2;/*240=11110000*/
[Link]("a<<2="+c);
c = a >>2; /* 215 = 1111 */
[Link]("a>>2="+c);
c=a>>>2;/*215=00001111*/
[Link]("a>>>2="+c);
}
}
Thiswouldproducethefollowingresult:

a<<2=240
a>>15
a>>>15

LogicalOperators
Thefollowingtableliststhelogicaloperators:
AssumeBooleanvariablesAholdstrueandvariableBholdsfalse,then:

Operator Description Example


&& [Link] (A&&B)
arenon-zero,thentheconditionbecomestrue. isfalse.
|| [Link] operandsarenon- (A||B)istrue.
zero,thentheconditionbecomestrue.
! [Link] !(A&&B)istrue.
[Link]
thenLogicalNOToperatorwillmakefalse.

Example
[Link]:

publicclassTest{
publicstaticvoidmain(Stringargs[]){
boolean a =true;
booleanb=false;
[Link]("a&& b = "+(a&&b));
[Link]("a||b = "+(a||b)); [Link]("!(a &&
b) ="+!(a && b));
}}
Thiswouldproducethefollowingresult:

a&&b=false a
|| b =true
!(a&&b)=true

AssignmentOperators
TherearefollowingassignmentoperatorssupportedbyJavalanguage:

Operator Description Example


= Simple assignment operator, Assigns C = A + B willassign
values from rightsideoperands toleftside operand value of A + B into C

+= Add AND assignment operator, It addsright C+=Aisequivalent to C =


operand to the left operand and C+A
assigntheresulttoleftoperand
-= Subtract AND assignment operator, It subtracts C-=AisequivalenttoC
right operand from theleft =C-A
operandandassigntheresulttoleft operand
*= MultiplyANDassignmentoperator,Itmultipliesright C*=Aisequivalentto C =
operandwiththeleftoperand C*A
andassigntheresulttoleft operand

/= Divide AND assignment operator,It divides left C/=Aisequivalent to C =


operandwiththerightoperandandassignthe result to C / A
left operand

%= ModulusANDassignmentoperator,Ittakesmodulu C %= A is equivalent toC


susingtwooperandsandassign the result to left =C%A
operand

Example
[Link] program:
publicclassTest{
publicstaticvoidmain(Stringargs[])
{inta=10; intb=20; int c=0;c=a+b; [Link]("c
=a+b="+c);
c+=a;
[Link]("c+=a="+c);c -= a ;
[Link]("c-=a ="+c );
c*=a;
[Link]("c*=a="+c);
\a=10;
c=15;
c/=a;
[Link]("c/=a="+c);
a=10;
c =15;
c%=a;
[Link]("c%=a="+c);
}}
Thiswouldproducethefollowingresult:

c = a + b =30
c += a =40
c-=a=30
c*= a =300
c /= a =1
c%=a=5

ConditionalOperator(?:)

Conditionaloperatoris alsoknownas [Link] operatorconsists ofthree operands


[Link]
[Link]:
variablex=(expression)?valueiftrue:valueiffalse

Example
publicclassTest{
publicstaticvoidmain(Stringargs[])
{inta,b;
a=10;
b=(a==1)?20:30;
[Link]("Valueofbis:"+b);
b=(a==10)?20:30;
[Link]("Valueofbis:"+b);
}}
Thiswouldproducethefollowingresult:

Value of b is:30
Valueofbis:20

PrecedenceofJavaOperators:
Operator precedence determines the grouping of terms in an expression. Thisaffectshowan expression is
evaluated. Certain operators have higher precedence than others; for example, the
multiplicationoperatorhashigherprecedencethantheadditionoperator:Forexample,x=7+3* 2; here, x is
assigned 13, not 20 because operator * has higher precedence than +, so it first gets
multipliedwith3*[Link],operatorswiththehighestprecedenceappearatthe
topofthetable,[Link],higher precedence operators
will be evaluatedfirst.
Category Operator Associativity
Postfix ()[].(dotoperator) Lefttoright
Unary ++--!~ Righttoleft
Multiplicative */% Lefttoright
Additive +- Lefttoright
Shift >>>>><< Lefttoright
Relational >>=<<= Lefttoright
Equality ==!= Lefttoright
BitwiseAND & Lefttoright
BitwiseXOR ^ Lefttoright
BitwiseOR | Lefttoright
LogicalAND && Lefttoright
LogicalOR || Lefttoright
Conditional ?: Righttoleft
Assignment =+=-=*=/=%=>>= Righttoleft
<<=&=^=|=
Comma , Lefttoright
MODULE-1 CHAPTERNO–03
ControlStatements
Lecture-10

LearningObjectives:

Thestudentswillbeableto understand:

JavaControlStatements
Selection/ Decisionmaking
Iteration/Loopstatement
jump

Java’sControlStatements

The JAVA control statements inside a program are usually executed sequentially. Sometimes a programmer
wantstobreakthenormalflowandjumptoanotherstatementorexecuteasetofstatementsrepeatedly. The statements
which break the normal sequential flow of the program are called control statements. Java’s
programcontrolstatements can be put intothe following categories: selection ordecision making statement,
iteration or loop statement, and jump.

Selection/Decisionmakingstatement
ASelection ordecision makingstatement allowsprogramto choosedifferentpathsofexecution based upon the
truth value of an expression.

Therearetwotypesofdecisionmakingstatements inJava. Theyare:

 ifstatements
 switchstatements
Differenttypesofselectionordecisionstatementsinjavaare:

ifStatement
Thisstatementisusedwhenthedecisionis madetakingonlyonecondition intoconsideration.

Syntax:
if(condition)
{//Thesecodesareexecutedwhenconditionis true
}
Example

publicclassTest{
publicstaticvoidmain(Stringargs[]){int x=10; if(
x <20){
[Link]("Thisisifstatement");
}}}
Thiswouldproducethefollowingresult:

Thisisifstatement

Example
Writeaprogramtoinputanintegerfromkeyboardanddisplay itifitis positive.

Solution:
// [Link]
[Link].*;class
DispPositive
{publicstaticvoidmain(Stringargs[])
{int n;
[Link]("Enteraninteger:");Scanner
input = new Scanner([Link]);n =
[Link]();
if(n>0)
{
[Link]("Theinteger="+n);

}
}}

Output:
Enteraninteger:
7
Theinteger=7

ifelsestatement
Thisstatementisusedwhenthedecisionis madetakingexactlytwoconditions intoconsideration.
Syntax:
if(condition)
{
//Thesecodesareexecutedwhenconditionis true
}
else
{
//Thesecodesareexecutedwhenconditionisfalse
}

Example
publicclassTest{

publicstaticvoidmain(Stringargs[]){int x=30;
if(x <20){
[Link]("Thisisifstatement");
}else
{
[Link]("Thisiselsestatement");
}}}
Thiswouldproducethefollowingresult:

Thisiselsestatement

Example
Writeaprogramtoinput anintegerfromkeyboard and checkwhetherit isevenorodd. Solution:
// [Link]
[Link].*;class
IsEvenOdd
{
publicstaticvoidmain(Stringargs[])
{
intn;
[Link]("Enter an integer:");
Scannerinput=newScanner([Link]); n
= [Link]();
if(n%2==0)
{
[Link](n+"isaneveninteger");
}
else
{
[Link](n+"isanoddinteger");
}}}

Output:
Enteraninteger: 7
7is anoddinteger

if-else-ifstatement
Thisstatement isusedwhenthedecisionismadetaking morethantwoconditionsinto
consideration.
Syntax:
if (condition1)
{
//Thesecodesareexecutedwhencondition1istrue
}
elseif(condition2)
{
//Thesecodesareexecutedwhencondition2istrue
}
………………………..
……………………
…..else
{
//Thesecodesareexecutedwhenallconditionsarefalse
}
Example

publicclassTest{
publicstaticvoidmain(Stringargs[]){int x=30; if(
x ==10){
[Link]("ValueofXis10");
}elseif(x==20){[Link]("ValueofXis20");
}elseif(x==30){[Link]("ValueofXis30");
}else{[Link]("Thisiselsestatement");
}
}
}
Thiswouldproducethefollowingresult:

ValueofXis30

Example
Writeaprogramtocalculatedivisionobtainedbyastudentwithhisaveragemarkentered through the
keyboard as per following rules:
𝐩𝐞𝐫𝐜𝐞𝐧𝐭𝐚𝐠𝐞𝐦𝐚𝐫𝐤≥𝟔𝟎,1stdivision

𝟓𝟎≤𝐩𝐞𝐫𝐜𝐞𝐧𝐭𝐚𝐠𝐞𝐦𝐚𝐫𝐤<60,2nddivision

𝟒𝟎≤𝐩𝐞𝐫𝐜𝐞𝐧𝐭𝐚𝐠𝐞𝐦𝐚𝐫𝐤<50,3rddivision
𝟐𝟎≤𝐩𝐞𝐫𝐜𝐞𝐧𝐭𝐚𝐠𝐞𝐦𝐚𝐫𝐤<50,Fail

Solution:
//[Link]
[Link].*;class
FindDivision
{
publicstaticvoidmain(Stringargs[])
{
intavg_mark;
[Link]("Enteraveragemark:");
Scanner input = new Scanner([Link]);
avg_mark = [Link]();
if(avg_mark>=60)
{
[Link]("1stDivision");
}
elseif(avg_mark>=50&&avg_mark<60)
{
[Link]("2ndDivision");
}
elseif(avg_mark>=40&&avg_mark<50)
{
}
else
{
[Link]("3rdDivision");
}
}
}

Output:
Enteraveragemark: 75
1stDivision

Nestedif-elsestatement

Thisstatementisusedwhenthedecisionismadetakingoneiforelseifstatementinsideanotherif or else
if statement.
Syntax:

Thesyntaxforanestedif...elseisasfollows:
if(condition1)

{
//Executeswhenthecondtition1istrue

if(condition2)
{

//Executeswhenthecondition2istrue}}

Example

publicclassTest{
publicstaticvoidmain(Stringargs[]){int x=30; int
y =10;
if(x==30){
if(y==10){
[Link]("X=30andY=10");
}
}
}

Thiswouldproducethefollowingresult:

X=30andY=10

Switchcasestatements
The switch statement is Java’s multi way branch statement. It provides an easywayto dispatch execution
to different parts of your code based on the value of an expression. As such, it often provides abetter
alternative to a large series of if-else-if statements.

Syntax:
switch(expression)
{
casevalue1:
//Thesecodesareexecutedwhenvalueofexpressionisvalue1 break;
casevalue2:
//Thesecodesareexecutedwhenvalueofexpressionisvalue2 break;
...……………..
. .................. casevalueN:
//ThesecodesareexecutedwhenvalueofexpressionisvalueN break;
default:
//Thesecodesareexecutedwhenvalueofexpressionisotherthanabovecasevalues
}

Example

Write a program to display amonth name, if its corresponding integervalue isenteredthroughthe


keyboard. Integer 1 corresponds to January, 2 corresponds to February and so on.
Solution:
//[Link]
[Link].*;
classFindYear
{
publicstaticvoidmain(Stringargs[])
{
intm;
[Link]("Enteraninteger:");Scanner input=newScanner([Link]);m= [Link]();
switch(m)
{
case 1: [Link]("January");
break;
case 2: [Link]("February");
break;
case 3:
[Link]("March");
break;
case 4: [Link]("April");
break;
case 5:
[Link]("May");
break;
case 6: [Link]("June");
break;
case7: [Link]("July");
break;
case 8: [Link]("August");
break;
case 9: [Link]("September");
break;
case 10: [Link]("October");
break;
case 11:
[Link]("November");break;
case 12:
[Link]("December");break;
default:[Link]("Invalidmonth");
}
}
}

Output:
Enteraninteger:9 September
MODULE-1 CHAPTERNO–03
ControlStatements
Lecture-11

LearningObjectives:
Thestudentswillbeableto understand
Iteration/Loopstatement
Whileloop
Do-whileloop
Forloop
jump

Iteration/Loopstatements
Aniterationorloopstatementallowsprogramexecutiontorepeatoneormorestatementsmany number of time based
upon some condition.

Java’s iteration statements are for, while, and do-while. These statements create what we commonly call
loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination
condition is met.
whileloop

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its
controlling expression is true.
The condition can be any Boolean expression. The body of the loop will be executed as long asthe
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop.

Note:Thecurlybracesareunnecessaryifonlyasinglestatementisbeing repeated.

Syntaxofwhile loop:
initialization;
while(condition)
{
//thesecodesareexecutedineachiterationoftheloop
//incrementordecrementstatementwhichadvancestheloop;
}
Example
publicclassTest{
publicstaticvoid main(String args[]){int x=10;
while( x <20){ [Link]("value of x : "+x
); x++;
[Link]("\n");
}
}
}
Thiswouldproducethefollowingresult:

value of x:10 value of


x :11 value of x :12
value of x:13 value of
x :14 value of x :15
value of x:16 value of
x :17 value of x :18
value of x:19
Example
Writea programto displaythesquareandcubeofallintegersfrom1to n,foranypositiveinteger.

Solution:
//[Link]
[Link].*;class
SquareCube1toN
{
publicstaticvoidmain(Stringargs[])
{intn,i=1,s,c;
[Link]("Enterapositiveinteger:");Scannerinput
=newScanner([Link]);
n = [Link](); [Link]("Integer\t\tSquare\t\tCube");
while(i<=n)
{
s=i*i;
c=i*i*i;
[Link](i+"\t\t"+s+"\t\t"+c);i++;
}}}
Output:
Enterapositiveinteger: 10
Integer Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

dowhileLoop
If the conditional expression controlling a while loop is initially false, then the body of the loop
will notbe executed at all. However, sometimes itis desirable to execute the body of a while loop
at least once, even if the conditional expression is false to begin with. The do-while loop always
executes its body at least once, because its conditional expression is at the bottom of the loop.

Syntaxofdowhileloop:
initialization;
do

{
// body of
loop
Increment/
decrement;
}while(condition);

Example
publicclassTest{
publicstaticvoidmain(Stringargs[]){int
x=10;
do{
[Link]("value of x : "+ x );x++;
[Link]("\n");}while( x <20);
Thiswouldproducethefollowingresult:
valueofx:10valueofx :11
value of x:12 value of x:13 valueofx :14 valueofx :15 value of x :16value of x:17 value of x
:18 value of x :19

Example1.20

Writea programto find factorialofa positiveintegergiven fromthe keyboard.

Solution:
//[Link]
import
[Link].*;class
Factorial
{
publicstaticvoidmain(String[]args)
{int n,i=1;longfact=1;
[Link]("Enterapositiveinteger:");
Scanner input = new Scanner([Link]);
n=
[Link]();do
{
fact=fact* i;
i++;
}while (i<=n);
[Link]("Factorialof"+ n+"is:"+ fact);
}
}

Output:
Enterapositiveinteger: 7
Factorialof7is5040
MODULE-1 CHAPTERNO–03
ControlStatements&Typecasting
Lecture-12

LearningObjectives:
Thestudentswillbeableto understand
3.7.2.3Forloop
jump
Typecasting
3.7.2.3forloop

Thisloopisthemost popularloop.
Syntaxofforloop:
for(initialization;condition;iteration)
{
//thesecodesareexecutedineachiterationoftheloop
}
.
Example
publicclassTest{
publicstaticvoidmain(Stringargs[])
{
for(intx=10;x<20;x=x+1)
{
[Link]("value of x : "+ x );
[Link]("\t");
}}}

Thiswouldproducethefollowingresult:
valueof x:10valueofx:11valueofx:12valueofx:13valueofx:14valueofx:15
Example
Write aprogramtoprint alleven integersfrom 1ton, forany positiveintegern inputthroughthe
keyboard.

Solution:
//[Link]
va import
[Link].*; class
Integers1toN
{
publicstaticvoidmain(Stringargs[])
{
intn,i;
[Link]("Enterapositiveinteger:");
Scanner input = new Scanner([Link]);
n=[Link]();
[Link]("Evenintegersfrom1to"+n+"are:");for(i=1;
i<=n; i++)
{
if(i%2==0)
{
[Link](i+"\t");
}
}
}
}

EnhancedforloopinJava:

[Link].
Syntax:

for(declaration:expression)

{
//Statements
}
 Declaration: The newly declared block variable, which is of a typecompatible
with the elements of the array you are accessing. The variable will beavailable
withintheforblockanditsvaluewouldbethesameasthecurrentarray element.
 Expression: This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.

Example
publicclassTest{
publicstaticvoidmain(Stringargs[]){int[]numbers={10,20,30,40,50};for(int x: numbers ){
[Link](x); [Link](",");
}
[Link]("\n");
String[]names={"khusi","liza","lishi","lipi"};for(String name
: names ){
[Link](name); [Link](",");
}
}}
Thiswouldproducethefollowingresult:
10,20,30,40,50,
Khusi,liza,lishi,lipi

breakKeyword:
Thebreakkeywordisusedto [Link] any loop
or a switch statement.
Thebreakkeywordwillstoptheexecutionoftheinnermostloopandstartexecutingthe next
line of code after the block.

Syntax:
Thesyntax of a break is a single statement insideany loop: break;
Example
publicclassTest{
publicstaticvoidmain(Stringargs[]){int[]
numbers ={10,20,30,40,50};
for(int x : numbers){
if(x ==30){ break;
}
[Link](x);
[Link]("\t");
}}
}
Thiswouldproducethefollowingresult:
10 20

continueKeyword:

[Link] immediately jump to the


next iteration of the loop.
Inaforloop,thecontinuekeywordcausesflow ofcontroltoimmediatelyjumptotheupdatestatement. In a
while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:
The syntaxofacontinueisasinglestatementinsideanyloop:continue;
Example

publicclassTest{

publicstaticvoidmain(Stringargs[]){int[]
numbers ={10,20,30,40,50}; for(int x :
numbers){
if(x==30){
continue;
}
[Link]( x );
[Link]("\t");}}}
Thiswouldproducethefollowingresult:
10 20 40 50

3.7.2JumpStatements

[Link] following jump


statements:
breakstatement:A breakstatementtakestheprogramcontrol outof [Link] breakstatementis used,
program control immediately jump to the statement immediately follows the loop statement.

continuestatement:Acontinuestatementtakescontroltothebeginningofthe loop.

Note:gotostatementisnotsupportedbyjava.

Example
Writeaprogramtocheckwhetheranintegerenteredthroughkeyboardisprimeornot.
Solution:
//[Link]
a import
[Link].*;class
checkPrime
{publicstaticvoidmain(Stringargs[])
{int n,i;
[Link]("Enter an integer:");
Scannerinput=newScanner([Link]); n
= [Link]();
for(i=2;i<n; i++)
{if(n%i==0)
{
[Link](n+"isnotPrime");
break;

}}
if(i==n)
[Link](n+"isPrime");
}}
Output:
Enteraninteger:
11
11is Prime

3.7.4Typecasting

The methodofconvertingoneprimitivedatatype intoanotherdatatype iscalledtypecasting. There are


twotypes of typecasting: implicit type casting and explicit type casting.
Implicittypecastingorwideningcasting
Thisistheprocessofconverting asmallertypeto alarger type.
𝑏𝑦𝑡𝑒→𝑠ℎ𝑜𝑟𝑡→𝑐ℎ𝑎𝑟→𝑖𝑛𝑡→𝑙𝑜𝑛𝑔→𝑓𝑙𝑜𝑎𝑡→𝑑𝑜𝑢𝑏𝑙𝑒
This is done automatically bythe compiler. Hence it is also knownas implicit type casting. The
implicit typecasting is demonstrated below.

Example

Writeaprogramtodemonstratetheuseofimplicittypecasting.

Solution:
//[Link]
public class
ImplicitTC
{publicstaticvoidmain(String[] args)
{
intmyInt =9;
double myDouble = myInt; //Automaticcasting:inttodouble
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}

Output:
9
9.0
}

Explicit typecastingornarrowing casting


This type casting is done manually byplacing the type in parentheses in front ofthe value. This is
[Link]
typecastingisdemonstratedbelow.
Example

Writeaprogramtodemonstratetheuseofexplicittypecasting. Solution:
//[Link]
public class

ExplicitTC
{publicstaticvoidmain(String[] args)
{
doublemyDouble= 9.78;
int myInt = (int) myDouble; //Manualcasting:doubletoint
[Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9
}}

Output:
9.78
9

CommentsinJAVA
The java comments are statements that arenot executed bythe compiler and interpreter. The comments can
be used to provide informationorexplanationaboutthe variable, method, [Link] canalso be
used to hide program code for specific time.
InJavathereare threetypes ofcomments:
 Singlelinecomments
 Multilinecomments
 Documentationcomments
MODULE-1 CHAPTERNO–03
TakinginputfromKeyboard
Lecture-13

LearningObjectives:
Thestudentswillbeableto understand
Givinginputtoajavaprogram
Commandlinearguments
Scannerclass
BufferedReaderclass

Givinginputtoajavaprogram
Taking input fromkeyboardisoneofthe most essentialpartsofaprogramming language. Injava, inputcanbe taken from
the keyboard using either of these following methods:

Commandlineargumentmethod

The command line arguments are the arguments that we pass during the execution ofa program. Accessing
command line arguments inside a java program is quite easy. They are stored in the String array (named
args[] inourexamples. 1st argument isstoredinargs[0],2nd argument isstored inargs[1] and soon)which
ispassed as a parameter to the main() method. It is clearly explained in the following example.

ExampleWriteaprogramtofindadditionoftwointegers,wheretheinputsaregivenascommand line arguments.

Solution:
//[Link]
class CommandLine
{
publicstaticvoidmain(Stringargs[])
{
int x, y, res;
x=[Link](args[0]);
y=[Link](args[1]);
res=x+y;
[Link]("Requiredadditionresultis"+res);
}
}
Output:
E:\JAVA>javaCommandLine65111
Requiredadditionresultis 176

Explanation:
The inputs given during program execution get stored as string value in args[0] & args[1]
[Link]()methodisusedtoconvertstringtoitscorresponding
integer.

Scannerclassmethod
Scanner [Link] forobtainingthe inputoftheprimitivetypeslike int,double,etc. and
strings. It is the easiest way to read input in a Java program, though not very efficient if we want an
inputmethod for scenarios where time is a constraint like in competitive programming.

 To create anobject ofScanner class, we usuallypass the predefined object [Link], which
representsthestandard input stream. We maypass anobject ofclass File ifwewantto read
input from a file.
 To read numerical values of a certain data type xyz, the function to use is nextXyz(). For
example, to readavalue oftype short, we canuse nextShort(). To read an integer value,
weuse nextInt(). To reada longvalue we use nextShort(). To read a double value, we use
nextDouble() and so on.
 Toreadstrings,weusenextLine().
 To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) function returns the first character in that
string.

Example1.29

Writea programtofindadditionoftwointegers,wheretheinputsaregivenfromthekeyboard.

Solution:
//[Link]
import [Link].*;
class InputScanner
{
publicstaticvoidmain(Stringargs[])
{
intx,y,res;
[Link]("Entertwointegers:");
Scannerinput=newScanner([Link]);x=[Link](); y =
[Link]();res=x+y;
[Link]("Requiredadditionresultis"+res);
}
}

Output:
Entertwointegers:
67 89
Requiredadditionresultis156

BufferedReaderclassmethod
It is the most efficient methodofreading inputs fromthe keyboard. This is the Java classicalmethodtotake
input, Introduced in JDK1.0. This method is used by wrapping the [Link] (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the
command line. The main demerit is that wrapping code is hard to remember and we have to import built in
package [Link].

Example1.30

Writeaprogramtofindadditionoftwonumbersgivenfromthekeyboard,usingBufferedReader class method.


Solution:
[Link].*;
classBufferedReaderAddition
{
publicstaticvoidmain(Stringargs[])
{BufferedReaderbr=newBufferedReader(newInputStreamReader([Link]));
String
str;int
x,y,z;
try
{[Link]("Enter1stnumber:");
str=[Link]();x=[Link](str);[Link]("Enter2ndnumber:"); str
= [Link](); y=[Link](str);
z=x+y;
[Link](“AdditionResultis:”+z);
}
catch(Exceptione)
{
[Link]("InvalidNumber..TryAgain!!!!!!!");
}
}
}

Output:
Enter1stnumber:
45
Enter2ndnumber:
89
AdditionResultis: 134
MODULE-1 CHAPTERNO–03
JavaArrays
Lecture-14

LearningObjectives:

Thestudentswillbeableto understand
Arrayinjava
Declarationandcreationofarray
Programson1D arrays
Passingarrayto methods

Arrayinjava
 Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of
the same type.

 An array is used to store a collection of data, but itis often more useful to think of an array as a collection
of variables of the same type.

 Instead ofdeclaring individual variables, suchas number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.

Declarationandcreationofarray
 To use an array in a program, you must declare a variable to reference the array, and you must specify
the type of arraythe variable can reference. Here is the syntax for declaring an array variable

Syntax
Datatype[]arrrefvar;//preferredway Or
Datatypearrrefvar[];//worksbutnotpreferredway
Creationofarray
Syntax
arrayrefvar=newdatatype[arraysize];
Theabovestatementdoestwo things
 ItcreatesanarrayusingnewdataType[arraySize].

 Itassignsthe reference ofthe newlycreatedarraytothe variable arrayRefVar.

Declaringanarrayvariable, creatinganarray, and assigningthereferenceofthearraytothevariable canbe combined in


one statement, as shown below
Syntax
Datatype[]arrayrefvar=newdatatype[arraysize];

Example
Followingstatementdeclaresanarrayvariable,myList,createsanarrayof10elementsofdoubletypeandassignsits reference to
myList

Double[]myList=newdatatype[9];
Following picture represents array myList. Here, myListholds ten double values and theindices are from 0 to 9.

Programson1Darrays
Example
Thefollowingcodedisplays alltheelementsinthearraymyList

publicclassTestArray{

publicstaticvoidmain(String[]args) {
intn;
Scanners=newScanner([Link]);
[Link]("[Link]:"); n =
[Link]();
double myList[] = new double[n];
[Link]("Enteralltheelements:"); for
(int i = 0; i <n; i++)
{
myList[i]=[Link]();
}

//Printallthearrayelements

for(doubleelement:myList){ [Link](element);
}
}
}

Thiswillproducethefollowingresult−

Output
1.9
2.9
3.4
3.5

Example

Writeaprogramtosorttheelementsinan1Darray? Solution

import [Link];
publicclassAscending_Order
{
publicstaticvoid main(String[]args)
{
intn,temp;
Scanners=newScanner([Link]);
[Link]("[Link] inarray:"); n =
[Link]();
int a[] = new int[n];
[Link]("Enteralltheelements:");
for (int i = 0; i < n; i++)
{
a[i]=[Link]();
}
for(int i=0;i<n;i++)
{
for(intj=i+ 1;j<n;j++)
{
if(a[i]> a[j])
{
temp=a[i]; a[i]
= a[j];
a[j]=temp;
}
}
}
[Link]("AscendingOrder:");
for (int i = 0; i <= n - 1; i++)
{
[Link](a[i]+",");
}

}
}

Input Output
478 432
786 478
432 561
561 786

Passingarraytomethods

Justasyoucanpassprimitivetypevaluestomethods,youcanalsopassarraysto methods. For


example, the following method displays the elements in an int array.
Example
Writeaprogramtosort theelementsinan1Darraybypassingarraytomethods?
Solution
publicclasssortNumbers
{
publicstaticvoidmain(String[]args)
{
int[]data={40,50,10,30,20,5};
[Link]("UnsortedListis:");
display(data);
sort(data);[Link]("\nSorted
Listis:"); display(data);
}
publicstaticvoiddisplay(intnum[])
{
for(int i=0; i<[Link];i++)
[Link](num[i]+"");
}
publicstaticvoidsort(intnum[])
{
inti,j, temp;
for(i=0;i<[Link]-i;i++)
{
for(j=0;j<[Link]-i-1;j++)
{
if(num[j]>num[j+1])
{
temp = num[j];
num[j]=num[j+1];
num[j+1] = temp;
}
}
}
}
}

Input Output
40 5
50 10
10 20
30 30
20 40
5 50
MODULE-1 CHAPTERNO–03
JavaArrays
Lecture-15

LearningObjectives:

Thestudentswillbeabletounderstand
Returningarrayto methods
MultidimensionalArray
Arrayofobjects
Returningarraytomethods
Amethodmayalso returnanarray. For example, the following methodreturnsanarraythat isthereversalof another
array.

publicclass ArrayReturn1
{
publicstaticdouble[]returnArray()
{
double[]x;

x = new double[3]; //Createanarrayof3elements

x[0] = 2.3;
x[1]=3.4;
x[2]=4.5;

return(x); //Returnthe**reference**(location) ofthearray


}

publicstaticvoidmain(String[]args)
{
double[]a;

a=returnArray();

[Link]("ArrayAFTERcallingreturnArray:");

for(int i=0;i<[Link];i++)
[Link]( a[i] );
}
}
Output
2.3
3.4
4.5

MultidimensionalArray

SyntaxtoDeclareMultidimensionalArrayinjava

1. dataType[][]arrayRefVar;(or)
2. dataTypearrayRefVar[][];(or)
3. dataType[]arrayRefVar[];

Exampleto instantiateMultidimensionalArrayin java

1. int[][]arr=newint[3][3];//3rowand3column

Example to initialize Multidimensional Array in java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example

Writeaprogramtodeclare,instantiate,initializeandprintthe2Dimensionalarray.

classTestarray3{
publicstaticvoidmain(Stringargs[]){
//declaringand initializing2Darray
intarr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing2Darray
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+"");
}
[Link]();
}
}}

Example

Writeaprogramtoprinttheelementsinmatrix.

import [Link];

publicclassJavaProgram
{
publicstaticvoidmain(Stringargs[])
{
introw,col,i,j;
intarr[][]=newint[10][10];
Scannerscan=newScanner([Link]);

[Link]("EnterNumberofRowforArray(max10) :"); row =


[Link]();
[Link]("EnterNumberofColumnforArray(max10):"); col
= [Link]();

[Link]("Enter"+(row*col)+"ArrayElements:"); for(i=0;
i<row; i++)
{
for(j=0;j<col;j++)
{
arr[i][j]=[Link]();
}
}

[Link]("TheArrayis:\n");
for(i=0; i<row; i++)
{
for(j=0;j<col;j++)
{
[Link](arr[i][j]+"");
}
[Link]();
}
}
}

Arrayofobjects
Anobject ofclassrepresentsasinglerecord in memory, ifwewant morethanonerecord ofclasstype, wehave to
create an arrayofclass or object. As we know, an array is a collection ofsimilar type, therefore an array can be a
collection of class type.

Syntaxforcreating an arrayof object

classClassName
{
datatypevar1;
datatypevar2;
----------
datatypevarN;

method1();
method2();
----------
methodN();
}

Class-Name[]object=newClass-Name[size];

Example
Writeaprogramtoprintname,ageandsalayofthreeemployees.
Solution
[Link];

classEmployee
{
intId;
StringName;
int Age;
longSalary;

voidGetData() //DefiningGetData()
{
Scannersc=newScanner([Link]);

[Link]("\n\tEnterEmployeeId:"); Id
= [Link]());

[Link]("\n\tEnterEmployeeName:");
Name = [Link]();

[Link]("\n\tEnterEmployeeAge:");
Age = [Link]();

[Link]("\n\tEnterEmployeeSalary:"); Salary
= [Link]());

voidPutData() //DefiningPutData()
{
[Link]("\n\t"+Id+"\t"+Name+"\t"+Age+"\t"+Salary);
}

publicstaticvoidmain(Stringargs[])
{

Employee[]Emp=newEmployee[3]; int
i;

for(i=0;i<3;i++)
Emp[i]=newEmployee(); //Allocatingmemorytoeachobject

for(i=0;i<3;i++)
{
[Link]("\nEnterdetailsof"+(i+1)+"Employee\n");
Emp[i].GetData();
}

[Link]("\nDetailsofEmployees\n");
for(i=0;i<3;i++)
Emp[i].PutData();

}
}

Name Age Salary


[Link] 45 65000
ShiveMukharjee 29 38000
BhumiSitrang 35 43000

1. Defineliteralsinjava.
Ans : Literal in Java isa synthetic representation of boolean, numeric, character, or string data. It is a means
ofexpressing particular values in the program, such as an integer variable named ''/count is assigned an
integer value in the following statement. int count = 0; A literal '0' represents the value zero.
2. What arebit wiseoperators?
Ans : In Java, bitwise operators perform operations on integer data at the individual bit-level. Here, the
integer data includes byte , short , int , and long types of data. There are 7 operators to perform bit-level
operations in Java. Operator.
3. Whyjavadoesnotprovideanydestructor?
Ans : Java has its own garbage collection implementation so it does not require any destructor like C++ .
This makes Java developer lazy in implementing memory management. Still we can have destructor along
with garbage collector where developer can free resources and which can save garbage collector's work.
4. Whyjavacharacterstakes2byte unlikec/c++,whichtakes1 byteof memory?
Ans : It is because java uses Unicode system, not ASCII (American Standard Code for Information
Interchange) code system. Unicode system represents a character set which can be used to represent all
languages available world. \u0000 is the lowest range of Unicode system.

10. DefineConstructor.
Ans: A constructor in Java isa special method that is used to initialize objects. The constructor is called
when an object of a class is created.

5. [Link] dynamicallytoanobject ofaclass?

Ans : A class can be defined as a template/blueprint that describes the behavior/state that the object of its
type [Link] memory is only allocated to the variables of the class when the object is created. The
memory is not allocated to the variables when the class is declared. At the same time, single variables can
have different values for different objects, so every object has an individual copy of all the variables of the
class.
6. Defineastaticmethod
Ans:Astatic method(orstatic function) is amethoddefinedasa memberofanobject but isaccessible
directlyfroman API object'sconstructor,ratherthan fromanobject instance created via the constructor.
7. Whyjavaiscalledaportablelanguage?
Ans :Java isknownasa"portable language" because Javacodecanexecuteonallmajor platforms. What's more,
once you've compiled your Java source to "byte-code" .
8. Whyjavaiscalled arobust language?
Ans : Java is robust because it utilizes strong memory management. There is an absence of pointers that
bypasses security dilemmas. There is automatic garbage collection in Java which runs on the Java Virtual
Machine to eliminate objects which are not being accepted by a Java application anymore.
9. Whyjavaiscalled adynamiclanguage?
Ans : Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount ofrun-time information that can be used to
verify and resolve accesses to objects at run-time.

10. Whyjavaisarchitectureneutral?
Ans : Unlike many other programming languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform-independent byte code.
11. WhatisJDK, JIT&JRE?
Ans : Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK)
contains JRE along with various development tools like Java libraries, Java source compilers, Java
debuggers, bundling and deployment tools. Just InTime compiler (JIT) is runs afterthe programhas started
executing, on the fly.

12. Definemultithreading.
Ans : Multithreading is the ability of a program or an operating system to enable more than one user at a
time without requiring multiple copies of the program running on the computer. Multithreading can also
handle multiple requests from the same user.
13. WhoisthefatherofJAVA?
Ans : James Gosling OC (born May19, 1955), often referred to as "Dr. Java," is a Canadian computer
scientist, best known as the founder and lead designer behind.
19. Whyjavaiscalledaplatformindependentlanguage?
Ans:Java is platform-independent because it uses a virtual machine. The Java programming language and
all APIs are compiled into bytecodes. Bytecodes are effectively platform-independent. The virtual machine
takes care of the differences between the bytecodes for the different platforms.
20. Whyjavaiscalledwriteoncerunanywherelanguage(WORA)?
Ans : ava applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system without any
adjustment.
21. DefineJVM.
Ans:AJava virtualmachine(JVM) isavirtualmachinethat enablesacomputertorunJavaprograms as well
as programs written in other languages that are also compiled to Java bytecode.

LongTypeQuestions

1. Whatisconstructoroverloading?Discusswithanexample.
2. Discussthefeaturesofjava whichmakesitapowerfullanguage.
3. WhatisJVM?ExplainthearchitectureofJVMwiththehelpofaneatdiagram.
4. DifferentiatebetweenC++andJAVAindetails.
5. [Link].
6. Explainvariousloopcontrolstatements injavawithexamples.
7. Explainvariousselectioncontrolstatementinjavawith examples.
8. [Link].
9. Writeaprogramthatgivestheoutput:“WelcometotheWorldof Java”.
10. Write a program to find sum of first n natural numbers, where value of integer is supplied from the
keyboard.
11. Writeaprogramtofindsumofdigitsofanintegergiventhroughthe keyboard.
12. Write aprogram to printfirstn termsofaFibonaccisequence [Link] first two
terms of the Fibonacci sequence are 0 and 1.
13. Writeaprogramtofindourreverseofagivennumber
14. Writea programtocheckwhetheranintegerisprimenumberornot.
15. WriteaprogramtocheckwhetherintegerisArmstrongornot.
16. Writeaprogramtoadditiontwon× n matrices.
17. Writeaprogramtofindmaximumvaluefromalistcontainingnnumericvalues.
18. Write ajava programto find1+2+3+ ............... +50.
19. Explaindiscussbrieflythebuzzwordsof Java.
20. Discuss&explainbrieflythefeaturesofObjectorientedprogramming.

*****************

Common questions

Powered by AI

Java is platform-independent because it compiles source code into an intermediate form called byte code, which is not specific to any machine architecture. This byte code is executed by the Java Virtual Machine (JVM), which translates it into machine-specific code on different platforms. This allows Java programs to run on any system with a compliant JVM without modifying the code, epitomized by the 'Write once, run anywhere' concept .

A constructor in Java is a special method that is used to initialize objects of a class. It has the same name as the class and does not have a return type, unlike regular methods. Constructors are invoked when a new object is created, and they can be used to set initial values for object attributes. While regular methods are called upon the creation of objects through method calls and can return values, constructors are automatically called when an object is instantiated .

The 'Write once, run anywhere' (WORA) principle in Java signifies that a Java program, once written and compiled, can be executed on any platform that has a compliant JVM, without any need for recompilation. This is because Java code is compiled into byte code, which is platform-independent. Practically, this allows developers to distribute applications across various environments easily and ensures consistency and portability of Java applications .

Inheritance in Java allows classes to inherit properties and behaviors from a parent class, which is a foundational mechanism for achieving polymorphism. Through inheritance, a base class reference can point to objects of its derived subclasses, enabling polymorphic behavior such as method overriding. This facilitates the dynamic method invocation, where the overridden method in a subclass is called at runtime, allowing the program to exhibit different behaviors even when accessed through a common interface .

Java does not provide destructors as in C++ due to its use of automatic garbage collection to handle memory management. This garbage collector runs on the Java Virtual Machine and automatically cleans up objects that are no longer in use. This design decision removes the burden of manual memory management from developers, enhances security, and reduces memory leaks and pointer-related errors .

In Java, the types of inheritance include single, hierarchical, multilevel, and hybrid inheritance. Hierarchical inheritance occurs when multiple child classes inherit from a single parent class. For example, if we have a superclass named 'Vehicle', and two subclasses 'Car' and 'Truck', both 'Car' and 'Truck' inherit the properties of 'Vehicle', illustrating hierarchical inheritance .

Polymorphism in Java is implemented through method overloading and method overriding. Overloading, also known as compile-time polymorphism, involves having multiple methods with the same name but different parameters within the same class, which allows a single function to behave differently based on the input parameters. Method overriding, or runtime polymorphism, occurs when a subclass provides a specific implementation of a method already defined in its superclass, allowing it to be called through its superclass reference .

Java is considered robust because it has strong memory management features such as automatic garbage collection, which eliminates unused objects to free up memory. Additionally, Java avoids pointers, which can lead to unsafe behaviors, and provides extensive error handling through exception handling mechanisms. These elements contribute to Java's robustness by preventing common programming errors and improving the reliability of Java applications .

Method overloading in Java occurs when multiple methods in the same class have the same name but differ in the type or number of parameters, allowing different operations based on the input arguments. Method overriding, on the other hand, involves a subclass providing a specific implementation of a method already defined in its superclass, enabling runtime polymorphism. The key difference lies in their timing and scope; overloading is resolved at compile-time whereas overriding is resolved at runtime and involves inheritance and subclassing .

In Java and object-oriented programming, message passing is the process by which an object communicates with other objects by invoking methods or functions on those objects. This enables the code to be modular and reusable, as objects interact with each other by sending and receiving information, enhancing flexibility and encapsulation in the program's design .

You might also like