Java is a high-level, object-oriented programming language developed by Sun Microsystems, designed for platform independence through its 'Write Once, Run Anywhere' philosophy. Key features include automatic memory management, robust error checking, and support for multithreading and distributed computing, making it suitable for various applications from mobile to enterprise systems. Java's syntax is similar to C++, but it simplifies learning by eliminating complex features, and it provides a rich standard library for developers.
Java is a high-level, object-oriented programming language developed by Sun Microsystems, designed for platform independence through its 'Write Once, Run Anywhere' philosophy. Key features include automatic memory management, robust error checking, and support for multithreading and distributed computing, making it suitable for various applications from mobile to enterprise systems. Java's syntax is similar to C++, but it simplifies learning by eliminating complex features, and it provides a rich standard library for developers.
Pow
4.) What is java and uxplatn -feolures of Java. |
Tava: Tova ts a high-lere, Object - oriented prograrnining. |
language davelopea by Sun Microsystems to the mfd—1940s. TE ts
designed to be plat-form- tndspenctent, muaning Java. programs can |
yun on efferent types of computer systems, wtthade modéfecation, |
Frahures of Tava
4. Platform Tndependence + Tava achieves platform Pndependence |
“Though “the “ Whytte Once, Run finpotire” (WOR) phélosopru. |
This nuans Tava code ts comptled into bytecode, whith can run |
on any system that has @ JVM, regardless of the tandleriging |
hordwax or operating systern. |
2. Object — Oriented + Taya is based. on the object-orfented programa!
“tog (00P) paradégin, allowing developers to model real-world — |
entities with classes and. objects. Thés enemuyages code reusability,
_ modularity and scalability.
(5. dimple and Casy to learn: Tova fs dustqred to be easy to
| learn and use. Tts syrton fs similar to C++, but tH elefnates
“complex features IPke potters and multiple mhottance, making tt
| Simpl and ys ermr-prone.
4 Fobust and sewre : Java emphasizes evvor— checking at |
| runtime and duaing comptlation, making Ht las fey. for
i proqroms to crash. {SS
5. Maltelncadtng Support + Java supports rultittinwadtng « whic
allows mulliple tasks or “Threads to 1un stra Mareoaaty within
Prograro. “this ts useful ‘for aevehoptng appltcations ‘that reed »
berforrn many tasks concurrecatly, {tke woth and Sever appltcalions.
G. Distrtbubed Computing : Java. supports cléstrtbuted compa
‘though tools (tke Remote Method Jnvocation (RM1) and Ecderprite
Java Beans (E38). Thts ts useful for opplicalions that run oy
mulliple computers over a rework, Itke enterprise — level oppltcait ons,
% Audornatic Memory Managemerl : Java has an automatic gov
collection system, whitch hubs manage tormory by aud omalicabhy
challocating amor thal, ts no longer fr use. “This reduces
mamowy leaks and mates mmory management easter for diveloper
8. Pah Performance + Although Java ts nol as fast as lowerteul
languages Itke C+*, advancments Yo The JVM and “the Ported ction
of Just-tn-Teme (ITT) compilers have Stel ffeantiy Tmproved ts
performance over ttme.
9 Rich Standard Lbrary + Jayq provides a large standard "raw,
known as “tu Java Standard Libvaw or Java API, whfch
Fnctuces a vice Yange of classes and methods for tasks such a
networking, data stracture management, t/o Operations,
40, Scalability and Flentbiltty: Java te widely used tr a vark
of application domains, fom mobile and dleskiop applications
to large-scale enterprise systems. Tt Subborts
both small and
large projects, making if highliy scalable.
at elb. Loeplain “The structure of Java wilh an example.
dowmentation section
I |
Ix |
a/
Global declaration
function
Package slotements
Class classname,
| main metfod defirition |
| { |
| Local dectoralion s
| Executable statements
iS
A. Package Dedaration + Dedares “fhe package. Packages ane used 40 |
| organi z+ classes and avotd nor ng confitets. |
7 Tmaport Statements: Used to import olin Java classes or packages
F ntedea, |
|
is. Class declaration: A Tava program is Organized tn classes. |
Each fava file ‘typically hos one main class that es public,
which must have fie sam name as the file.
4. Main Method + The entry. point of OM Tava. program Ys “the
main meiRod. Thés whe the program starts oxcenuding..5. Methods and variables + You can deftee methods Cfun dor) and
Methods contain ‘The prqratm lygic
variables within lhe cla
and vartables stove data,
Crample
package com. examble s
import java. uli. Scanner s
public class HelolWortd {
pubite static votd main (String I oy) {
String name = “Java” +
Bystern. out. prtatln (“ttello, + nam #1 blediome to
te world of Tava.”)§
j
public static vord gpatUser (String username) £
System oul, printin CHtello, * + username + 1");
j
2a Desorbe fe dataty pes of Java-
Treva defines eight primitive types of data + byte» short ind Long.
chan, float, double and bookan.
Tedeqer Types + ont signed, posittve and re alive values. Java doent
seen Tbe. i
eg bold the whole numbers. There
Support unstgned values. Triteqe typ
on 4 databy pes waded to Tnteqen ted,
\onq.-
gmp such Os —byfle- short,Default
Dalatype — Stze ta Bytes
Value
byte 4 (a bits) 0
short 2 (16 bFts) 0
Ynt + (32 bits) o
Long 8 Gabtis) 0
Floating Potnt Numbers = can hold real numbers, thon ax 2 datailyps
related to floating -poted numbers, such as, float and double. ‘float’
stores veal numbers using single prectsfon, whtras, ‘double’ stores
real numbers using double preciston.
Datatype Stews tn Bytes Default
| float % (32 bits) 0-0
double 3 (64bIts) 0.0
Character Types * in Java ts used to stow characters. Tt occupies
2 bytes fn The memory unit and uses Unkcode 40 represent charac.
The default value of char fs ‘spact’.
Boolean: is used to deal with the logical valires. Tt occupies 4 byte
in Te rer 01y wtih default value as “false: Tt can have one of
ae two values manne. ‘true? or ‘false? Ths ts The type gutu yred
by alf. sulational operators.
Jave ts strongly typed language. The vaxtous Aakaty pes supported
by Java ane as shown below,Dalaty pes in Java
{
Piteaitive Dot aly pes
Won- Primitives Datatiy
es pes
Nurwente 7
Non -Numerfe Derived Usa-defenid
Anteqer Floatin B : l : annotations 4
q 00 kan character Arrays enum — class
byte * 1
a Float boolean chan
ent double ‘
t Subclass . au
~ long abstract rherface
class
What is an onnay 9 Explain “the types of aarcy.
too s avn aonay ts & qroup of Wke- typed variables -that are
refened to by a@ common name. Arrays of any type can be cated
and may have ont or more dimenstons.
Types OF array
Q) One - Dimenstonal Arrays? A one- cimenstonal analy t8, essentially,
a list of \he- typed variables. To crxtate an amay» you must fost
credle an anaay variable of “te destred type. The qennal -forin of a
ore-dimenstonal amraty dectaralion is
‘type var—namel J5
"How, type duclaus tir base type of the ABH The base type
dalermines the doe. type Of each element That comprises “fy anna.
The gerd form of rew as tt applies to one cimenstonal armars :
Le Aarayy=v0% = rau “type [strc]fo) Mallctinenstona Aneust Te avo, nll inen siocal ancy a
- wn idimenctonal
actu ally ways of umays. To dicure 9 venlidiimenctonal a
‘
wniable, sbectfy cach additional godue using onuiis sol of syare
brackets. Poy examples The following daclae a two- démenctona)
aoncy variable calli lwo.
Ynl twodl1() = rw in Lajie)
“Whis atlocates 9 4 by 5 cana and assigns tl te twod.
Pot - B
3. a) Explain the alt Operators available %m Java,
‘Arithmetic opoatore + “these Operators ave used th mathematical
“xpresstons. When artthmelic opoctors wilh 100 or move Operands,
hen it ts cathd antthmnelic expression.
* ALL cattimdic Operators Qu Binary Operctore pect $4 and «>
Huse an bolh binoowy and unary operators also. When we use
wlth single Oprand fen tH rugates ‘the value.
EO Es the only ovaloaded operator among. all the oparators
| fn Tava, when Ft ts used with puswnic dat. pers tun tt peforms
addition operation and cohen tt ts used wef, Strings, ' performs
» eoncalenation.
The Opaands must be Of tumente or character type-
Opactors Result
+ Addition
y Substraction
Mulliblicarion
/ Devestt
ston
ost
Mootulus“the indived
Bilwise Operators! “Rese operators, operate upon Re iodivictuol
. indivi als of
bits of “the choand. “They work “pon the individual bits of on
Ofevand.
o The bitwise Operators supported by Java fs as gan below,
Operators: Result
~ Bitwise NOT
oa BYtwise AND
| Brtwese OR
A Bitwfise KOR
>> Right Sheft
>>> Regt Shift Zeno Fell
<< Left heft
Relational Operctors + ptational Operctors determine “the relationship
thal Ore opevand has with reference to Offer operand. All Relational
operctors ax Binasy operators.
* The outcome of The relational opector ts a boolean Value.
+The relational Operators ade move frequent used tn oxpresstons
‘that control “fe vantous loop statements and if statements.
operator Result
: Epil to
fs Not Equal to
> Grate than
Z Less “than
de Grealexthan oy equal to
<= Less than oy qqpaltoLogical Operator : Logical opactors axe used to find logecal
yelation among ‘The Boolean values. Operates upon the Boolean
Operands. Result of logecal operclion fs Boolean value.
The list of logreat Operators supported by Java :
Opera ov Ruult
44 Logical AND
; Logteal oR
: Logécat NOT
Ex: A=Twe B=False Logical -
AG4B = True ANB = False
MIB = False ALA = False,
Assignment Opator: These oporator #8 wseckt osston value from
right sidt Opevand. to left side operand. All assignment operators
| on binosy operators.
“When using an assignment opaators, both ‘the operands must be of
sarne, type Tf thee ts an assfgnmment of one datatype value to ans,
then ‘typecasting has to happen.
5 Wrtte a Jawa progearn 10 add two Teteger ruumbers.
import java. ull L Scanner 5
public class AddTwoNumbers {
public, static votd mafn Cstrtng tJ os) {
Scanmwr scanmtr = pew Scanner (5ysten.th);
Systern.outs prtatln (* Enter the first tteqnrs )3Mk num) = scanner. react Trt CD
dystem. oul. printlo C Eaton The second inlegar s ":
Tor ntma = scanney. noetTat();
Tok sum = nim) + numa 5
System, out. pittln (The sum of “4 mewn ond
, $
4
numa +” F529 4-ga%):
+4. a) Explain contol statements wilh syntan .
Control
ments
Seudion Statement TheralZon statement Ju
top Statement
i while break
fase do-whtle labetid. break
if-dse~7f ladder Jor Cont ine
seottch for-cach labded contre
nested suttch (chanced fox) return
Sdecion Statements +
* Java Supports {wo sebiction statements. tf and swtich. These
Statements alow 10 contol “fe |
low of Programs execution based
upon conditions.
+The y statemedt ig Javars conditional brat
Dch Statement. Tt ts used
to wide program execution ‘irough too different pes.
syrtan
Tf slaternerd :
Pf Condition)
j2 Coondl?tton) {
| yy
ase {
| ye Te?
H-else-Tf ladden :
17 Pf CondPiton)§
| use if {
| ~ ne
\ 4 i
| set
\
; ook!
Natted if-else statement: tf Condition) {
Pf Condition) ¢
yocucns
Use { \
|
| j
| * Ceonditton) ¢ |
|
|
i
4
swottch: The switch statement fs g reultivoay byanch Statement.
———syntovt : suatich Cexpresston) {
Case value}: // senbenct sequence
Iyeak
Case Valuras 7 sentence seqprenee
break 5
Case valieeNe/Etatement seqprence
break;
default + // sdatement Sequence
The volute of “Ihe expression ta swotlch statement fe compared wth
Gach of fe valucs tn te case statements. Tf malch ts four ly
code sequence following. hak case rs executed.
Ftevalion Statements :
while Loob: Tt wheats a statement ov block of statements Untfl he
expression fs true fn while loop.
synto + aphtle Ccondltion) {
i M body of loop
Since the while loop evaluates its conditional expression at te
top of ‘the toops the body of the loop will not execette even once if
he condition ts false to begin woth.
do- while Loop: The dlo-while loop dhoays exeattes 1s bocty at least
once, because its conditional expression ts at the bottom Of The loop,
syntax: dof
I body of loo}
while Ccondiy fon); i
* Cach fleration of tie do-while loop fexst ene ceetes “Ihe bo.
dy. of fi
| loop and cthen evaluates the condittonal expression. Ty cl of Me
fs truss The loop will repeat.
lt
rs expressin[for loop + When ‘he loop “fist stars, the trtlialtzartion portton of ‘he
Hoop 1 executect. “hits ts an expression fal sete hie valtte of the (oop
contol variable, which acts as a counter thal controls “Ife loop.
‘The tnbliatization expression ts owly exeutted once. Neel, condition
fs evaluated,
Syolen® for Cietifatizations conditions tteration) {
} I body.
Syotox: for Ctype fia —vanz collection)
Statement-block
“How, type specifies the data type and tr-var specfftes the nae
of an fteration vartable that will vecetve the elements from a
| collection.
| Tauop statements
| break Statement: -Tt terminates’ a statement seyence fh a |
| sateen sintemertt. + Tt can be used to extt aloop. '
| “Tt con be used as @ “civilized” form of goto. |
| BY using break, we can force tmmucliate terménation of a loop, |
| bypossing cha conditfonal expiesston and any, vemafntng, code fh |
|The body of ix loop. When 0 bicak statement fs encountered
| tnsfoe a loop, the loop is temfnated ond program control
| yesumes at Te ret statement ‘followseg ‘the loop. |
| continue statement :
| continue statement skip The remainder of “Ih. code tn ts body, |
| for a particular tteration. ty whole ond do-while loops, aS
| ortinae statement causes control to be transfemed derectly. to the
7 anes Di nfs, “Iw loop.
Ihe cond? onal expreasfon that) contls “the loo}
hen Statement +
The reluin statement ts used to explictlly yebuin [rom “
; fer. back ¢
welhod. Ihat fs. TH causes program control tp Lans-fer back to
Me cotter Of Me meliod.
SAL anu time to a melhod The yeturn statement can be usec ‘to
Cause execution to branch back Io “the calter of ‘lhe melioct.
“Hhus. The return statement Troe ce ey lerminades “fhe method fn
which it ts executed.
4). Write a Java Prqram +o demonstrate auoflch statement.
Class SeottehDemo {
public static votd magn (string 03 args) {
for Cit *=05 Fee 5 tt)
seotleh CO)
Caseo:
System, out « bitty C8? ts Z0.0.””)
break;
breaks;
Casea:
's two. »).
System. ouk.prinbln (« ¢ ¢
break;
cases:
Systern. ouk. britdln (“ tis “lree.);
break;
defaute:
fs Pasta than 3:
System. oul. prin (« 9
Fo