Java Programming Basics and Concepts
Java Programming Basics and Concepts
SHITAL PATHAR
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.
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.
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.
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.
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]
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
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.
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.
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.
6. Polymorphism:
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.
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.
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.
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.
[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 .
[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.
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.
[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.
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
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.
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.
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 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
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
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”
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.
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
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
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
Output:
b1 value is = true
b1 value is = false
b1 value is = true
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
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.
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
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
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.
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.
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.
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;
class IfElse
{
public static void main(String args[])
{
int i = [Link](args[0]);
if(i > 0)
{
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.
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");
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.
class SwitchDemo
{
public static void main(String args[])
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.
class WhileDemo
{
public static void main(String args[])
{
int i = [Link](args[0]);
while(i > 0)
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.
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);
}
}
o for
Syntax: for(initialization; condition; iteration)
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.
class ForDemo
{
public static void main(String args[])
{
for(int num = 1; num < =5; num ++ )
[Link](“num =”+num);
}
}
Output: 1
2
3
4
5
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.
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.
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.
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.
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
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
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 };
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.
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
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
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
{
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.
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)
{
}
}
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.
.
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]();
}
}
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);
}
}
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);
}
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]();
}
}
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();
}
}
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]();
}
}
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
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]();
}
}
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]();
}
}
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
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;
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
class test
{
int a,b;
test( int i ,int j)
{
a = i;
b = j;
}
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.
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)
class Student
{
int id;
String name;
Student(int id,String name)
{
id = id;
name = name;
}
void display()
{
[Link](id+" "+name);
}
}
output: 0 null
0 null
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
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);
}
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
LIST OF QUESTIONS:
Extra :
---------------------------------------------------------------------------------------------------------------------
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]
[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.
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
Go to command prompt.
prompt> path
PATH = c:\program files\Java\Jdk1.8.0_XX\bin;(other entries).
5. Common Errors .
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.
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.
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?.