0% found this document useful (0 votes)
3 views59 pages

Java Programming Basics and Concepts

The document provides an introduction to Java, covering its definition, history, and key components such as JRE, JVM, and bytecode. It explains the differences between procedural and object-oriented programming, as well as comparisons between Java and C++. Additionally, it outlines core OOP concepts including abstraction, encapsulation, inheritance, and polymorphism, along with the structure of a Java program.

Uploaded by

killaflamepyro
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)
3 views59 pages

Java Programming Basics and Concepts

The document provides an introduction to Java, covering its definition, history, and key components such as JRE, JVM, and bytecode. It explains the differences between procedural and object-oriented programming, as well as comparisons between Java and C++. Additionally, it outlines core OOP concepts including abstraction, encapsulation, inheritance, and polymorphism, along with the structure of a Java program.

Uploaded by

killaflamepyro
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

JAVA & INTERNET TECHNOLOGY PREPARED BY:PROF.

SHITAL PATHAR

Chapter – 1 Introduction to JAVA

1. What Is Java?
2. What Is History of Java?
3. What Is JRE?
4. What Is JVM?
5. What Is Bytecode?
6. Difference between POP and OOP.
7. Difference between C++ and Java?
8. Explain OOP concept.
9. Explain Program Structure of java.
10. What Is Java application and Applets? Give difference between application and
applets.
11. Explain feature of Java.
12. Write advantages and disadvantages of java?
13. Internet With Java
14. Explain data types in Java.
15. What is variable? Explain scope of variables.
16. What is identifiers and literals.
17. Explain Type conversion and casting.
18. Explain operators in Java.
19. Explain Control statement in java.
20. Explain Command line argument in java.
21. Explain array in Java.
22. Explain length instance of array in Java.
23. What is class?
24. What is object.
25. How to use or access variable and method of class.
26. Program for class and object .
27. What is method overloading?
28. What is Constructor ?
29. Explain passing object as parameter.
30. Explain different access specifiers or access control with example.
31. Explain this keyword in java.
32. Explain static keyword in java.

Parul Institute of Engineering & Technolgy (CSE) Page 1


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

Q-1 What Is Java?

 The Java is Object oriented programming language ,which is derived from c and c++.We
can create and implement executable content using the Java programming language.
 It was developed by James Gosling at Sun Microsystems in 1991. It was released in
public as a alpha & beta version in 1995.
 Java programs can be either application or applets.
 JDK also known as java 2 Platform that comes in three editions J2SE(Java 2 standard
edition),J2EE(,Java 2 enterprise edition) J2ME(Java 2 micro edition) .
 In Java , Java Developer’s Kit (JDK) is a software environment provided by Sun
Microsystems, which contains JRE(Java Runtime Environment)+Java language
development tools(compiler,interpreter,debugger,
 applet viewer etc..)
 It means JDK=JRE+Development tools and JRE=JVM+ set of libraries
 JDK comes in various versions and can be downloaded free from the Sun Microsystems.
 Java is compiled and interpreted language. Java program is saved to .java files . compiler
translates the program into an intermediate language called Java bytecode.
 This bytecodes are stored into .class files which is generated from .java file after
compilation. Java interpreter is also called Java Virtual Machine (JVM) is
interpreted(converted) this bytecode into executable code.
 Java is a platform independent language that means it can run on different OS. The Java
platform consists of JVM and Java API (Application programming Interface). The API
provides pre-written libraries and standard functionality with classes and interfaces.

Q-2 What Is History of Java?

 Java is Object oriented programming language developed by James Gosling at Sun


Microsystems in 1991.
 It takes 18 months to develop the first working version.
 Actually their original goal was to create a computer language that could be used to build
programs that would run in any different execution environment.
 It was released in public in 1995 as a alpha & beta version.
 This language was initially called “OAK” ,OAK is national tree of many countries but it
was renamed “JAVA” in 1995.
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Oak was first used in television set-top boxes designed to provide video-on-demand
services.
 Oak was unsuccessful so in 1995 sun changed the name to Java and modified the
language to take advantages of the growing World Wide Web.

Parul Institute of Engineering & Technolgy (CSE) Page 2


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

 Java Version History


 JDK alpha and beta(1995)
 JDK 1.0 (23 rd Jan,1996)
 J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb,2002)
 J2SE 5.0(30TH Sep ,2004)
 Java SE 6(11th Dec,2006)
 Java SE 7 (28th July,2011)
 Java SE 8 (18th March ,2014)

James Gosling(java creator)


Q-3 What Is JRE?

 JRE means Java Runtime Environment. JDK contains JRE.

 It means JDK=JRE+ Development tools and JRE=JVM+ set of libraries


 It is implementation of JVM.
 It physically exists. It contains set of libraries and other files that JVM uses at runtime.
 JRE contains the complete set of class files for basic language classes,GUI component
classes,and advanced collections API(Application programming Interface) etc. for all the
java packages.

Parul Institute of Engineering & Technolgy (CSE) Page 3


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Q-4 What Is JVM?

 Java Virtual Machine. It is software program .It exist only inside the computer memory.
So it is called virtual.
 JVM are available for many hardware and software platforms (i.e. JVM is platform
dependent).
 Java compiler compiles source code (.java file) into intermediate code known as
bytecode(.class file).
 This bytecode are not executable code. JVM is interpreter for bytecode.
 Java Virtual Machine interprets this byte code into the machine code depending upon the
underlying operating system and hardware combination.
 It is responsible for all the things like garbage collection, array bounds checking, etc…
 Java was designed to allow application programs that could be run on any platform
without having to be rewritten or recompiled by the programmer for each separate
platform. A Java virtual machine makes this possible.

Execution Engine:
 The Execution Engine of JVM is Responsible for executing the program and it contains
two parts.
1. Interpreter.
2. JIT Compiler (just in time compiler).

 The java code will be executed by both interpreter and JIT compiler simultaneously So it
will reduce the execution time and provide high performance.
 The Just-In-Time (JIT) compiler is a component of the Java Runtime Environment (JRE).
Parul Institute of Engineering & Technolgy (CSE) Page 4
JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 It improves the performance of Java applications by compiling bytecodes to native
machine code at run time.
 The JIT compiler is enabled by default, and is activated when a Java method is called.
 The JIT compiler compiles the bytecodes of that method into native machine code,
compiling it "just in time" to run.
 When a method has been compiled, the JVM calls the compiled code of that method
directly instead of interpreting it.

Q-5 What is bytecode?

 The output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a
highly optimized set of instructions .It is executed by Java Virtual Machine (JVM). JVM
is an interpreter for bytecode.
 Bytecode is a machine independent code.
 By translating a Java program into bytecode it much easier to run a program in a wide
variety of environments.
 only the JVM needs to be implemented for each platform. Once the run-time package
exists for a given system, any Java program can run on it.
 The use of bytecode enables the Java run-time system to execute programs much faster.

Parul Institute of Engineering & Technolgy (CSE) Page 5


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

Q-6 Difference between POP and OOP.

POP OOP
1. Program is divided into small parts 1. Program is divided into parts called
called function objects.
2. Importance is given to function. 2. Importance is given to data.
3. It follows top down approach 3. It follows bottomup approach
4. It does not have any access specifier. 4. It has access specifier named
public,private,protected.
5. Data can move freely from function 5. Object can move and communicate
to function. with each other through member
function.
6. To add new data and function in 6. To add new data and function in
POP is not easy OOP is easy
7. POP does not have any proper way 7. OOP provides data hiding so provide
for hiding data so it is less secure. more security.
8. Overloading is not possible. 8. Overloading is possible
9. Ex: C,VB, FORTRAN 9. Ex: C++ , JAVA ,[Link]

Q-7 Differentiate C++ and Java

C++ Java
1. C++ is not fully object oriented 1. java is fully object oriented language
language. as its main() is also within the class
2. C++ supports operator overloading. 2. Java does not support operator
overloading
3. C++ has templates 3. Java does not have template classes

Parul Institute of Engineering & Technolgy (CSE) Page 6


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
4. C++ supports multiple-inheritance. 4. Java does not support multiple-
inheritance
5. pointers are the important part of C++ 5. Java does not use pointers.
programs
6. C++ use global variables. 6. Java generally does not use global
variable
7. C++ use destructor to destroy the 7. Java has finalize() method to destroy
objects the objects
8. C++ use header files. 8. There are no header files in Java. Java
has inbuilt packages to use built-in
functions.

Q-8 Explain OOP concept.


1. Abstraction
 Abstraction represent important features without including the background details or
explanations.
 Abstraction separates specification from implementation.
 It shows only important things to the user and hides the internal details.
 Ex: we know how to drive car i.e. clutch,break etc. we also know what happens when we
press on break but we don’t know how it happened?and how it is implemented?this is
called abstraction.
 Abstraction is process of hiding the implementation details and showing only the
functionality.
 Abstraction in Java is achieved by using interface and abstract class.

2. Encapsulation
 The wrapping up of data and methods into a single unit is known as encapsulation.
 The data is not accessible to the outside world and only those methods,which are
wrapped in the class,can access it. encapsulation provides data hiding features.
 We can create a fully encapsulated class in java by making all the data members of the
class private. Now we can use public methods to get the data in it.

Parul Institute of Engineering & Technolgy (CSE) Page 7


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

3. Inheritance
 Inheritance is the process in which objects of one class get the properties of objects of
another class.
 The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).
 It supports the concept of hierarchical classification. Main feature of
 inheritance is reusability that avoids writing the same code twice.
 extends is the keyword used to inherit the properties of a class

class parent
{
void showparent()
{
[Link](“this is parent class”);
}
}
class child extends parent
{
void showchild()
{
[Link](“this is child class”);
}
}
class demo1
{
public static void main(String args[ ])
{
child c1=new child();
[Link]();
[Link]();
}
}
o/p:- this is parent class
this is child class

4. class:
 A class is a group of objects that has common properties.

Parul Institute of Engineering & Technolgy (CSE) Page 8


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 It can be defined as a template/blueprint that describes the behaviors/states of object.
 A class is a blue print from which individual objects are created.
 You declare a class by specifying the class keyword
 EX: class student
{
int id;
public static void main(String args[])
{
student s1= new student();
student s2= new student();
}
}

5. object:

 Object is the physical as well as logical entity. object is the fundamental building blocks.
Each object is instance of some class.
 Objects have states and behaviors.
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
 In Programme object's state is stored in fields/variable and behavior is shown via
methods.

 EX: class student


{
int id;
public static void main(String args[])
{
student s1= new student(); // s1 is object
student s2= new student(); //s2 is object
}
}

Parul Institute of Engineering & Technolgy (CSE) Page 9


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

6. Polymorphism:

 Polymorphism means the ability to take more than one form.


 Poly + morphs :- poly means many and morphs means forms.
 So polymorphism means many forms.
 There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism.
 We can perform polymorphism in java by method overloading and method overriding.

 Method Overloading:
 In Java, it is possible to define two or more methods of same name in a class, but
argument list or parameters are different. This concept is known as Method Overloading.
 Method Overriding
 Child class has the same method as of base class. In such cases child class overrides the
parent class method. This feature is known as method overriding.

Parul Institute of Engineering & Technolgy (CSE) Page 10


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Q-9 Explain Program Structure of JAVA .

 Java program may contain many classes in which one class define main [Link]
contains data type declaration ,method,and executed [Link] of java program
is:

Document section
Package stat.
Import stat.
Interface stat.
class classname
{
public static void main(String args[])
{
[Link](“hello”);
}
}

o Document section:
 A set of comment lines like program name, author name, and othe details .

o Package stat.:
 In this declareing package name and informs the compiler that the classes defined here
belong to this package.

o Import stat.:
 Number of import stat. will come. this is similar to include stat. this stat. import inbuilt or
user define package

o Interface:
 A interface like class but includes group of method declaration.

o Class definition:
 class is keyword .A java program may contain multiple class definition. class are primary
of java program.

o main() method:
 Every java program requires main method .main method creates objects of various
classes and communicate between [Link]() method is called when a java application
begins.

o public:
 The public keyword is an access specifier.

Parul Institute of Engineering & Technolgy (CSE) Page 11


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 When we write public then that member may be accessed by code outside the class. In
this main() must be called by code outside of its class when program is [Link] we
write public for main() method.

o static:
 static allows main() to be called without having to create particular instance(object) of the
[Link] main() is called by JVM before any objects are created.

o void:
 simply tells the compiler that main() does not return a value.

o String args[]:
 String is class and args is array name. So args[] is array of instances(object) of the class
[Link] of type String store character [Link] argument is store in
args[0],second argument is store in args[1] and so on..

o System:
 It is the name of class that contains objects that is used for standard I/O .
 It is class in the [Link] package.

o out:
 out is a static member of the System class, and is an instance of [Link].
 The object out represents output stream(i.e Command window)

o println:
 The println() is method of out object that takes the text string as an argument and
displays it to the standard output i.e on monitor [Link] is method that is display string
which is passed to it.

Q-10 Explain types of Java Programs. Differentiate Java applications and Java Applets.

 There are two types of Java programs: Applications and Applets.

o Applications
 Java application programs can run directly on our computer. Applications must
have a main(). Java application programs are compiled by javac command and
run using java command.

o Applet
 An applet is a Java program that runs over the Internet and executed by a Java-
compatible Web browser.
 An applet is actually a tiny Java program, dynamically downloaded across the network,
just like an image, sound file, or video clip. The important difference is that an applet is
an intelligent program, not just an animation or media file.
 In other words, an applet is a program that can react to user input and dynamically
change—not just run the same animation or sound over and over.

Parul Institute of Engineering & Technolgy (CSE) Page 12


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 Applet does not have main().
 Applets run in appletviewer.
 Applet needs HTML file before it can be run.

Java Applications Java Applets


Java applications run on the local computers. Java applets run on the internet generally
Java applications can be run by java command Java applets run in appletviewer
Java applications must have main() Java applets do not have main() but it should
have paint()
Java applications do not need HTML file to Java applets need HTML file to run
run

Q-11 Explain features of Java or Advantages of java or Java buzzwords.

Parul Institute of Engineering & Technolgy (CSE) Page 13


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Following are the features of Java.
1. Simple
2. Platform independent
3. Secure
4. Object oriented
5. Portable
6. Robust
7. Multithreaded
8. Interpreted and high performance
9. Distributed
10. Dynamic.
11. Architectural Neutral

[Link]
 Java is easy to learn and use for professional programmer. If you know C and
C++ syntax and if you already understand the basic concepts of object-oriented
programming, learning Java will be easier.

[Link] independent

 Platform dependent means the source code has to be modified according to the
platform.
 Platform independent means the execution of the program is possible by the any
type of os .so it makes possible to execute the program at any type of
environement available.
 Java is a platform independent language bcoz of the bytecode magic of java. In
java, when we execute the source code...it generates the bytecode(.class file)
 Bytecodes are easily interpreted by JVM which is available with every type of
OS we install.
 Java provides the facility to "Write once -Run any where"(Known as platform
independent) .
 It means java programs can run on variety of platforms means on different
operating systems.

[Link]
 access restrictions are enforced (public, private)
 byte codes are verified
 When you use a Java-compatible Web browser, you can safely download Java
applets without fear of viral infection . Java achieves this protection by not
allowing access to other parts of the computer by downloaded programs. There is
ability to download applets with confidence that no harm will be done. This is
considered the most important aspect of Java.

[Link]-Oriented
 The object oriented language must support the characteristics of the OOPs
concepts like abstraction, polymorphism, inheritance and encapsulatio. and Java is
a fully object oriented language .

Parul Institute of Engineering & Technolgy (CSE) Page 14


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 it supports all the characteristics needed to be object oriented.
 In the Java every thing is treated as objects to which methods are applied.
 No stand alone methods, constants, and variables are there in java. Everything in
java is object even the primitive data types can also be converted into object by
using the wrapper class.

[Link]
 Portability, in relation to software, is a measure of how easily an application can
be transferred from one computer environment to another.
 Java applications can be transferred easily from machine to machine. It provides
the feature write-once-run-anywhere makes the java language portable but the
system must have JVM.
 Operating system upgrades, processor upgrades, and changes in core system
resources can be the failure point for the program.
 But Java applications are independent of this failure. The goal of Java designers
was “write once; run anywhere, any time, forever.”

[Link]
 Robust simply means strong.
 Java uses strong memory management and automatic garbage collection
mechanism .
 There is exception handling and type checking mechanism in java. .
 Java program can run on variety of system.
 compiler checks the program for any error and interpreter checks any run time
error.
 All the above features makes Java language robust.

[Link]
 A thread is like a separate program, executing concurrently.
 Java was designed to meet the real-world requirement of creating interactive,
networked programs. To accomplish this, Java supports multithreaded
programming, which allows you to write programs that do many things
simultaneously.
 The main advantage of multi-threading is that it shares the same memory. Threads
are important for multi-media, Web applications etc.
 The Java uses concept of synchronization to handle multiple programs.

[Link] and high performance

 Java compiler compiles the Java source code into Java bytecode. This code can be
interpreted on any system by JVM.
 This language uses Bytecode which is more faster than ordinary pointer code so
Performance of this language is high.
 Garbage collector, collect the unused memory space and improve the performance
of application.
 It have no pointers so that using this language we can develop an application very
easily.

Parul Institute of Engineering & Technolgy (CSE) Page 15


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 It support multithreading, because of this time consuming process can be reduced
to execute the program.
 JIT is also used for high performance

[Link]

 Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. The original version of Java (Oak) allows objects on two
different computers to execute procedures remotely.
 Java provides this facility by having a package called Remote Method Invocation
(RMI). This feature brings level of abstraction to client/ server programming.

[Link]
 Because it is interpreted , Java is an extremely dynamic language, At runtime, the
java environment can extends itself by linking in classes that may be located on
remote servers on a network(for example, the internet)
 At runtime, the java interpreter performs name resolution while linking in the
necessary classes. The Java interpreter is also responsible for determining the
placement of object in memory.
 Java supports functions written in other languages. These functions are called
native methods and these methods are linked dynamically at run time with Java
code.

[Link] Neutral
 Architecture represents processor.
 A Language is said to be Architectural neutral which can run on any available
processors in the real world without considering there architecture and vendor
(providers) irrespective to its development and compilation.

Q-12 Explain advantages and disadvantages of Java.

o Advantages:

 Java is portable language. The goal of Java designers was WORA “write once; run
anywhere, any time, forever.”
 We can download Java applications from WWW and can run those applications on our
local computer.
 Java is platform independent language. Java programs can run on variety of platforms
means on different operation systems with different programming environments.
 Java is a secure language. When you use a Java-compatible Web browser, you can safely
download Java applets without fear of viral infection.
 Java supports multithreading so user can run more than one thread activity at a time.
 Java code is checked before loading so they are secured from run time errors.
 Through inheritance Java eliminates the redundant code and provides reusability.
 Java loads classes dynamically at the time they are actually needed.
 Java and Internet

Parul Institute of Engineering & Technolgy (CSE) Page 16


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
o Java users can run applet programs on Internet.
o Java users can download Java applications form Internet and run them on local
computers.
 Java and WWW
o World Wide Web is a distributed system that runs on the top of the Internet. It
contains web pages that provide information and control.
o Java is used in distributed system. Java communicate with the web page through
the special tag <APPLET>.

o Disadvantages:

 Performance : - Java can be consided slower and more memory consuming than c or
c++.
 Look :- The default look of GUI application written in java is very [Link] is possible
to specify different look through the pluggable look.

Q-13 Internet with Java(OR Java and WWW).

 Internet allows many different types of computers to be connected together, including all
computers having different CPU and Operating system.
 So ,the ability to write a portable program is useful for internet.
 Java is strongly associated with the Internet because java’s WORA ,write once run
anywhere concept is available.
 Java is used in distributed environments such as Internet. Because both the Web and Java
share the same philosophy, Java could be easily incorporated into web system.
 When Java lang. was first developed and ported on the Internet ,no browsers were
available that could run Java applets. Hot Java is the web browser that enables the display
of interactive content on the Web, using Java language.
 Before Java, WWW was limited to the display of text and images.
 Using Java into web pages has made it capable of supporting animations, graphics ,games
and wide range of special effects.
 With the support of java the web has become more interactive and dynamic.
 On the other hand , with support of web ,we can run a Java program on someone else’ s
computer across the Internet.

Parul Institute of Engineering & Technolgy (CSE) Page 17


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Q-14 Explain data types in Java.

 Data type represent which type of data is stored in variable.


1.

 Java defines eight simple or primitive types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
 Integers: This group includes byte, short, int, and long, which are for whole valued
signed numbers.
 Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
 Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
 Boolean: This group includes boolean, which is a special type for representing true/false
values.

o Integers and Floating-point numbers:


Name Width(bits) Default Value Range
long 64 0L –
9,223,372,036,854,775,808to9,223,372,036,854,775,807
int 32 0 –2,147,483,648 to 2,147,483,647
short 16 0 –32,768 to 32,767
byte 8 0 –128 to 127
double 64 0.0d 4.9e–324 to 1.8e+308
float 32 0.0f 1.4e−045 to 3.4e+038

 Ex: long l1=12345678L;


int i1=40000
short 1=1900
byte b1=2
double d1=88.88
float f1=3.2f

Parul Institute of Engineering & Technolgy (CSE) Page 18


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

o Characters:
Name Width(bits) Default value
char 16 '\u0000'
 The data type used to store characters in char. char in java is not same as char in c or c++.
 Java use Unicode to represent characters.
 Unicode define fully international character set that represent all of the characters found
in all human languages. For this purpose in java char is a 16 bit type. range of char is 0 to
65,[Link] are no negative char.
 Ex: char ch=’m’

o Booleans:
Name Width(bits) Default value
char 1 false
 Boolean is used for logical [Link] can have only one of two possible values, true or
false.
 Ex: Boolean b1=true

Q-15 What is variable? Explain scope of variables.

 The variable is the unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type. All variables have a scope, which defines their
visibility, and a lifetime.
 In Java, all variables must be declared before they can be used.
 variable declaration:- type identifier [ = value][, identifier [= value] ...] ;

 The type is one of Java’s atomic types, or the name of a class or interface. The identifier
is the name of the variable. You can initialize the variable by specifying an equal sign
and a value

 Examples:
int a, b, c; // declares three int, a, b, and c.
int d = 3, e, f = 5; // declares three more int, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'. specified type, use a
comma-separated list.

o Scope of variables
 Most of the computer languages define two general categories of scopes: global and
local.
 The variables declared within the method of a class are local variable.
 Variables in method arguments are also local variables.
 Variables declared within the class can be used by all the methods of that class globally.
 Program.
class c1

Parul Institute of Engineering & Technolgy (CSE) Page 19


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
{
public static void main(String args[])
{
int x=10; //known to all code within main
{ //start new scope
int y=20; //known only to this block
x=y*2; //no error
}
y=100 //error ,y is not known
[Link](x); // no error ,x is known
}
}

Q-16 What is identifiers and literals.

o Identifiers:

 Identifiers are used for class names, method names, and variable names.
 Identifier may be any name of uppercase, lowercase letters, numbers, or the underscore
and dollar-sign.
 They must not begin with number.
 VALUE and value is different identifiers.
Ex: Avg, a_b,a4,$t

o Literals:
 A constant value in is called literal
 literal can be used in anywhere.
 Ex: 100 , 98.7 , ‘x’ , “hello”

Q-17 Explain Type conversion and casting.

 When we assign a value of one type to a variable of another type is called type
conversion.
 For ex. when we assign value of int variable to float variable or float to double.
 If two types are compatible then java will perform the conversion automatically and if
two types are not compatible then java will not perform the conversion automatically.
 For that we must use cast, which performs explicit conversion between incompatible
types.

o Automatic type conversion:(Implicit conversion or Widening conversion)


 Automatic type conversion is performed when two conditions are met:
 The two types are compatible.
 The destination type is larger than source type.
 It is called widening conversion.
 Ex: int type is larger to hold all valid byte values. so in this automatic conversion is
possible.

Parul Institute of Engineering & Technolgy (CSE) Page 20


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 The numeric types ,including integer and floating point types are compatible with each
other.
 There are no automatic conversion from numeric type to char or Boolean.
 Char and Boolean are not compatible with each other.
 Ex: int i;
byte b=12;
i=b;

o Casting incompatible types(Explicit conversion or narrowing conversion)


 If we want to assign int value to a byte variable then it will not be performed
automatically, because byte is smaller than int. It is called narrowing conversion. we must
use cast for this type of conversion.
 Syntax: (target type) value
 target type specifies the desired type to convert the specified value to.
 Ex: int i=12;
byte b;
b= ( byte) i;

Q-18 Explain operators in Java.

 Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.

1. Arithmetic Operators
 Arithmetic operators are used in mathematical expressions. The following table lists the
arithmetic operators:
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement

2. Bitwise Operators
 Java defines several bitwise operators which can be applied to the integer types, long, int,
short, char, and byte. These operators act upon the individual bits of their operands.

Operator Result
~ Bitwise unary NOT
& Bitwise AND

Parul Institute of Engineering & Technolgy (CSE) Page 21


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

A B ˜A A&B A|B A^B


0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 0 1

 Program for bitwise operator.

class op
{
public static void main(String args[])
{
int n1=4,n2=5;
[Link](“AND result =”+(n1 & n2));
[Link](“OR result =”+(n1 | n2));
[Link](“XOR result =”+(n1 ^ n2));
[Link](“NOT result =”+(~n1 ));
[Link](“>>Shift right result =”+(n1 >> n2));
[Link](“<< shift Left result =”+(n1 << n2));
}
}

 Output: 8421
AND result = 4 n1=4 0100
OR result = 5 n2= 5 0101
XOR result = 1
NOT result = 11
>>Shift right result = 8
<<Shift left result = 2

Parul Institute of Engineering & Technolgy (CSE) Page 22


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
3. Relational Operators
 The relational operators determine the relationship that one operand has to the other.

Operator Dsecription Example(x=4,y=7)


== Equal to (x= = y) false
!= Not equal to (x ! =y) true
> Greater than (x > y)  false
< Less than (x < y)  true
>= Greater than or equal to (x > = 4) true
<= Less than or equal to (y < = 2 ) false

 Program for relational operator.


class op
{
public static void main(String args[])
{
int n1=4,n2=5;
[Link](“Equal =”+(n1 = = n2));
[Link](“Not equal =”+(n1 != n2));
[Link](“Greater than =”+(n1 > n2));
[Link](“Less than =”+(n1 < n2));
}
}

 Output:
Equal = false
Not equal = true
Greater than = false
Less than = true

4. Logical Operators
 The logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.

Operator Result
^ Logical XOR (exclusive OR)
|| Logical OR
&& logical AND
! Logica NOT

Logical AND Logical OR Logical XOR Logical NOT


&& true false || true false ^ true false ! true false
True true false true true true true false true result false true
False false false false true false false true false .

Parul Institute of Engineering & Technolgy (CSE) Page 23


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 Program for Logical operator
class op
{
public static void main(String args[])
{
int n1=4,n2=5,n3=1,n4=2;
boolean b1;
b1=!(n1>n2);
[Link](“b1 value is =”+b1);
b1=((n1>n2)&&(n3<n4));
[Link](“b1 value is =”+b1);
b1=((n1>n2) | |(n3<n4));
[Link](“b1 value is =”+b1);
}
}

 Output:
b1 value is = true
b1 value is = false
b1 value is = true

5. The Assignment Operator


 The assignment operator is the single equal sign, =.
var = expression;

 Here, the type of var must be compatible with the type of expression. The assignment
operator allows you to create a chain of assignments. For example, consider this
fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100

6. The ? Operator or ternary operator.


 Java includes a special ternary (three-way) operator that can replace certain types of if-
then-else statements.
The ? has this general form:
expression1 ? expression2 : expression3
 Here, expression1 can be any condition that evaluates(check) to a boolean value.
 If expression1 is true, then expression2 is evaluated or executed.
 If expression1 is false, then expression3 is evaluated or executed.
 Both expression2 and expression3 are required to return the same type, which can’t be
void.

a > b ? a = 0 : a = 1;

 When Java evaluates this assignment expression, it first looks at the expression to the left
of the question mark. If a > b is true then a=0 will be evaluated else a=1 will be
evaluated.

Parul Institute of Engineering & Technolgy (CSE) Page 24


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 Examples:
a>0 ? [Link](“a is positive”) : [Link](“a is negative”);

 Program for ternary operator.

class op
{
public static void main(String args[])
{
int n1=4,n2=5,n3;
n3 = n1 > n2 ? n1 : n2;
[Link](“max value is =”+n3);
}
}

 Output:
max value is = 5

7. Auto Increment and Auto Decrement Operators


 These operators modify the values of an expression by adding and subtracting 1.

X=5 Dsecription value of Y value of X


5 Y=++X 6 6
5 Y= X++ 5 6
5 Y= --x 4 4
5 Y= X-- 5 4

 Program for Increment & Decrement operator.

class op
{
public static void main(String args[])
{
int n1=5,n2=5,n3=5,n4=5;
[Link](“n1=” + ++n1);
[Link](“n2=” + --n2);
[Link](“n3=” + n3++);
[Link](“n4=” + n4--);
}
}
 Output:
n1 = 6
n2 = 4
n3 = 5
n4 = 5

Parul Institute of Engineering & Technolgy (CSE) Page 25


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Q-19 Explain Control statement in java.

1. Conditional Flow control


 simple if
 If ….else
 Nested if …else
 Ladder if .. else
 Switch
2. Loop control
 While loop
 Do while loop
 For loop
 Enhanced for loop
3. Exit loop or jump statement
 Break
 Continue
 return

1. Conditional Flow control

o simple if
 The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths.
Syntax: if (condition)
statement1;

 Here, each statement may be a single statement or a compound statement enclosed in curly
braces. The condition is any expression that returns a boolean value. If the condition is
true, then statement1 is executed. Otherwise, statement1 is not executed.

 Program for if statement.

class abc
{
public static void main(String args[])
{
int mark=50;
if(mark>= 50 )
[Link](“good marks=“+mark);
}
}
 Output: good marks = 50

o if .. else
 The if ..else statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths.

Parul Institute of Engineering & Technolgy (CSE) Page 26


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Syntax: if (condition)
statement1;
else
statement2;

 Here, each statement may be a single statement or a compound statement enclosed in curly
braces. The condition is any expression that returns a boolean value. The else clause is
optional. If the condition is true, then statement1 is executed. Otherwise, statement2 (if it
exists) is executed.

 Program for if…else statement.

class abc
{
public static void main(String args[])
{
int mark=20;
if(mark>= 50 )
[Link](“good marks=“+mark);
else
[Link](“you are fail marks=“+mark);

}
}
 Output: you are fail marks= 20

o Nested IF
 A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming.
Syntax: if (condition)
{
if(condition)
statement1;
else
statement2;
}
else
statement3;

 Program for nested if…else statement.

class IfElse
{
public static void main(String args[])
{
int i = [Link](args[0]);
if(i > 0)
{

Parul Institute of Engineering & Technolgy (CSE) Page 27


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
if(i > 3)
[Link]("i > 0 and i > 3");
else
[Link]("i > 0 and i <= 3");
}
else
[Link]("i <= 0");
}
}
 Output: c:> java IfElse 5
i > 0 and i > 3
c:> java IfElse 2
i > 0 and i <= 3

o The if-else-if Ladder


 A common programming construct that is based upon a sequence of nested ifs is the if-
else-if ladder.
Syntax: if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

 The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed. If there is no final else and all other conditions are false, then no action will
take place.

 Program for elseifLadder statement.

class IfElseLadder
{
public static void main(String args[])
{
int i = [Link](args[0]);
if(i < 0)
[Link]("Negative number");
else if(i == 0)
[Link]("Zero");
else if(i == 1)
[Link]("One");
else if(i == 2)
[Link]("Two");

Parul Institute of Engineering & Technolgy (CSE) Page 28


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
else if(i == 3)
[Link]("Three");
else
[Link]("Greater than three");
}
}
 Output: c:> java IfElseLadder 0
Zero
c:> java IfElseLadder 3
Three

o Switch statement
 The switch statement is Java’s multi way branch statement. It provides an easy way to
execute different parts of your code based on the value of an expression. As such, it often
provides a better alternative than a large series of if-else-if statements.
Syntax: switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case value N:
// statement sequence
break;
default:
// default statement sequence
}

 The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must
be a unique literal means it must be a constant, not a variable. Duplicate case values are
not allowed.
 The switch statement works like this: The value of the expression is compared with each
of the literal values in the case statements. If a match is found, the code sequence
following that case statement is executed.
 If none of the constants matches the value of the expression, then the default statement is
executed. However, the default statement is optional. If no case matches and no default is
present, then no further action is taken. The break statement is used inside the switch to
terminate a statement sequence.

 Program for switch statement.

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

Parul Institute of Engineering & Technolgy (CSE) Page 29


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
{
int i = [Link] Int(args[0]);
switch(i)
{
case 1:
[Link]("one");
break;
case 2:
[Link]("two");
break;
case 3:
[Link]("three");
break;
case 4:
[Link]("four");
break;
default:
[Link]("Unrecognized Number");
}
}
}
 Output: c:> java SwitchDemo 2
two
c:> java SwitchDemo 4
Four

2. Loop control
 Java’s iteration statements are for, while, and do-while.. loop repeatedly executes the
same set of instructions until a termination condition is met.
o while
 It repeats a statement or block while its controlling expression is true.
Syntax: while(condition)
{
// body of loop
}
 The condition can be any Boolean expression. The body of the loop will be executed if
the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if
only a single statement is being repeated.

 Program for while loop.

class WhileDemo
{
public static void main(String args[])
{
int i = [Link](args[0]);
while(i > 0)

Parul Institute of Engineering & Technolgy (CSE) Page 30


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
{
[Link](“i= “+i);
i--;
}
}
}
 Output: c:> java WhileDemo 2
i= 2
i=1

o do-while
 Sometimes it is 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.

Syntax: do
{
// body of loop
} while (condition);

 Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the
loop terminates. condition must be a Boolean expression.

 Program for do while loop

class fact
{
public static void main(String args[])
{
int no;
no=[Link](args[0]);
int fact = 1;
do
{
fact=fact*no;
no--;
} while(no>0);
[Link](“fact of number =”+ fact);
}
}

 Output: c:> java fact 4


fat of number = 24

o for
 Syntax: for(initialization; condition; iteration)

Parul Institute of Engineering & Technolgy (CSE) Page 31


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
{
// body
}

 If only one statement is being repeated, there is no need for the curly braces. The for loop
operates as follows.
 When the loop first starts, the initialization portion of the loop is executed. Generally, this
is an expression that sets the value of the loop control variable, which acts as a counter
that controls the loop .The initialization expression is only executed once.
 condition is evaluated. This must be a Boolean expression. If this expression is true, then
the body of the loop is executed. If it is false, the loop terminates.
 iteration portion of the loop is executed. This is usually an expression that increments or
decrements the loop control variable. The loop then iterates, first evaluating the
conditional expression, then executing the body of the loop, and then executing the
iteration expression with each pass. This process repeats until the controlling expression
is false.

 Program for for loop

class ForDemo
{
public static void main(String args[])
{
for(int num = 1; num < =5; num ++ )
[Link](“num =”+num);
}
}
 Output: 1
2
3
4
5

o Enhanced for loop


 Syntax: for(data type variable : array name)
{
// body
}

 Program for Enhanced for loop


class f1
{
public static void main(String args[])
{
int a[]={10,20,30};
int s=0;
for(int x:a)
s=x+s;

Parul Institute of Engineering & Technolgy (CSE) Page 32


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
[Link](s);
}
}
 Output: 60

 In this ,variable is store value of array element one by one during each iteration.
 Ex: in first iteration x=10,in second iteration x=20 and thirs iteration x=30.
 So loop is executed three times in this example.

3. Exit control or Jump statement

o Using break
In Java, the break statement has three uses.
 It terminates a statement sequence in a switch statement.
 It can be used to exit a loop.
 It can be used as a form of goto.
 When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.

 Program for break statement

class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
if(i == 3)
break; // terminate
loop if i is 3
[Link]("i: " + i);
}
[Link]("Loop complete.");
}
}
output: 0
1
2
Loop complete

o Using continue
 you might want to continue running the loop, but stop processing the remainder of the
code in its body for this particular iteration. The continue statement performs such an
action.

 Program for countinue statement.

Parul Institute of Engineering & Technolgy (CSE) Page 33


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
if(i == 3)
continue;
[Link]("i: " + i);
}
}
}
output: 0
1
2
4

o Return
 The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method. Thus, the return statement
immediately terminates the method in which it is executed. The following example
illustrates this point.

 Program for return statement.

class Return
{
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
Output: Before the return

Q-20 Explain Command line argument in java.

 You can pass information into a program when you run it using command line argument.
 In public static void main(String args[]) In this String args[] refers the command line
arguments having the type string. args is a string [Link] stores first argument in
args[0],second in args[1] and so on…
 Ex: cmd>java prog1 hi hello
cmd>java prog1 2 3
class cmd

Parul Institute of Engineering & Technolgy (CSE) Page 34


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
{
public static void main(String args[])
{
for(i=0;i<[Link];i++)
[Link](“argument=”+args[i])
}
}
o/p: cmd>java prog1 hi hello
hi
hello

Q-21 Explain array in Java.

 An array is a group of variables they have same data type and that are referred to by a
common name. Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
o One dimensional Array
o Multi dimensional Array
o Non rectangular Array

o One-Dimensional Arrays
 To create an array, you first must create an array variable of the desired type.
o Declare: type array name[]; or type [ ] array name;
o Ex: int a1[]; or int [] a1;
 Now you must allocate memory using new keyword.
o construct: array name= new type [ size];
o Ex: a1= new int [ 10];
 Now assign value into array.
o Assign : array name[size] = value;
o Ex: a1 [10] =20;
 Here, type declares the base type of the array. Thus, the base type for the array
determines what type of data the array will hold.
 There is a second syntax to combine declaration and construct:
o Syntax: type[ ] var-name = new type[size];
o Ex: int al[] = new int[3];
 Arrays can be initialized when they are declared.
o Ex: int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

 Demonstrate a one-dimensional array.


class Array
{
public static void main(String args[])
{
int days[];
days = new int[5];
days[0] = 31;
days[1] = 28;

Parul Institute of Engineering & Technolgy (CSE) Page 35


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
days[2] = 31;
days[3] = 30;
days[4] = 31;
[Link]("April has " +days[3] + " days.");
}
}

o Multidimensional Arrays
 In Java, multidimensional arrays are actually arrays of arrays. To declare a
multidimensional array variable, specify each additional index using another set of square
brackets. For example, the following declares a two-dimensional array variable called
twoD.

 int twoD[ ][ ] = new int[4][5];


 This allocates a 4 by 5 array and assigns it to twoD. The following program numbers
each element in the array from left to right, top to bottom, and then displays these values:

class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[3][3];
int i, j, k = 0;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
}

 output:
0 1 2
3 4 5
6 7 8

o Non rectangular Arrays

Parul Institute of Engineering & Technolgy (CSE) Page 36


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 In Java, It is compulsory to allocate memory for the first dimension in multidimensional
array.
 We can allocate memory to remaining dimension afterwards.
 In non rectangular arrays number of rows elements are fixed,but number of columns for
each row are different.
 EX: int arr1[][]= new int [5] [ ]; //valid
int arr1[][]= new int [] [ 5]; //invalid

class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[3][ ];
twoD[0]= new int [ 1] ;
twoD[1]= new int [ 2] ;
twoD[2]= new int [ 3] ;
int i, j, k = 0;
for(i=0; i<3; i++)
{
for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<3; i++)
{
for(j=0; j<i+1; j++)
{
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
}
 output:
0
1 2
34 5

Q-22 Explain length instance of array in Java.

 The size of array that is the number of elements that an array can hold is found in its
length instance variable.
 All arrays have this variable, and it will always hold the size of array.
 Ex:
class length
{

Parul Institute of Engineering & Technolgy (CSE) Page 37


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
public static void main(String args[])
{
int a1[]={1,2,3};
int a2[]= new int[5];
[Link](“size of array a1=” +[Link])
[Link](“size of array a2=” +[Link])
}
}
o/p:
3
5

Q-23 What is class?

 Class is a container for variables and methods. Class defines a new data type that is used
to create the object of that type. Thus, a class is a template for an object, and an object is
an instance of a class. A class is declared by use of the class keyword.
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ......................
type methodnameN(parameter-list)
{
// body of method
}
}
 The data, or variables, defined within a class are called instance variables because each
instance of the class contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another.
 The code is contained within methods. The methods and variables defined within a class
are called members of the class.

 Syntax of method declaration:

return type methodname (argument list)

Parul Institute of Engineering & Technolgy (CSE) Page 38


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 return type: It specify the type of data returned by the method. if it returns int
then write int if it does not return any value then write void
 methodname : It is the valid name of any method.
 argument list: It is a sequence of type and identifier pairs separated by commas.

 Java classes do not need to have a main( ) method. You only specify main() method if
that class is the starting point for your program.

 Example:

class Box
{
int width,height, depth;
void set()
{
}
void set1(int a)
{
}
int set2()
{
}
int set3(int a)
{
}
}

Q-24 What is object?

 A java object is one instance of class. A object is a block of memory that contains space
to store all the instance variables. Objects are created by using new operator. The new
operator creates an object of the specified class in the heap area of memory and returns a
reference to the object created. It is dynamically allocated memory to the object.
 Syntax:
classname objectname = new classname();
 Ex:
Box b1=new Box();
 Now when we create another object reference and give to reference of previous object
Box b1;
b1=new Box();
Box b2=b1
 The above stat. can not create new object in the memory but b1 and b2 will both refer to
the same object.
 It simply makes b2 refer same object as does [Link] any changes made to the object
through b2 will affect the object to which b1 is referring. because they are the same
object.

Parul Institute of Engineering & Technolgy (CSE) Page 39


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
b1
Height
Width
Box Object
Depth
b2

Q-25 How to use or access variable and method of class.

 .
The dot ( ) operator is used to access the instance variables and method defined in
class.
 Syntax:

objectname . variablename;
objectname . methodname();

 Ex:
class Box
{
int width,height, depth;
void set()
{
[Link](“hello”);
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
[Link]=10;
[Link]=20;
[Link]=30;
[Link]();
}
}

Parul Institute of Engineering & Technolgy (CSE) Page 40


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
Q-26 Program for class and object .

1. Create class Box which has 3 variable (width,height,depth) .calculate volume of box and
display answer.
class Box
{
int width,height, depth;
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
int v1;
[Link]=10;
[Link]=20;
[Link]=30;
v1=[Link] * [Link] * [Link];
[Link](“volume of v1=” + v1);
}
}

 output: volume of v1 = 6000

2. Create class Box which has 3 variable (width,height,depth) .create two object and
calculate volume of two object and display answer.
class Box
{
int width,height, depth;
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box();
int v1 ,v2;
[Link]=10;
[Link]=20;
[Link]=30;
[Link]=3;
[Link]=4;
[Link]=5;
v1=[Link] * [Link] * [Link];
[Link](“volume of v1=” + v1);
v2=[Link] * [Link] * [Link];
[Link](“volume of v2=” + v2);
}

Parul Institute of Engineering & Technolgy (CSE) Page 41


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
}
 output: volume of v1 = 6000
volume of v2=6

3. Create class Box which has 3 variable (width,height,depth) and one method display (no
argument no return) . calculate volume and display answer.
class Box
{
int width,height, depth;
void display()
{
int v1;
v1=width * height * depth;
[Link](“volume of v1=” + v1);
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
[Link]=10;
[Link]=20;
[Link]=30;
[Link]();
}
}

 output: volume of v1 = 6000

4. Create class Box which has 3 variable (width,height,depth) and one method display (no
argument return) . calculate volume of two object and display answer.
class Box
{
int width,height, depth;
int display()
{
int v1;
v1=width * height * depth;
return v1;
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box();

Parul Institute of Engineering & Technolgy (CSE) Page 42


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
int v1,v2;
[Link]=10;
[Link]=20;
[Link]=30;
[Link]=3;
[Link]=4;
[Link]=5;
v1=[Link]();
[Link](“volume of v1=” + v1);
v2=[Link]();
[Link](“volume of v1=” + v2);

}
}

 output: volume of v1 = 6000


volume of v2=60

5. Create class Box which has 3 variable (width,height,depth) and two method method1
display (no argument no return) and method2 set (arg but no return) .calculate volume
and display answer.
class Box
{
int width,height, depth;
void display()
{
int v1;
v1=width * height * depth;
[Link](“volume of v1=” + v1);
}
void set(int w,int h ,int d)
{
width = w;
height = h;
depth = d;
}

}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
[Link](10,20,30);
[Link]();
}
}

Parul Institute of Engineering & Technolgy (CSE) Page 43


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 output: volume of v1 = 6000

Q-27 What is method overloading?


 In java it is possible to define two or more methods within the same class that share the
same name but their parameter declarations are different.
 In this methods are said to be overloaded and the process is referred to as method
overloading.
 Java uses the type and number of parameters to determine which overloaded method to
call.
 Thus overloaded methods must differ in the type and number of parameters.
 While overloaded methods may have different return type.
 When java call to overloaded method it executes those method whose parameters match
the arguments used in the call.

class overloaddemo
{
void test()
{
[Link](“no parameters.”);
}
void test(float a)
{
[Link](“value of float a=”+a);
}
void test(int a ,int b)
{
[Link](“value of a=”+a);
[Link](“value of b=”+b);
}
int test(int a)
{
return a*a;
}
class m1
{
public static void main(String args[])
{
overloaddemo ob= new overloaddemo();
[Link]();
[Link](10.2f);
[Link](10,20);
int r=[Link](10);
[Link](“value of r=”+r);
}
}
 output: no parameters
value of float a=10.2
value of float a=10

Parul Institute of Engineering & Technolgy (CSE) Page 44


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
value of float b=20
value of float r=100

Q-28 What is Constructor ?

 It can be difficult to initialize all of the variables in a class each time an instance(object)
is created.
 Java allows objects to initialize themselves when they are created.
 This automatic initialization is performed through the use of a constructor.
 A constructor initializes an object immediately when they are created. It has the same
name as the class in which it resides and its syntax is same as method.
 Once defined ,the constructor is automatically called immediately after the object is
created,before new operator completes.
 Constructor have no return type ,not even void .

class Box
{
int width,height, depth;
Box() //this is the constructor for Box
{ width = 10;
height = 20;
depth = 30;
}
void display()
{
int v1;
v1=width * height * depth;
[Link](“volume of v1=” + v1);
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2= new Box();
[Link]();
[Link]();
}
}

 output: volume of v1 = 6000


volume of v1=6000

1. What is Default Constructor .

 Constructor with no argument is called default constructor. There is no need to create


default constructor in program code. When object is created java will automatically call

Parul Institute of Engineering & Technolgy (CSE) Page 45


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
the default constructor. When following statement is executed default constructor Box()
is called automatically.
Box b1=new Box();
 Every class has at least one constructor, which is called default constructor.
 The default constructor automatically initializes all instance variable to zero.

2. What is parameterized Constructor .

 While we use Box() Constructor with no argument ,it is not very useful because all boxes
have same value of width,height,depth.
 Now if we want to take different value of this variable for different boxes then we have to
add parameter to the constructor.
 Parameterized constructors takes parameters to initialize the variables of the class.
 Constructors share the same name in the single class,but they have different parameter
list.
 The compiler differentiates these constructor based on the number of parameters in the
list and their types.

class Box
{
int width,height, depth;
Box(int w, int h ,int d) //this is the parameterized
constructor
{ width = w;
height = h;
depth = d;
}
void display()
{
int v1;
v1=width * height * depth;
[Link](“volume of v1=” + v1);
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box(10,20,30);
Box b2= new Box(4,5,6);
[Link]();
[Link]();
}
}

 output: volume of v1 = 6000


volume of v1=120

Parul Institute of Engineering & Technolgy (CSE) Page 46


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
3. Explain copy constructor.

 Through copy constructor we can copy one object into another object

class student
{
int id;
String name;
student(int i,String n1)
{
id = i;
name = n1;
}
student (student s)
{
id=[Link];
name=[Link];
}
void display()
{
[Link](id+" "+name);
}
}
class m1
{
public static void main(String args[])
{
student s1 = new student(1,"vipul");
student s2 = new student(s1);
[Link]();
[Link]();
}
}
 output: 1 vipul
1 vipul

4. Explain constructor overloading.

 constructor overloading is same as the method overloading. When any object created, it
will execute the constructor, which matches the type and number of parameters.

class Box
{
int width,height, depth;
Box()
{ width = 10;
height = 20;
depth = 30;

Parul Institute of Engineering & Technolgy (CSE) Page 47


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
}
Box(int w ,int h, int d)
{ width = w;
height = h;
depth = d;
}
Box(int l)
{
width = height = depth =l
}

int display()
{
return width * height * depth;
}
}
class m1
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2= new Box(1,2,3);
Box b3= new Box(4);
int v=[Link]();
[Link](“volume of v=” + v);
v=[Link]();
[Link](“volume of v=” + v);
v=[Link]();
[Link](“volume of v=” + v);

}
}
 output: volume of v1 = 6000
volume of v=6
volume of v=64

Q-29 Explain passing object as parameter.

 We can also pass object as a parameter in java.

class test
{
int a,b;
test( int i ,int j)
{
a = i;
b = j;
}

Parul Institute of Engineering & Technolgy (CSE) Page 48


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
void equal(test T)
{
if(a==T. a && b==T.b)
[Link](“value of 2 objects r equal”);
else
[Link](“value of 2 objects r not equal”);
}
}
class m1
{
public static void main(String args[])
{
test t1= new test(10,20);
test t2= new test(10,20);
test t3=new test(30,40);
[Link](t2);
[Link](t3);
}
}
 output: value of 2 objects r equal
value of 2 objects r not equal

Q-30 Explain different access specifiers or access control with example. OR Explain
public, private , protected and default keywords with example.

 Java provides access control by which you can control what parts of a program can
access the members of a class. By controlling access, you can prevent misuse.
 Java’s access specifiers are private, protected, default, public.

 private: When a member(variable or method) of a class is specified as private, then it


will only accessed in the same class in which it is declared as private. The private
members cannot access in the outside world. If any class declared as private than that
class will not be inherited.

 protected: If you want to allow an element to be seen outside your current package, but
only to classes that subclass your class directly at that time declare that element protected
.
 default:When no access specifier is used, then bydefault the member of a class is default
. when any member of class is specified as default access specifier then the method or
variable will be accessed in only that package in which they are [Link] cannot be
accessed outside the package.

 public: When a member of a class is specified as public specifier, then that member can
be accessed by any other code. main() method in Java is always public because it is
called by code that is outside the program.

Example:
package p1;
Parul Institute of Engineering & Technolgy (CSE) Page 49
JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
class access
{
private int a=10;
protected int b=20;
int c=30;
public int d=40;
void get()
{
[Link](“a =”+ a);
[Link](“b =”+ b);
[Link](“c =”+ c);
[Link](“d =”+ d);
}
}
class d1 extends access
{
[Link](“a =”+ a); //error a can not be used here.
[Link](“b =”+ b);
[Link](“c =”+ c);
[Link](“d =”+ d);
}
class d2
{
access o1= new access();
[Link](“a =”+ o1.a); //error a can not be used here.
[Link](“b =”+ o1.b);
[Link](“c =”+ o1.c);
[Link](“d =”+ o1.d);

package p2;
class access2
{
[Link] o2=new [Link]();
[Link](“a =”+ o2.a); //error a can not used
here(private)
[Link](“b =”+ o2.b); //error b can not used
here(protected)
[Link](“c =”+ o2.c); //error c can not used
here(default)
[Link](“d =”+ o2.d);
}
class access3 extends access2
{
[Link] o2=new [Link]();
[Link](“a =”+ o2.a); //error a can not used
here(private)

Parul Institute of Engineering & Technolgy (CSE) Page 50


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
[Link](“b =”+ o2.b);
[Link](“c =”+ o2.c); //error c can not used
here(default)
[Link](“d =”+ o2.d);

Private No Modifier Protected Public


Same Class Yes Yes Yes Yes
Same Package Subclass No Yes Yes Yes
Same Package Non-Subclass No Yes Yes Yes
Different Package Subclass No No Yes Yes
Different Package Non-Subclass No No No Yes

Q-31 Explain this keyword in java.

 “this” keyword is used inside any instance method or constructor of class.


 “this” is a reference variable that refers to the current object whose Method or
constructor is being invoked(call). It is a keyword in java language represents current
class object.
 When we use same name for instance variable(data member of class) and formal
parameter at that time JVM does not differentiate between instance variable and formal
parameter .
 So at that time this keyword is useful.
 To differentiate between instance variable (data member of the class) and formal
parameter , the data member of the class must be preceded by "this".
 If any variable is preceded by "this" JVM treated that variable as class variable.
 Syntax: [Link] member of class
 Static method can not use “this” keyword.

 problem without “this”.

class Student
{
int id;
String name;
Student(int id,String name)
{
id = id;
name = name;
}
void display()
{
[Link](id+" "+name);
}
}

Parul Institute of Engineering & Technolgy (CSE) Page 51


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
class a1
{
public static void main(String args[]){
Student s1 = new Student(1,"vipul");
Student s2 = new Student(2,"shital");
[Link]();
[Link]();
}

 output: 0 null
0 null

 solution using “this”.

class Student
{
int id;
String name;
Student(int id,String name)
{
[Link] = id;
[Link] = name;
}
void display()
{
[Link](id+" "+name);
}
}
class a1
{
public static void main(String args[]){
Student s1 = new Student(1,"vipul");
Student s2 = new Student(2,"shital”);
[Link]();
[Link]();
}

 output: 0 vipul
1 shital

Q-32 Explain static keyword in java.

 class member must be accessed only with an object of its class.


 Now it is possible to create member that can be used by itself, without reference to a
specific instance(object).
 To create such member of class we use “ static “ keyword.
 The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks .

Parul Institute of Engineering & Technolgy (CSE) Page 52


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 you can declare both variable and methods to be static.
 static means that variable or method is not tied to any particular object of that class.
 when a member(variable ,method) is declared static ,it can be accessed before any objects
of its class are created, and without reference to any object.

o static variable:
 If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not
unique for each object)
 If we want to have only one place of storage for data regardless of how many objects are
created,or even if no objects are created we can use static variable.
 The static variable gets memory only once in class area at the time of class loading.
 Syntax: static datatype variablename = value;

class Student
{
int rollno;
String name;
static String college ="Parul University";
Student(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno+" "+name+" "+college);
}

static
{
[Link]("static block ");

}
static void display2()
{
[Link](“college=”+college);
}

public static void main(String args[])


{
Student s1 = new Student(1,"vipul");
Student s2 = new Student(2,"shital");
[Link]();
[Link]();
ndisplay2();
}

Parul Institute of Engineering & Technolgy (CSE) Page 53


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
}
 output:
static block
1 vipul Parul University
2 shital Parul University
College =Parul University

o static method:
 we can create method that we can call even if no objects are created.
 static method can only call other static methods.
 static method must only access static data.
 static method can not refer to “this” or “super” keyword.

o static block:
 static block is executed before the creation of any of the objects of the class.
 if we need to do some calculation to initialize our static variables, we can declare static
block that gets executed exactly once,when the class is first loaded.

 If we use static method and variable outside of the class then we specify the name of their
classname with dot operator.
 classname .method() classname .variablename

Parul Institute of Engineering & Technolgy (CSE) Page 54


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

LIST OF QUESTIONS:

1. List four different OOP concepts.


2. Describe JVM.
3. Describe main() method in Java.
4. State the importance of byte code.
5. Write any four differences between Java and C++.
6. Explain basic structure of Java programs.
7. List different features of Java. Explain any one of it
8. Explain following
i)Byte Code (ii) JVM (iii) Platform Independent.
9. Explain following
(i) Portable (ii) JRE (iii) Applet
10. Distinguish between break and continue statements in Java.
11. Explain any one of Java Loop Statements with program example.
12. What is Wrapper class? Explain use of any one wrapper class.
13. Explain Type Conversion and Casting.
14. List methods of String class. Explain how to use String class .
15. List methods of String Buffer class. Explain how to use String buffer class
16. Write a Java program to read two strings from command line argument and check the
equality of two string using string function.
17. Write a program and explain how to create class and object .
18. Explain copy constructor in JAVA
19. Write a program to explain Method Overloading
20. Static Method Vs Non Static Method.
21. Explain different Access Controls in java.
22. Explain “this” keyword with example.

Parul Institute of Engineering & Technolgy (CSE) Page 55


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

Extra :
---------------------------------------------------------------------------------------------------------------------

1. W.A.P to print hello

filename: [Link]

class hello
{
public static void main(String args[])
{
[Link](“hello”);
}
}
 Windows :- start run cmd dos screen
 Linux:- texteditor
 compile:- javac filename
ex: javac [Link]

 Run: java classname


ex: java hello
 O/P : hello
---------------------------------------------------------------------------------------------------------------------
---------------------

2. How to create environment for Java Program

[Link] JDK

 Install Java Development Kit(JDK) ,which is freely available from sun Microsystems
 JRE(Java Runtime Environment) is nedded for running Java [Link] includes JRE.

[Link] JDK’s “bin” directory in the PATH.

 Windows OS searches the current directory and the directories listed in the PATH
environment variable for executable programs.
 You need to include the path where JDK is installed in the PATH.
 To edit PATH environment variable in windows .
Mycomputer  properties  Advanced  Environment variable  System Variable
 PATH  Edit
 variable name : path
 variable value: Insert path here ex: c:\program files\java\jsk1.8.0_XX\bin; (with
semicolon)
 Do not selete existing entries,otherwise some existing applications may not run.
 To edit path in Linux write in terminal :
 export JAVA_HOME=/path/to/java/jdk1.x

Parul Institute of Engineering & Technolgy (CSE) Page 56


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

3. Verify JDK installation

 Go to command prompt.
 prompt> path
PATH = c:\program files\Java\Jdk1.8.0_XX\bin;(other entries).

4. Checking the current Java version

 Checking the Java version in Windows


 Click Start > Control Panel > Java.
 On the Java tab, click View to display a list of all the installed Java versions. You can
enable and disable Java versions from this window.
From a command prompt
 Open a command prompt (Click to Start > Run, and then type cmd).
 Type java -version.
 The Java version and related information displays. For example:
 C:\Users\Authorized User>java -version
java version "1.7.0_15"
Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
Java HotSpot(TM) Client VM (build 23.1-b03, mixed mode, sharing)

 Checking the Java version in Mac


From the Java Control Panel
 From the Apple menu click System Preferences > Java.

Parul Institute of Engineering & Technolgy (CSE) Page 57


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR
 On the General tab of the Java Control Panel, click About.
 You can also review installed Java versions by clicking View on the Java tab.
 The above will only work if you have Oracle Java 1.7 or 1.8 installed on your machine. If
you do not see a Java Control Panel icon in System Preferences, you may instead be
using Apple Java 1.6, which does not have Java Control Panel functionality. If you are
using Apple Java 1.6, you may be able to investigate your Java version via Terminal
instead.
From Terminal
 Open Terminal (Navigate to Applications > Utilities > Terminal))
 Type java -version.
 The Java version and related information displays.

Checking the Java version in Linux


 Open Terminal (this can be different depending on which version of Linux you are
running. For example, in Ubuntu, navigate to Applications > Accessories > Terminal).
In Red Hat, right-click the desktop, and select Open in Terminal from the pull-down
menu.
1. Type java -version. // this will check your jre version
2. javac –version // this will check your java compiler version if you installed
3. which java
4. whereis java
5. echo $JAVA_HOME

5. Common Errors .

Error -1 :-JDK installation error

 java>javac [Link]
 Error: ‘javac ‘ is not recognized as an internal or external command,operable program
or batch file .
 Probable causes: PATH environment variable, which maintains a list of search paths for
executable programs,does not include JDK’s bin directory.
 Solutions: First write path command in command prompt Check it includes your JDK;s
bin directory or not If not then Include JDK’s bin directory in PATH environment
variable.

Error -2 :- Class file not found in current directory.

 java>java hello
 Error: could not find or load main class hello . or Exception thread “main”
[Link]:Hello
 Probable causes: Java class file is not in the current directory.
 CLASSPATH environment is set ,but does not include the current directory.
 Solutions: Write “dir” command to list the content of the current [Link] unix ls
command is used.

Parul Institute of Engineering & Technolgy (CSE) Page 58


JAVA & INTERNET TECHNOLOGY PREPARED BY:[Link] PATHAR

Error -3 :- main method is wrong.

 java>java hello
 Error: main method is not found in class could not find or load main class hello . or
Exception thread “main” [Link]:Hello
 Solutions: check whether syntax of main() method is correct or not?.

Error -4 :- can not compile Java program.

Solutions: You did not install JDK and JRE

Parul Institute of Engineering & Technolgy (CSE) Page 59

You might also like