Unit - 1
Introduction
Q1) Introduce Java?
A1) Java is a robust, cross platform high level language. Java is based on object oriented programming which means it is designed using the concepts of object and classes.
Whenever a programmer writes a code in Java, that code can be available to run on any platform like LINUX, Windows or Mac OS. Also, this language is free to access for all users.
Most of the syntax in Java is derived from C and C++ programming language but eliminates the concept of pointers.
Why Java?
Java was intended to be not difficult to utilize and is hence simple to compose, compile, troubleshoot, and learn in comparison to other programming language.
Since Java is object-oriented, this permits you to make flexible program and reusable code Probably the main motivation why Java is so well known is one of its feature platforms independent.
Programs written in Java can run on numerous computer; as long as the computer has a Java Runtime Environment (JRE) installed, which allows a Java program to run on it.
Almost all kinds of computers are flexible with a JRE including computers running on Windows, Macintosh computers, Unix or Linux computers, and huge mainframe server computers, including mobile phones.
Since Java is from such a long time, probably the greatest organizations in the world are constructed utilizing the language such as Numerous banks, retailers, insurance agencies, etc.
Different versions of Java
● JDK Alpha and Beta: The first version which was released in 1995 as Java Alpha and Beta was highly unstable because of its APIs and ABIs.
● JDK 1.0: The first stable version came on 23 January 1996 JDK 1.0.2 also known as Java 1.
● JDK 1.1: This version was released on 19 February 1997 which includes new features like AWT event model, addition of inner classes, JavaBeans, JDBC, RMI, reflection and JIT.
● J2SE 1.2: This version release on 8 December 1998 with the codename playground. This version a signification release by Java as its size was three times of the Java platform. This version consists of 1520 classes in 59 packages. Some new features added like strictfp keyword, Swing graphical API, Java plug-in, Java IDl and collections.
● J2SE 1.3: This version was one of the famous version came on 8 May 2000 with codename Kestrel. The main changes done in this version were inclusion of HotSpot JVM, modified RMI compatible with COBRA, Java Naming and Directory Interface (JNDI) libraries, Java Platform Debugger Architecture (JPDA) and Java Sound.
● J2SE 1.4: This version was the first version to release under Java Community Process as JSR on 6 February 2002. The major changes in this version include: addition of assert keyword and library improvement (such as exception chaining, IPv6 support, Non-blocking I/O etc).
● J2SE 5.0: This version was initially named as 1.5 but further changed to 5.0 to show the maturity, stability, scalability and security. This version was released on 30 September 2004 with code name tiger. New language features that were added like generics, metadata, autoboxing, enumerations, Varags, improved semantics and static imports.
● Java SE 6: Released on 11 December 2006 with codename mustang. Sun released this version as Java SE instead of J2SE. Some of the major changes include in this version were scripting language support, JDBC 4.0 support Java compiler API, support for Pluggable annotations etc.
● Java SE 7: This update with codename dolphin was released on 7 July 2011. Major additions in Java 7 were JVM support for dynamic languages, compressed 64-bit pointers, concurrency utilities under JSR, upstream updates to XML, java deployment rule sets.
● Java SE 8: This version was released on 18 March 2014 with codename spider. Some of the major changes that were done in Java SE 8 are support for lambda expression, JavaScript embed into applications, repeating annotations, launching of JavaFX applications and permanent generation removal.
● Java SE 9: The release of this version was delayed many time and finally released on 21 September 2017. This version provides improved support to native code integration, multi-gigabyte heaps, garbage collector and self tuning JVM.
● Java SE 10: Java SE 10 was released on 20 March 2018. This version was released with aim to remove primitive data types and support to 64 bit addressable arrays with some additional new features. These features were local variable type inference, application class data sharing, parallel full GC for GI, root certificates and many more.
● Java SE 11: This version also known as JDK 11 was released on 25 September 2018. Still its bug fixes are going on.
● Java SE 12: This was version was released 19 March 2019 with some fewer changes.
Q2) What are the features of java?
A2) Features of Java
● Object Oriented: Java is a complete object oriented language. This means that everything in Java revolves around the use of Objects.
● Secure: Java is a very secure language; one of the main reasons is the lack of pointers. Virus free software’s can be developed using Java programming constructs.
● Robust: Java is a very robust language because of features like automatic garbage collection, memory management, exception handling, etc.
● Portable: One of the very important features of Java is that can be used on any platform without any problems. This means that it allows you to run the Java Bytecode on any platform.
● Simple: Java is a simple language because of its ease of use and less complicated features.
● Platform Independent: Java is a ‘write’ once, ‘run’ anywhere language, which means that once written, it has the capability to be executed on any machine that has Java Runtime Environment (JRE).
Q3) What is the history of java?
A3) History behind Java
Nowadays Java is one such language which is used worldwide including internet, mobiles, games, e-commerce etc.
Let’s have a look at the history of Java and see how it comes so far:
- In June 1991, the first project written in Java is initiated by a team of three members having James Gosling, Mike Sheridan and Patrick Naughton. This team of sun engineers become famous as Green Team.
- The initial purpose of using Java was for small, embedded systems such as TV set-top boxes.
- At first it was referred as Green talk by James Gosling and the file extension for it was decided is .gt.
- Then James Gosling referred it as Oak which was developed as a part of Green project.
- Since Oak was already a trademark used by Oak Technologies, so in 1995 it was renamed as Java.
- Before selecting the name Java the team had huge discussion among names suggested like dynamic, revolutionary, silk, jolt, DNA etc. Team wants to select such a name which reflects the nature of technology. So finally the team members preferred Java over other names.
- The first public implementation of Java was made in 1995 as Java 1.0 by Sun. It is based on the concept of Write once and Run Anywhere on any platforms.
- In 2006, Sun finally released Java’s some code as free and open source software Under GNU General Public License (GPL).
- And finally, in 2007 Sun declared Java’s all core code free and open source so that anyone can use it without any restrictions.
Q4) Define byte code?
A4) The Java Virtual Machine's instruction set is known as Java bytecode. It functions similarly to an assembler, which is an alias for C++ code. Java bytecode is generated as soon as a java programme is compiled. Java bytecode, to put it another way, is machine code in the form of a.class file. We can achieve platform independence in Java by using java bytecode.
How does it work?
When we develop a Java programme, the compiler first compiles it and generates bytecode for it. We can run this.class file on any other platform if we want to. The Java Virtual Machine, not the processor in question, now runs the bytecode generated after the first compilation. This effectively means that on whatever platform where we wish to run our code, we only need a minimal java installation. The Java Virtual Machine makes the resources needed to run the bytecode available by instructing the processor to allocate them. Because JVMs are stack-based, they must stack implementations in order to read the codes.
Fig 1: Working of byte code
Advantages
One of the main reasons James Gosling founded Java was to achieve platform independence, and it is this implementation of bytecode that allows us to do so. As a result, bytecode is an essential part of each Java application. The JVM's set of instructions may vary from system to system, but all can decode bytecode. Keep in mind that bytecodes are non-runnable programmes that require on the presence of an interpreter to execute, which is where the JVM comes in.
Bytecode is a machine-level programming language that runs on the Java Virtual Machine. When a class is loaded, it receives a stream of bytecode for each of its methods. The bytecode for that method is invoked whenever that method is called during the execution of a programme. Javac not only compiles a programme, but it also generates bytecode for it.
As a result, we've realized that Java's bytecode implementation makes it platform-independent. This contributes to Java's portability, which is lacking in languages like C and C++. Java's portability assures that it may be used on a wide range of platforms, including computers, mobile devices, servers, and more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.
Q5) Explain java virtual machine?
A5) JVM (Java Virtual Machine) is a program that gives us the flexibility to execute Java programs. It provides a runtime environment to execute the Java code or applications.
This is the reason why Java is said to platform independent language as it requires JVM on the system it runs its Java code.
JVM is also used to execute programs of other languages that are compiled to Bytecode.
JVM can also be describe as:
- A specification where JVM working is pre defined.
- An implementation like JRE (Java Runtime Environment) is required.
- Runtime Instance means wherever a program is run on command prompt using java command, an instance of JVM is created.
Significance of JVM
JVM is used for two primary functions
- It allows Java programs to use the concept of “Write Once and Run Anywhere”.
- It is utilized to manage and optimize memory usage for programs.
Architecture of JVM
Java applications require a run-time engine which is provided by JVM. The main method of Java program is called by JVM. JVM is a subsystem of JRE (Java Runtime Environment).
Let’s see the internal architecture of JVM as shown in the figure below:
Fig 2: Architecture of JVM
- Class Loader: This part is used to load class files. There are three major functions of class loader as Loading, Linking and Initialization.
- Method Area: Structure of class like metadata, the constant runtime pool, and the code for methods are stored method area.
- Heap: Heap is the memory where all the objects, instance variables and arrays are stored. This is a shared memory which is accessed by multiple threads.
- JVM Language Stacks: These hold the local data variables and their results. Each thread has their own JVM stack used to store data.
- PC Registers: The currently running IVM instructions are stored in PC Registers. In Java, every thread has its their own PC register.
- Native Method Stacks: It hold the instruction of native code depending on their native library.
- Execution Engine: This engine is used to test the software, hardware or complete system. It doesn’t contain any information about the tested product.
- Native Method Interface: It is a programming interface. It allows Java code to call by libraries and native applications.
- Native Method Libraries: It consists of native libraries which are required by execution engine.
Q6) Describe JDK?
A6) The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
The Java Development Kit (JDK) is a cross-platform software development environment that includes a set of tools and libraries for creating Java-based applications and applets. Along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment), it is a key package used in Java (Java Runtime Environment).
Beginners frequently confuse JRE and JDK; nevertheless, if all you want to do is launch Java programmes on your machine, you may do so with ease using Java Runtime Environment. However, if you want to create a Java-based software programme, you'll probably need some extra tools, such as JDK, in addition to JRE.
JDK is an implementation of any of Oracle Corporation's Java Platforms, as listed below:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
To finish the creation of a Java application, the JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and so on.
Fig 3: JDK
Components of JDK in Java
The following is a list of the JDK's core components in Java.
● java - In older SUN Java, it serves as a deployment launcher. It interprets the source code compiled by the javac compiler after loading the class files.
● javac - The java compiler is used to transform the source code to bytecode, as specified by javac.
● javadoc - The javadoc tool creates documentation for comments contributed to source code.
● jar - The jar aids in the management of jar files in the package library by the archives.
● jps - Java Virtual Machine Process Status Tool is abbreviated as jps. It keeps track of the active JVMs for the current programme.
● appletviewer - The appletviewer is a programme that allows you to run and debug Java applets without using the internet.
● idlj - An IDL-to-Java compiler converts a Java IDL file into Java bindings.
● javap - The javap performs the function of a file disassembler.
● JConsole - JConsole is a Java management and monitoring application.
● javah - The javah is a stub-generator, and native methods are written with C-Header.
● javaws - For JNLP apps, javaws serves as a Web Start launcher.
● jhat - The jhat is a tool for heap analysis.
● jmc - The abbreviation jmc stands for Java Mission Control.
Q7) Why JDK used?
A7) The Java Development Kit includes a number of tools as well as knowledge on Java development. Downloading JDK software and blending it with the classpath is all it takes to deploy Java software. After downloading and installing JDK, the only method to run the software is to select the correct version of Java. Although Java 8 is the most widely used version, Java 10 is the most recent version that is also available online.
JDK is a collection of directories that are used to implement the Java platform standard, including class libraries and the compiler. It's also referred to as the JRE's superset.
Q8) Define data types in java?
A8) Various data types are used in Java. These data types are used to represent the memory allocation. Every data type has a different amount of memory allocation associated with it.
They are also called primitive data types in Java.
- Byte: The byte data type is an 8-bit signed two's complement integer. Range is -128 to 127.
- Short: The short data type is a 16-bit signed two's complement integer. Range is -32,768 to 32,767 (inclusive).
- Int: The int data type is a 32-bit signed two's complement integer. Range is -231 to 231-1.
- Long: The long data type is a 64-bit two's complement integer. Range is -263 to 263-1.
- Float: The float data type is a 32-bit IEEE 754 floating point.
- Double: The double data type is a 64-bit IEEE 754 floating point.
- Boolean: true and false are two possible values of the boolean data type.
- Char: The char data type is a single 16-bit Unicode character. Range is '\u0000' (or 0) to '\uffff'.
Q9) Explain operators in java?
A9) Different types of Operators
Following are various types of operators in Java:
- Arithmetic Operators
- Unary Operators
- Relational Operators
- Logical Operators
- Boolean Operators
- Bitwise Operators
- Ternary Operators
- New Operators
- Cast Operators
1. Arithmetic Operators: They are the type of operators that perform an operation on two operands.
+, -, *, /, % are various Arithmetic operators
+ is the Addition operator
- is the Subtraction operator
* is the Multiplication operator
/ is the division operator
% is the remainder operator also called as modulus operator
Lets see a program on this concept
Code:
Class ArithmeticOperators{
Public static void main(String[] args) {
Double n1 = 12.5, n2 = 3.5, add, subtract, multiply, divide, mod;
// This is how you use the addition operator
Add = n1 + n2;
System.out.println("n1 + n2 = " +add);
// This is how you use the subtraction operator
Subtract = n1 - n2;
System.out.println("n1 - n2 = " +subtract);
// This is how you use the multiplication operator
Multiply = n1 * n2;
System.out.println("n1 * n2 = " +multiply);
// This is how you use the division operator
Divide = n1 / n2;
System.out.println("n1 / n2 = " +divide);
// This is how you use the mod or remainder operator
Mod = n1 % n2;
System.out.println("n1 % n2 = " +mod);
}
}
Output:
2. Unary Operators: They are the types of operators that perform an operation on one operand.
+ is the Unary Plus Operator
- is the Unary Minus Operator. It inverts sign of an expression
++ is the Increment Operator. Increments value by 1
-- is the decrement Operator. Decreases value by 1
! is the Logical complement Operator. It inverts the value of a boolean, i.e. true to false and false to true
Program:
Class UnaryOperator {
Public static void main(String[] args) {
Double number = 5.2, unaryPlus, unaryMinus, increment, decrement, unaryLogical;
Boolean flag = false;
System.out.println("+ unaryPlus = " + +number);
System.out.println("- unaryMinus= " + -number);
System.out.println("++ increment = " + ++number);
System.out.println("-- decrement= " + --number);
System.out.println("! unaryLogical: !flag = " + !flag);
}
}
Output:
3. Relational Operators: Also called as equality and relational operators, these operators determine the relationship between the two operands.
== is the Equal to operator
!= is the Not equal to operator
> is the Greater than operator
>= is the Greater than or equal to operator
< is the Less than operator
<= is the Less than or equal to operator
Program:
Class RelationalOperators {
Public static void main(String args[]) {
Int x = 50;
Int y = 70;
System.out.println("x == y = " + (x == y) );
System.out.println("x != y = " + (x != y) );
System.out.println("x < y = " + (x < y) );
System.out.println("x > y = " + (x > y) );
System.out.println("y <= x = " + (y <= x) );
System.out.println("y >= x = " + (y >= x) );
}
}
Output:
4. Logical Operators: Also called as conditional operators, Logical operators operate on boolean expressions. Various Logical operators are:
&& Conditional-AND, its true only if all boolean expressions are true
|| Conditional-OR, its true if either of the boolean expression is true
Program:
Class LogicalOperators{
Public static void main(String args[]) {
Boolean n = false;
Boolean m = true;
System.out.println("m && n = " + (m&&n));
System.out.println("!(m && n) = " + !(m && n));
System.out.println("m || n = " + (m||n) );
}
}
Output:
5. Boolean Operators: These operators operate only on Boolean Operands
& denotes the AND operator
| denotes the OR operator
^ denotes the XOR operator
! denotes the NOT operator
!= denotes the NOT EQUAL TO operator
== denotes the EQUAL TO operator
Program:
Class BooleanOperators{
Public static void main(String args[]){
Boolean X = true;
Boolean Y = false;
System.out.println("X&Y = "+(X&Y));
System.out.println("X|Y = "+(X|Y));
System.out.println("X^Y = "+(X^Y));
System.out.println("!X = "+(!X));
System.out.println("X!=Y = "+(X!=Y));
System.out.println("X==Y = "+(X==Y));
System.out.println("(X|Y)&X = "+((X|Y)&X));
}
}
Output:
6. Bitwise Operators: They are used to perform bit shift operators in Java.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Program:
Class BitwiseOperators {
Public static void main(String[] args)
{
Int x = 5;
Int y = 7;
// bitwise AND 0101 & 0111=0101 = 5
System.out.println("x&y = " + (x & y));
// bitwise OR 0101 | 0111=0111 = 7
System.out.println("x|y = " + (x | y));
// bitwise XOR 0101 ^ 0111=0010 = 2
System.out.println("x^y = " + (x ^ y));
// bitwise AND ~0101=1010, will give 2's complement of 1010 = -6
System.out.println("~x = " + ~x);
// can be combined with assignment operator for shorthand assignment x=x&y
x &= y;
System.out.println("x= " + x);
}
}
Output:
7. Ternary Operators: It is the only operator that takes three operands. It can be used to replace if-else statements as well as switch statements.
Program:
Class TernaryOperator {
Public static void main(String[] args) {
Double num = -5.5;
String verdict;
Verdict = (num>0.0) ? "Positive" : "Not Positive";
System.out.println("The Number " +num+ " is " +verdict);
}
}
Output:
8. New Operator: The new operator instantiates a class by dynamically allocating (i.e., allocation at run time) memory for a new object and returning a reference to that memory.
Program:
Class Square
{
double squareSide;
}
public class NewOperator
{
Public static void main(String[] args)
{
Square s1 = new Square();
// assigning s2 to s1
Square s2 = s1;
s2.squareSide = 20;
System.out.println(s1.squareSide);
System.out.println(s2.squareSide);
}
}
Output:
M
Up casting: Java Virtual Machine (JVM) performs automatic conversion.
Byte => short => int => long => float => double
e.g. int j = 5;
Long i = j;
Down Casting: Also called as explicit casting, this can be best explained through an example.
e.g. int j = 5;
Long i = j;
Byte b1=j; //compile time error
Byte b2=(byte)j; //allowed. Explicit casting is done
Q10) Describe conditional statements?
A10) Conditional statements are used to choose the path for execution. These are of three types: if/else/else if, ternary and switch.
1. If statement
The simplest form of control structure is if statement. This statement checked a Boolean expression, if the expression value is true then the program enters a block of code; otherwise if Boolean expression value is false it skip if statement block.
Syntax of if statement is:
If(Boolean condition)
{
Line 1; //it will execute only when if statement holds true
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“Output is true”);
}
}
}
Output:
Output is true
2. If-else statement
An extended version of if statement, which use a second block of code which is known as else block in the situation when if condition fails.
Syntax of if else statement:
If(Boolean condition)
{
Line 1; // it will execute only when if statement holds true
}
Else
{
Line 2; // it will execute only when if statement holds false
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“if condition is true”);
}
Else
{
System.out.println(“if condition is false”);
}
}
}
Output:
If condition is true
3. If-else-if ladder or Nested if-else condition
In nested if-else condition first if condition is followed by many else-if conditions. In other way we can define it as a decision tree of if-else-if statement where we have to make multiple choices based on combination of conditions.
Syntax of nested if-else condition:
If(Boolean condition 1) {
Statement 1; //it will executes when condition 1 is true
}
Else if(Boolean condition 2) {
Statement 2; // it will executes when condition 2 is true
}
Else {
Statement 2; //it will executes when all the conditions are false
}
Example:
Public class Example {
Public static void main(String[] args) {
Int a = 15;
If(a < 10) {
System.out.println("a is less than 10");
}else if (a = 12) {
System.out.println("a is equal to 12");
}else if(a > 10) {
System.out.println("a is greater than 10");
}else {
System.out.println(a);
}
}
}
Output:
a is greater than 10
4. Ternary Condition
Ternary condition is an enhancement or shorthand to the if-else condition. The working of ternary and if-else condition is same.
Consider an example of if-else:
If (a > 2) {
System.out.println("a is higher than 2");
} else {
System.out.println("a is lower or equal to 2");
}
Now see the same code in ternary condition
System.out.println(a > 2 ? "a is higher than 2" : "a is lower or equal to 2");
5. Switch condition
Switch conditions in Java are almost same as nested if-else statement.
Switch conditions are designed using multiple blocks of codes known as cases. Among so many cases a single case is executed based on the condition mentioned in the switch.
They are simple to use in comparison to nested if-else. While writing switch statements few things need to be kept in mind:
● We cannot create duplicate case. Each case will be different.
● The variables we can use in case are int, short, byte, char or enumeration. Strings are also supported.
● If all cases fail, then only default statement will be executed.
● While using switch statement, we use break statement also. Break statement will terminate the execution after switch case is satisfied, otherwise next case will be executed.
● The case expression variable must be same as at the time of declaration.
Syntax of switch statement:
Switch (condition){
Case data1:
Statement 1;
Break;
.
.
.
Case dataN:
Statement N;
Break;
Default:
Default statement;
}
Example:
Class Student
Public static void main(String[] args) {
Int a = 2;
Switch (a){
Case 0:
System.out.println("value is 0");
Break;
Case 1:
System.out.println("value is 1");
Break;
Default:
System.out.println(a);
}
}
}
Q11) Explain for, while and do while loop?
A11) For loop
Just like C and C++, for loop in Java is also same. A for loop is used to execute a set of code several times.
For loop consists of three parts. First part is used to initialize the loop variable, second part contains the condition and the third part increment/decrement the variable. For loop is defined in a single line.
Syntax of for loop:
For(initialization, condition, increment or decrement)
{
//block of statements to be executed
}
Example
Class Example
{
Public static void main(String[] args)
{
Int s = 1;
For(int i = 1; i<=5; i++) {
s = s + i;
}
System.out.println("The sum = " + s);
}
}
Output:
The sum = 6
While loop
The while loop statement is also used to repeat the execution of code multiple times.
While loops are preferable to use when we don’t know the exact number of iterations to be done in advance.
Here the initialization of variable and increment/decrement is done outside the loop statement.
In while loop the condition is checked first, if the condition is true then only execution will be done inside the loop; otherwise outside loop statements will be executed.
While loops are also know as entry controlled loop.
Syntax of while loop
While(condition){
//looping statements
}
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
While(a<=5) {
System.out.println(a);
a = a+ 1;
}
}
}
Output:
The list of first 5 even numbers
1
2
3
4
5
Do-while loop
In do-while loop statements are executed first then the condition is evaluated at the end of the loop.
It can we use on those places where we want to execute the statements at least once.
The do-while loops are also known as the exit controlled loop.
Syntax of do-while loop:
Do
{
Statements
} while (condition);
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
Do {
System.out.println(a);
a = a+ 1;
} while(a<=5)
}
}
Q12) Describe jumping statements?
A12) Jump statements are used to change the execution flow of the program to some other specific statements.
In Java there are two types of jump statements: break and continue.
1. Break statement
It is used to immediately terminate the execution of a loop and the control will be passing on to the next statement after the loop.
Break statement are always used inside a loop or switch statement, they cannot be used independently.
Example
Class Example {
Public static void main(String[] args) {
For(int a = 1; a<= 5; a++) {
System.out.println(a);
If(a==3) {
Break;
}
}
}
}
Output
1
2
3
2. Continue statement
Continue statements are used when we want to skip only specific part of the loop and jumps to the next instruction in the loop immediately, while break statement terminates the loop.
It can be used with for or while loop.
Example
Class Example
{
Public static void main(String arg[])
{
For(int x = 0; x <=3; x++)
{
If(x == 1)
Continue;
System.out.println("Number= " + x);
}
}
}
Output
Number = 0
Number = 2
Number = 3
Q13) Explain methods?
A13) In general, a method is a manner of accomplishing a goal. In Java, a method is a collection of instructions that accomplishes a specified goal. It ensures that code can be reused. Methods can also be used to easily alter code. We'll study what a method is in Java, the different sorts of methods, how to declare a method, and how to invoke a method in Java in this part.
What is a method in Java?
A method is a collection of statements or a series of statements organized together to conduct a specific task or action. It's a technique for making code more reusable. We create a method once and then use it repeatedly. We don't have to write code over and over again.
It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.
Method Declaration
Method properties such as visibility, return-type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.
Fig 4: Method declaration
Method Signature: A method signature is a description of a method. It's included in the method declaration. It contains the method name as well as a list of parameters.
Access Specifier: The method's access specifier or modifier is the method's access type. It specifies the method's visibility. There are four different types of access specifiers in Java:
● public - When we utilise the public specifier in our application, all classes can access the method.
● private - The method is only accessible in the classes in which it is declared when we use a private access specifier.
● protected - The method is accessible within the same package or subclasses in a different package when we use the protected access specifier.
● default - When no access specifier is specified in the method declaration, Java uses the default access specifier. It is visible only from the same package only.
Return Type: The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything.
Method Name: It's a one-of-a-kind moniker that's used to specify a method's name. It must be appropriate for the method's functionality. If we're making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.
Parameter List: It consists of a list of parameters separated by a comma and contained in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.
Method Body: It's included in the method declaration. It contains all of the actions that must be completed. It is protected by a pair of curly braces.
Q14) Write the types of methods?
A14) Types of Method
There are two types of methods in Java:
● Predefined Method
● User-defined Method
Predefined Method
Predefined methods in Java are methods that are previously defined in the Java class libraries. It's also known as the built-in method or the standard library approach. We can use these methods directly by calling them at any time in the application. Length(), equals(), compareTo(), sqrt(), and other pre-defined methods are examples. When we call any of the predefined methods in our software, a set of codes relevant to that method run in the background, which are already saved in the library.
Every predefined method is contained within a class. The java.io.PrintStream class, for example, defines the print() function. It outputs the statement we typed into the method. For example, print("Java"), it prints Java on the console.
Example
Demo.java
Public class Demo
{
Public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output
The maximum number is: 9
We utilized three predefined methods in the preceding example: main(), print(), and max() (). Because these methods are predefined, we have utilised them without declaring them. The PrintStream class has a print() function that prints the result to the console. The greater of two numbers is returned by the max() function of the Math class.
User-defined Method
A user-defined method is a method that is written by the user or programmer. These strategies are tweaked to meet the needs of the situation.
How to Create a User-defined Method
Let's build a user-defined mechanism for determining whether an integer is even or odd. We'll start by defining the method.
//user defined method
Public static void findEvenOdd(int num)
{
//method body
If(num%2==0)
System.out.println(num+" is even");
Else
System.out.println(num+" is odd");
}
The following method, entitled find even odd, has been defined (). It has an int-type parameter called num. We used void because the method does not return any value. The procedures to determine whether a number is even or odd are contained in the method body. If the number is even, it will be printed as such; otherwise, it will be printed as odd.
Q15) Write a program to print this using a for loop?
*
* *
* * *
* * * *
* * * * *
A15) Program
Public class PyramidExample {
Public static void main(String[] args) {
For(int i=1;i<=5;i++){
For(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Q16) Write a program to print a pattern?
* * * * * *
* * * * *
* * * *
* * *
* *
*
A16) Program
Public class PyramidEg {
Public static void main(String[] args) {
Int term=6;
For(int i=1;i<=term;i++){
For(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Q17) Write the difference between for, while, and do while loop in java?
A17) Difference between for, while and do while loop
Difference | For Loop | While Loop | Do-While Loop |
Introduction | For loop in Java iterates a given set of statements multiple times. | The Java while loop executes a set of instructions until a boolean condition is met. | The do-while loop executes a set of statements at least once, even if the condition is not met. After the first execution, it repeats the iteration until the boolean condition is met. |
Best time to use | Use it when you know the exact number of times to execute the part of the program. | Use it when you don’t know how many times you want the iteration to repeat. | Use it when you don’t know how many times you want the iteration to repeat, but it should execute at least one time. |
Syntax | For(init; condition; icr/dcr){ //statements to be repeated } | While(condition){ //statements to be repeated } | Do{ //statements to be repeated }while(condition); |
Example | For(int x=0; x<=5; x++){ System.out.println(x); } | Int x=0; While(x<=5){ System.out.println(x); x++; } | Int x=0; Do{ System.out.println(x); x++; }while(x<=5); |
Unit - 1
Introduction
Q1) Introduce Java?
A1) Java is a robust, cross platform high level language. Java is based on object oriented programming which means it is designed using the concepts of object and classes.
Whenever a programmer writes a code in Java, that code can be available to run on any platform like LINUX, Windows or Mac OS. Also, this language is free to access for all users.
Most of the syntax in Java is derived from C and C++ programming language but eliminates the concept of pointers.
Why Java?
Java was intended to be not difficult to utilize and is hence simple to compose, compile, troubleshoot, and learn in comparison to other programming language.
Since Java is object-oriented, this permits you to make flexible program and reusable code Probably the main motivation why Java is so well known is one of its feature platforms independent.
Programs written in Java can run on numerous computer; as long as the computer has a Java Runtime Environment (JRE) installed, which allows a Java program to run on it.
Almost all kinds of computers are flexible with a JRE including computers running on Windows, Macintosh computers, Unix or Linux computers, and huge mainframe server computers, including mobile phones.
Since Java is from such a long time, probably the greatest organizations in the world are constructed utilizing the language such as Numerous banks, retailers, insurance agencies, etc.
Different versions of Java
● JDK Alpha and Beta: The first version which was released in 1995 as Java Alpha and Beta was highly unstable because of its APIs and ABIs.
● JDK 1.0: The first stable version came on 23 January 1996 JDK 1.0.2 also known as Java 1.
● JDK 1.1: This version was released on 19 February 1997 which includes new features like AWT event model, addition of inner classes, JavaBeans, JDBC, RMI, reflection and JIT.
● J2SE 1.2: This version release on 8 December 1998 with the codename playground. This version a signification release by Java as its size was three times of the Java platform. This version consists of 1520 classes in 59 packages. Some new features added like strictfp keyword, Swing graphical API, Java plug-in, Java IDl and collections.
● J2SE 1.3: This version was one of the famous version came on 8 May 2000 with codename Kestrel. The main changes done in this version were inclusion of HotSpot JVM, modified RMI compatible with COBRA, Java Naming and Directory Interface (JNDI) libraries, Java Platform Debugger Architecture (JPDA) and Java Sound.
● J2SE 1.4: This version was the first version to release under Java Community Process as JSR on 6 February 2002. The major changes in this version include: addition of assert keyword and library improvement (such as exception chaining, IPv6 support, Non-blocking I/O etc).
● J2SE 5.0: This version was initially named as 1.5 but further changed to 5.0 to show the maturity, stability, scalability and security. This version was released on 30 September 2004 with code name tiger. New language features that were added like generics, metadata, autoboxing, enumerations, Varags, improved semantics and static imports.
● Java SE 6: Released on 11 December 2006 with codename mustang. Sun released this version as Java SE instead of J2SE. Some of the major changes include in this version were scripting language support, JDBC 4.0 support Java compiler API, support for Pluggable annotations etc.
● Java SE 7: This update with codename dolphin was released on 7 July 2011. Major additions in Java 7 were JVM support for dynamic languages, compressed 64-bit pointers, concurrency utilities under JSR, upstream updates to XML, java deployment rule sets.
● Java SE 8: This version was released on 18 March 2014 with codename spider. Some of the major changes that were done in Java SE 8 are support for lambda expression, JavaScript embed into applications, repeating annotations, launching of JavaFX applications and permanent generation removal.
● Java SE 9: The release of this version was delayed many time and finally released on 21 September 2017. This version provides improved support to native code integration, multi-gigabyte heaps, garbage collector and self tuning JVM.
● Java SE 10: Java SE 10 was released on 20 March 2018. This version was released with aim to remove primitive data types and support to 64 bit addressable arrays with some additional new features. These features were local variable type inference, application class data sharing, parallel full GC for GI, root certificates and many more.
● Java SE 11: This version also known as JDK 11 was released on 25 September 2018. Still its bug fixes are going on.
● Java SE 12: This was version was released 19 March 2019 with some fewer changes.
Q2) What are the features of java?
A2) Features of Java
● Object Oriented: Java is a complete object oriented language. This means that everything in Java revolves around the use of Objects.
● Secure: Java is a very secure language; one of the main reasons is the lack of pointers. Virus free software’s can be developed using Java programming constructs.
● Robust: Java is a very robust language because of features like automatic garbage collection, memory management, exception handling, etc.
● Portable: One of the very important features of Java is that can be used on any platform without any problems. This means that it allows you to run the Java Bytecode on any platform.
● Simple: Java is a simple language because of its ease of use and less complicated features.
● Platform Independent: Java is a ‘write’ once, ‘run’ anywhere language, which means that once written, it has the capability to be executed on any machine that has Java Runtime Environment (JRE).
Q3) What is the history of java?
A3) History behind Java
Nowadays Java is one such language which is used worldwide including internet, mobiles, games, e-commerce etc.
Let’s have a look at the history of Java and see how it comes so far:
- In June 1991, the first project written in Java is initiated by a team of three members having James Gosling, Mike Sheridan and Patrick Naughton. This team of sun engineers become famous as Green Team.
- The initial purpose of using Java was for small, embedded systems such as TV set-top boxes.
- At first it was referred as Green talk by James Gosling and the file extension for it was decided is .gt.
- Then James Gosling referred it as Oak which was developed as a part of Green project.
- Since Oak was already a trademark used by Oak Technologies, so in 1995 it was renamed as Java.
- Before selecting the name Java the team had huge discussion among names suggested like dynamic, revolutionary, silk, jolt, DNA etc. Team wants to select such a name which reflects the nature of technology. So finally the team members preferred Java over other names.
- The first public implementation of Java was made in 1995 as Java 1.0 by Sun. It is based on the concept of Write once and Run Anywhere on any platforms.
- In 2006, Sun finally released Java’s some code as free and open source software Under GNU General Public License (GPL).
- And finally, in 2007 Sun declared Java’s all core code free and open source so that anyone can use it without any restrictions.
Q4) Define byte code?
A4) The Java Virtual Machine's instruction set is known as Java bytecode. It functions similarly to an assembler, which is an alias for C++ code. Java bytecode is generated as soon as a java programme is compiled. Java bytecode, to put it another way, is machine code in the form of a.class file. We can achieve platform independence in Java by using java bytecode.
How does it work?
When we develop a Java programme, the compiler first compiles it and generates bytecode for it. We can run this.class file on any other platform if we want to. The Java Virtual Machine, not the processor in question, now runs the bytecode generated after the first compilation. This effectively means that on whatever platform where we wish to run our code, we only need a minimal java installation. The Java Virtual Machine makes the resources needed to run the bytecode available by instructing the processor to allocate them. Because JVMs are stack-based, they must stack implementations in order to read the codes.
Fig 1: Working of byte code
Advantages
One of the main reasons James Gosling founded Java was to achieve platform independence, and it is this implementation of bytecode that allows us to do so. As a result, bytecode is an essential part of each Java application. The JVM's set of instructions may vary from system to system, but all can decode bytecode. Keep in mind that bytecodes are non-runnable programmes that require on the presence of an interpreter to execute, which is where the JVM comes in.
Bytecode is a machine-level programming language that runs on the Java Virtual Machine. When a class is loaded, it receives a stream of bytecode for each of its methods. The bytecode for that method is invoked whenever that method is called during the execution of a programme. Javac not only compiles a programme, but it also generates bytecode for it.
As a result, we've realized that Java's bytecode implementation makes it platform-independent. This contributes to Java's portability, which is lacking in languages like C and C++. Java's portability assures that it may be used on a wide range of platforms, including computers, mobile devices, servers, and more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.
Q5) Explain java virtual machine?
A5) JVM (Java Virtual Machine) is a program that gives us the flexibility to execute Java programs. It provides a runtime environment to execute the Java code or applications.
This is the reason why Java is said to platform independent language as it requires JVM on the system it runs its Java code.
JVM is also used to execute programs of other languages that are compiled to Bytecode.
JVM can also be describe as:
- A specification where JVM working is pre defined.
- An implementation like JRE (Java Runtime Environment) is required.
- Runtime Instance means wherever a program is run on command prompt using java command, an instance of JVM is created.
Significance of JVM
JVM is used for two primary functions
- It allows Java programs to use the concept of “Write Once and Run Anywhere”.
- It is utilized to manage and optimize memory usage for programs.
Architecture of JVM
Java applications require a run-time engine which is provided by JVM. The main method of Java program is called by JVM. JVM is a subsystem of JRE (Java Runtime Environment).
Let’s see the internal architecture of JVM as shown in the figure below:
Fig 2: Architecture of JVM
- Class Loader: This part is used to load class files. There are three major functions of class loader as Loading, Linking and Initialization.
- Method Area: Structure of class like metadata, the constant runtime pool, and the code for methods are stored method area.
- Heap: Heap is the memory where all the objects, instance variables and arrays are stored. This is a shared memory which is accessed by multiple threads.
- JVM Language Stacks: These hold the local data variables and their results. Each thread has their own JVM stack used to store data.
- PC Registers: The currently running IVM instructions are stored in PC Registers. In Java, every thread has its their own PC register.
- Native Method Stacks: It hold the instruction of native code depending on their native library.
- Execution Engine: This engine is used to test the software, hardware or complete system. It doesn’t contain any information about the tested product.
- Native Method Interface: It is a programming interface. It allows Java code to call by libraries and native applications.
- Native Method Libraries: It consists of native libraries which are required by execution engine.
Q6) Describe JDK?
A6) The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
The Java Development Kit (JDK) is a cross-platform software development environment that includes a set of tools and libraries for creating Java-based applications and applets. Along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment), it is a key package used in Java (Java Runtime Environment).
Beginners frequently confuse JRE and JDK; nevertheless, if all you want to do is launch Java programmes on your machine, you may do so with ease using Java Runtime Environment. However, if you want to create a Java-based software programme, you'll probably need some extra tools, such as JDK, in addition to JRE.
JDK is an implementation of any of Oracle Corporation's Java Platforms, as listed below:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
To finish the creation of a Java application, the JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and so on.
Fig 3: JDK
Components of JDK in Java
The following is a list of the JDK's core components in Java.
● java - In older SUN Java, it serves as a deployment launcher. It interprets the source code compiled by the javac compiler after loading the class files.
● javac - The java compiler is used to transform the source code to bytecode, as specified by javac.
● javadoc - The javadoc tool creates documentation for comments contributed to source code.
● jar - The jar aids in the management of jar files in the package library by the archives.
● jps - Java Virtual Machine Process Status Tool is abbreviated as jps. It keeps track of the active JVMs for the current programme.
● appletviewer - The appletviewer is a programme that allows you to run and debug Java applets without using the internet.
● idlj - An IDL-to-Java compiler converts a Java IDL file into Java bindings.
● javap - The javap performs the function of a file disassembler.
● JConsole - JConsole is a Java management and monitoring application.
● javah - The javah is a stub-generator, and native methods are written with C-Header.
● javaws - For JNLP apps, javaws serves as a Web Start launcher.
● jhat - The jhat is a tool for heap analysis.
● jmc - The abbreviation jmc stands for Java Mission Control.
Q7) Why JDK used?
A7) The Java Development Kit includes a number of tools as well as knowledge on Java development. Downloading JDK software and blending it with the classpath is all it takes to deploy Java software. After downloading and installing JDK, the only method to run the software is to select the correct version of Java. Although Java 8 is the most widely used version, Java 10 is the most recent version that is also available online.
JDK is a collection of directories that are used to implement the Java platform standard, including class libraries and the compiler. It's also referred to as the JRE's superset.
Q8) Define data types in java?
A8) Various data types are used in Java. These data types are used to represent the memory allocation. Every data type has a different amount of memory allocation associated with it.
They are also called primitive data types in Java.
- Byte: The byte data type is an 8-bit signed two's complement integer. Range is -128 to 127.
- Short: The short data type is a 16-bit signed two's complement integer. Range is -32,768 to 32,767 (inclusive).
- Int: The int data type is a 32-bit signed two's complement integer. Range is -231 to 231-1.
- Long: The long data type is a 64-bit two's complement integer. Range is -263 to 263-1.
- Float: The float data type is a 32-bit IEEE 754 floating point.
- Double: The double data type is a 64-bit IEEE 754 floating point.
- Boolean: true and false are two possible values of the boolean data type.
- Char: The char data type is a single 16-bit Unicode character. Range is '\u0000' (or 0) to '\uffff'.
Q9) Explain operators in java?
A9) Different types of Operators
Following are various types of operators in Java:
- Arithmetic Operators
- Unary Operators
- Relational Operators
- Logical Operators
- Boolean Operators
- Bitwise Operators
- Ternary Operators
- New Operators
- Cast Operators
1. Arithmetic Operators: They are the type of operators that perform an operation on two operands.
+, -, *, /, % are various Arithmetic operators
+ is the Addition operator
- is the Subtraction operator
* is the Multiplication operator
/ is the division operator
% is the remainder operator also called as modulus operator
Lets see a program on this concept
Code:
Class ArithmeticOperators{
Public static void main(String[] args) {
Double n1 = 12.5, n2 = 3.5, add, subtract, multiply, divide, mod;
// This is how you use the addition operator
Add = n1 + n2;
System.out.println("n1 + n2 = " +add);
// This is how you use the subtraction operator
Subtract = n1 - n2;
System.out.println("n1 - n2 = " +subtract);
// This is how you use the multiplication operator
Multiply = n1 * n2;
System.out.println("n1 * n2 = " +multiply);
// This is how you use the division operator
Divide = n1 / n2;
System.out.println("n1 / n2 = " +divide);
// This is how you use the mod or remainder operator
Mod = n1 % n2;
System.out.println("n1 % n2 = " +mod);
}
}
Output:
2. Unary Operators: They are the types of operators that perform an operation on one operand.
+ is the Unary Plus Operator
- is the Unary Minus Operator. It inverts sign of an expression
++ is the Increment Operator. Increments value by 1
-- is the decrement Operator. Decreases value by 1
! is the Logical complement Operator. It inverts the value of a boolean, i.e. true to false and false to true
Program:
Class UnaryOperator {
Public static void main(String[] args) {
Double number = 5.2, unaryPlus, unaryMinus, increment, decrement, unaryLogical;
Boolean flag = false;
System.out.println("+ unaryPlus = " + +number);
System.out.println("- unaryMinus= " + -number);
System.out.println("++ increment = " + ++number);
System.out.println("-- decrement= " + --number);
System.out.println("! unaryLogical: !flag = " + !flag);
}
}
Output:
3. Relational Operators: Also called as equality and relational operators, these operators determine the relationship between the two operands.
== is the Equal to operator
!= is the Not equal to operator
> is the Greater than operator
>= is the Greater than or equal to operator
< is the Less than operator
<= is the Less than or equal to operator
Program:
Class RelationalOperators {
Public static void main(String args[]) {
Int x = 50;
Int y = 70;
System.out.println("x == y = " + (x == y) );
System.out.println("x != y = " + (x != y) );
System.out.println("x < y = " + (x < y) );
System.out.println("x > y = " + (x > y) );
System.out.println("y <= x = " + (y <= x) );
System.out.println("y >= x = " + (y >= x) );
}
}
Output:
4. Logical Operators: Also called as conditional operators, Logical operators operate on boolean expressions. Various Logical operators are:
&& Conditional-AND, its true only if all boolean expressions are true
|| Conditional-OR, its true if either of the boolean expression is true
Program:
Class LogicalOperators{
Public static void main(String args[]) {
Boolean n = false;
Boolean m = true;
System.out.println("m && n = " + (m&&n));
System.out.println("!(m && n) = " + !(m && n));
System.out.println("m || n = " + (m||n) );
}
}
Output:
5. Boolean Operators: These operators operate only on Boolean Operands
& denotes the AND operator
| denotes the OR operator
^ denotes the XOR operator
! denotes the NOT operator
!= denotes the NOT EQUAL TO operator
== denotes the EQUAL TO operator
Program:
Class BooleanOperators{
Public static void main(String args[]){
Boolean X = true;
Boolean Y = false;
System.out.println("X&Y = "+(X&Y));
System.out.println("X|Y = "+(X|Y));
System.out.println("X^Y = "+(X^Y));
System.out.println("!X = "+(!X));
System.out.println("X!=Y = "+(X!=Y));
System.out.println("X==Y = "+(X==Y));
System.out.println("(X|Y)&X = "+((X|Y)&X));
}
}
Output:
6. Bitwise Operators: They are used to perform bit shift operators in Java.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Program:
Class BitwiseOperators {
Public static void main(String[] args)
{
Int x = 5;
Int y = 7;
// bitwise AND 0101 & 0111=0101 = 5
System.out.println("x&y = " + (x & y));
// bitwise OR 0101 | 0111=0111 = 7
System.out.println("x|y = " + (x | y));
// bitwise XOR 0101 ^ 0111=0010 = 2
System.out.println("x^y = " + (x ^ y));
// bitwise AND ~0101=1010, will give 2's complement of 1010 = -6
System.out.println("~x = " + ~x);
// can be combined with assignment operator for shorthand assignment x=x&y
x &= y;
System.out.println("x= " + x);
}
}
Output:
7. Ternary Operators: It is the only operator that takes three operands. It can be used to replace if-else statements as well as switch statements.
Program:
Class TernaryOperator {
Public static void main(String[] args) {
Double num = -5.5;
String verdict;
Verdict = (num>0.0) ? "Positive" : "Not Positive";
System.out.println("The Number " +num+ " is " +verdict);
}
}
Output:
8. New Operator: The new operator instantiates a class by dynamically allocating (i.e., allocation at run time) memory for a new object and returning a reference to that memory.
Program:
Class Square
{
double squareSide;
}
public class NewOperator
{
Public static void main(String[] args)
{
Square s1 = new Square();
// assigning s2 to s1
Square s2 = s1;
s2.squareSide = 20;
System.out.println(s1.squareSide);
System.out.println(s2.squareSide);
}
}
Output:
M
Up casting: Java Virtual Machine (JVM) performs automatic conversion.
Byte => short => int => long => float => double
e.g. int j = 5;
Long i = j;
Down Casting: Also called as explicit casting, this can be best explained through an example.
e.g. int j = 5;
Long i = j;
Byte b1=j; //compile time error
Byte b2=(byte)j; //allowed. Explicit casting is done
Q10) Describe conditional statements?
A10) Conditional statements are used to choose the path for execution. These are of three types: if/else/else if, ternary and switch.
1. If statement
The simplest form of control structure is if statement. This statement checked a Boolean expression, if the expression value is true then the program enters a block of code; otherwise if Boolean expression value is false it skip if statement block.
Syntax of if statement is:
If(Boolean condition)
{
Line 1; //it will execute only when if statement holds true
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“Output is true”);
}
}
}
Output:
Output is true
2. If-else statement
An extended version of if statement, which use a second block of code which is known as else block in the situation when if condition fails.
Syntax of if else statement:
If(Boolean condition)
{
Line 1; // it will execute only when if statement holds true
}
Else
{
Line 2; // it will execute only when if statement holds false
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“if condition is true”);
}
Else
{
System.out.println(“if condition is false”);
}
}
}
Output:
If condition is true
3. If-else-if ladder or Nested if-else condition
In nested if-else condition first if condition is followed by many else-if conditions. In other way we can define it as a decision tree of if-else-if statement where we have to make multiple choices based on combination of conditions.
Syntax of nested if-else condition:
If(Boolean condition 1) {
Statement 1; //it will executes when condition 1 is true
}
Else if(Boolean condition 2) {
Statement 2; // it will executes when condition 2 is true
}
Else {
Statement 2; //it will executes when all the conditions are false
}
Example:
Public class Example {
Public static void main(String[] args) {
Int a = 15;
If(a < 10) {
System.out.println("a is less than 10");
}else if (a = 12) {
System.out.println("a is equal to 12");
}else if(a > 10) {
System.out.println("a is greater than 10");
}else {
System.out.println(a);
}
}
}
Output:
a is greater than 10
4. Ternary Condition
Ternary condition is an enhancement or shorthand to the if-else condition. The working of ternary and if-else condition is same.
Consider an example of if-else:
If (a > 2) {
System.out.println("a is higher than 2");
} else {
System.out.println("a is lower or equal to 2");
}
Now see the same code in ternary condition
System.out.println(a > 2 ? "a is higher than 2" : "a is lower or equal to 2");
5. Switch condition
Switch conditions in Java are almost same as nested if-else statement.
Switch conditions are designed using multiple blocks of codes known as cases. Among so many cases a single case is executed based on the condition mentioned in the switch.
They are simple to use in comparison to nested if-else. While writing switch statements few things need to be kept in mind:
● We cannot create duplicate case. Each case will be different.
● The variables we can use in case are int, short, byte, char or enumeration. Strings are also supported.
● If all cases fail, then only default statement will be executed.
● While using switch statement, we use break statement also. Break statement will terminate the execution after switch case is satisfied, otherwise next case will be executed.
● The case expression variable must be same as at the time of declaration.
Syntax of switch statement:
Switch (condition){
Case data1:
Statement 1;
Break;
.
.
.
Case dataN:
Statement N;
Break;
Default:
Default statement;
}
Example:
Class Student
Public static void main(String[] args) {
Int a = 2;
Switch (a){
Case 0:
System.out.println("value is 0");
Break;
Case 1:
System.out.println("value is 1");
Break;
Default:
System.out.println(a);
}
}
}
Q11) Explain for, while and do while loop?
A11) For loop
Just like C and C++, for loop in Java is also same. A for loop is used to execute a set of code several times.
For loop consists of three parts. First part is used to initialize the loop variable, second part contains the condition and the third part increment/decrement the variable. For loop is defined in a single line.
Syntax of for loop:
For(initialization, condition, increment or decrement)
{
//block of statements to be executed
}
Example
Class Example
{
Public static void main(String[] args)
{
Int s = 1;
For(int i = 1; i<=5; i++) {
s = s + i;
}
System.out.println("The sum = " + s);
}
}
Output:
The sum = 6
While loop
The while loop statement is also used to repeat the execution of code multiple times.
While loops are preferable to use when we don’t know the exact number of iterations to be done in advance.
Here the initialization of variable and increment/decrement is done outside the loop statement.
In while loop the condition is checked first, if the condition is true then only execution will be done inside the loop; otherwise outside loop statements will be executed.
While loops are also know as entry controlled loop.
Syntax of while loop
While(condition){
//looping statements
}
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
While(a<=5) {
System.out.println(a);
a = a+ 1;
}
}
}
Output:
The list of first 5 even numbers
1
2
3
4
5
Do-while loop
In do-while loop statements are executed first then the condition is evaluated at the end of the loop.
It can we use on those places where we want to execute the statements at least once.
The do-while loops are also known as the exit controlled loop.
Syntax of do-while loop:
Do
{
Statements
} while (condition);
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
Do {
System.out.println(a);
a = a+ 1;
} while(a<=5)
}
}
Q12) Describe jumping statements?
A12) Jump statements are used to change the execution flow of the program to some other specific statements.
In Java there are two types of jump statements: break and continue.
1. Break statement
It is used to immediately terminate the execution of a loop and the control will be passing on to the next statement after the loop.
Break statement are always used inside a loop or switch statement, they cannot be used independently.
Example
Class Example {
Public static void main(String[] args) {
For(int a = 1; a<= 5; a++) {
System.out.println(a);
If(a==3) {
Break;
}
}
}
}
Output
1
2
3
2. Continue statement
Continue statements are used when we want to skip only specific part of the loop and jumps to the next instruction in the loop immediately, while break statement terminates the loop.
It can be used with for or while loop.
Example
Class Example
{
Public static void main(String arg[])
{
For(int x = 0; x <=3; x++)
{
If(x == 1)
Continue;
System.out.println("Number= " + x);
}
}
}
Output
Number = 0
Number = 2
Number = 3
Q13) Explain methods?
A13) In general, a method is a manner of accomplishing a goal. In Java, a method is a collection of instructions that accomplishes a specified goal. It ensures that code can be reused. Methods can also be used to easily alter code. We'll study what a method is in Java, the different sorts of methods, how to declare a method, and how to invoke a method in Java in this part.
What is a method in Java?
A method is a collection of statements or a series of statements organized together to conduct a specific task or action. It's a technique for making code more reusable. We create a method once and then use it repeatedly. We don't have to write code over and over again.
It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.
Method Declaration
Method properties such as visibility, return-type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.
Fig 4: Method declaration
Method Signature: A method signature is a description of a method. It's included in the method declaration. It contains the method name as well as a list of parameters.
Access Specifier: The method's access specifier or modifier is the method's access type. It specifies the method's visibility. There are four different types of access specifiers in Java:
● public - When we utilise the public specifier in our application, all classes can access the method.
● private - The method is only accessible in the classes in which it is declared when we use a private access specifier.
● protected - The method is accessible within the same package or subclasses in a different package when we use the protected access specifier.
● default - When no access specifier is specified in the method declaration, Java uses the default access specifier. It is visible only from the same package only.
Return Type: The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything.
Method Name: It's a one-of-a-kind moniker that's used to specify a method's name. It must be appropriate for the method's functionality. If we're making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.
Parameter List: It consists of a list of parameters separated by a comma and contained in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.
Method Body: It's included in the method declaration. It contains all of the actions that must be completed. It is protected by a pair of curly braces.
Q14) Write the types of methods?
A14) Types of Method
There are two types of methods in Java:
● Predefined Method
● User-defined Method
Predefined Method
Predefined methods in Java are methods that are previously defined in the Java class libraries. It's also known as the built-in method or the standard library approach. We can use these methods directly by calling them at any time in the application. Length(), equals(), compareTo(), sqrt(), and other pre-defined methods are examples. When we call any of the predefined methods in our software, a set of codes relevant to that method run in the background, which are already saved in the library.
Every predefined method is contained within a class. The java.io.PrintStream class, for example, defines the print() function. It outputs the statement we typed into the method. For example, print("Java"), it prints Java on the console.
Example
Demo.java
Public class Demo
{
Public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output
The maximum number is: 9
We utilized three predefined methods in the preceding example: main(), print(), and max() (). Because these methods are predefined, we have utilised them without declaring them. The PrintStream class has a print() function that prints the result to the console. The greater of two numbers is returned by the max() function of the Math class.
User-defined Method
A user-defined method is a method that is written by the user or programmer. These strategies are tweaked to meet the needs of the situation.
How to Create a User-defined Method
Let's build a user-defined mechanism for determining whether an integer is even or odd. We'll start by defining the method.
//user defined method
Public static void findEvenOdd(int num)
{
//method body
If(num%2==0)
System.out.println(num+" is even");
Else
System.out.println(num+" is odd");
}
The following method, entitled find even odd, has been defined (). It has an int-type parameter called num. We used void because the method does not return any value. The procedures to determine whether a number is even or odd are contained in the method body. If the number is even, it will be printed as such; otherwise, it will be printed as odd.
Q15) Write a program to print this using a for loop?
*
* *
* * *
* * * *
* * * * *
A15) Program
Public class PyramidExample {
Public static void main(String[] args) {
For(int i=1;i<=5;i++){
For(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Q16) Write a program to print a pattern?
* * * * * *
* * * * *
* * * *
* * *
* *
*
A16) Program
Public class PyramidEg {
Public static void main(String[] args) {
Int term=6;
For(int i=1;i<=term;i++){
For(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Q17) Write the difference between for, while, and do while loop in java?
A17) Difference between for, while and do while loop
Difference | For Loop | While Loop | Do-While Loop |
Introduction | For loop in Java iterates a given set of statements multiple times. | The Java while loop executes a set of instructions until a boolean condition is met. | The do-while loop executes a set of statements at least once, even if the condition is not met. After the first execution, it repeats the iteration until the boolean condition is met. |
Best time to use | Use it when you know the exact number of times to execute the part of the program. | Use it when you don’t know how many times you want the iteration to repeat. | Use it when you don’t know how many times you want the iteration to repeat, but it should execute at least one time. |
Syntax | For(init; condition; icr/dcr){ //statements to be repeated } | While(condition){ //statements to be repeated } | Do{ //statements to be repeated }while(condition); |
Example | For(int x=0; x<=5; x++){ System.out.println(x); } | Int x=0; While(x<=5){ System.out.println(x); x++; } | Int x=0; Do{ System.out.println(x); x++; }while(x<=5); |