0% found this document useful (0 votes)
3 views

BT 22032 - Unit 3 Java Programs

Uploaded by

porselvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

BT 22032 - Unit 3 Java Programs

Uploaded by

porselvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

BT22032 - PROGRAMMING FOR COMPUTATIONAL BIOTECHNOLOGY

APPLICATIONS

Unit – III JAVA


Data types, Keywords, Modifiers, Variables, Constants, Operators and
Separators, Control Structures, String handling, Interfaces, Applets.

Course Objective

3. To impart knowledge on Java programming.

Java is a class-based, object-oriented programming language that is


designed to have as few implementation dependencies as possible. It is
intended to let application developers write once, and run anywhere
(WORA), meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation. Java was first
released in 1995 and is widely used for developing applications for
desktop, web, and mobile devices. Java is known for its simplicity,
robustness, and security features, making it a popular choice for
enterprise-level applications.

Java was developed by James Gosling at Sun Microsystems Inc in May


1995 and later acquired by Oracle Corporation. It is a simple
programming language. Java makes writing, compiling, and debugging
programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language
and is designed to have as few implementation dependencies as
possible. A general-purpose programming language made for developers
to write once run anywhere that is compiled Java code can run on all
platforms that support Java. Java applications are compiled to byte
code that can run on any Java Virtual Machine. The syntax of Java is
similar to C/C++.

 Key Features of Java


1. Platform Independent
2. Object-Oriented Programming
3. Simplicity
4. Robustness
5. Security
6. Distributed
7. Multithreading
8. Portability
9. High Performance

. Java Virtual Machine(JVM)


The JVM is an integral part of the Java platform, responsible for
executing Java bytecode. It ensures that the output of Java programs
is consistent across different platforms.

 Writing a program is done by a java programmer like you and me.

 The compilation is done by the JAVAC compiler which is a primary


Java compiler included in the Java development kit (JDK). It
takes the Java program as input and generates bytecode as output.

 In the Running phase of a program, JVM executes the bytecode


generated by the compiler.

Now, we understood that the function of Java Virtual Machine is to


execute the bytecode produced by the compiler. Every Operating System
has a different JVM but the output they produce after the execution of
bytecode is the same across all the operating systems. This is why
Java is known as a platform-independent language.

2. Bytecode

Bytecode is the intermediate representation of Java code, generated by


the Java compiler. It is platform-independent and can be executed by
the JVM.

3. Java Development Kit(JDK)

While we were using the term JDK when we learn about bytecode and JVM.
So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment
(JRE), java debuggers, java docs, etc. For the program to execute in
java, we need to install JDK on our computer in order to create,
compile and run the java program.

4. Java Runtime Environment (JRE)

JDK includes JRE. JRE installation on our computers allows the java
program to run, however, we cannot compile it. JRE includes a browser,
JVM, applet support, and plugins. For running the java program, a
computer needs JRE.

5. Garbage Collector

In Java, programmers can’t delete the objects. To delete or recollect


that memory JVM has a program called Garbage Collector. Garbage
Collectors can recollect the objects that are not referenced. So Java
makes the life of a programmer easy by handling memory management.
However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.
6. ClassPath

The Classpath is the file path where the java runtime and Java
compiler look for .class files to load. By default, JDK provides many
libraries. If you want to include external libraries they should be
added to the classpath.

Basically everything in java is represented in Class as an object


including the main function.

Advantages of Java

 Platform independent: Java code can run on any platform that has
a Java Virtual Machine (JVM) installed, which means that
applications can be written once and run on any device.

 Object-Oriented: Java is an object-oriented programming language,


which means that it follows the principles of encapsulation,
inheritance, and polymorphism.

 Security: Java has built-in security features that make it a


secure platform for developing applications, such as automatic
memory management and type checking.

 Large community: Java has a large and active community of


developers, which means that there is a lot of support available
for learning and using the language.

 Enterprise-level applications: Java is widely used for developing


enterprise-level applications, such as web applications, e-
commerce systems, and database systems.

Disadvantages of Java

1. Performance: Java can be slower compared to other programming


languages, such as C++, due to its use of a virtual machine and
automatic memory management.

2. Memory management: Java’s automatic memory management can lead to


slower performance and increased memory usage, which can be a
drawback for some applications.

Java is statically typed and also a strongly typed language because,


in Java, each type of data (such as integer, character, hexadecimal,
packed decimal, and so forth) is predefined as part of the programming
language and all constants or variables defined for a given program
must be described with one of the Java data types.
Data Types in Java

Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories in
which data types are segregated

1. Primitive Data Type: such as boolean, char, int, short, byte,


long, float, and double

2. Non-Primitive Data Type or Object Data type: such as String,


Array, etc.

Understanding and effectively using these data types is crucial for


writing efficient and error-free Java code. If you’re aiming to master
Java, exploring detailed resources or Java Programming Course can help
you gain a strong command over data types and other essential Java
concepts

Data Types in JAVA


Primitive Data Types in Java

Primitive data are only single values and have no special


capabilities. There are 8 primitive data types. They are depicted
below in tabular format below as follows:

Example
Type Description Default Size Range of values
Literals
true or 8
boolean false true, false
false bits true, false

twos-
8
byte complement 0 (none)
bits -128 to 127
integer

‘a’, ‘\
u0041’, ‘\ characters representation
Unicode 16
char \u0000 101’, ‘\\’, of ASCII values
character bits
‘\’, ‘\n’,
‘β’ 0 to 255

twos-
16
short complement 0 (none)
bits -32,768 to 32,767
integer

-2,147,483,648
twos-
32
int complement 0 -2,-1,0,1,2
bits to
intger
2,147,483,647
-
twos- 9,223,372,036,854,775,808
64 -2L,-
long complement 0
bits 1L,0L,1L,2L to
integer

9,223,372,036,854,775,807
1.23e100f ,
IEEE 754
32 -1.23e-
float floating 0.0
bits 100f , .3f , upto 7 decimal digits
point
3.14F

IEEE 754 1.23456e300d


64
double floating 0.0 , -123456e-
bits upto 16 decimal digits
point 300d , 1e1d
Int
class Bio {
public static void main(String[] args) {
System.out.println("Hi Biotech Students");
int a=30;
int b=20;
int c =a+b;
int d =a*b;
int e = a-b;
System.out.println("Addition is " + c);
System.out.println("Mul is " + d);
System.out.println("Sub is " + e);
System.out.println("Addition is " + x);
}
}
Float
class Main {
public static void main(String[] args) {

float number = -42.3f;


System.out.println(number); // prints -42.3
}
}
Long
class LongExample {
public static void main(String[] args) {

long range = -42332200000L;


System.out.println(range); // prints -42332200000
}
}

SHORT

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

short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
A constant is a variable whose value cannot change once it has been assigned.
Java doesn't have built-in support for constants.

A constant can make our program more easily read and understood by others. In
addition, a constant is cached by the JVM as well as our application, so using
a constant can improve performance.

To define a variable as a constant, we just need to add the keyword "final" in


front of the variable declaration.
Example:
public class ConstantsDemo {
public static void main(String args[]) {
final byte var1 = 2;
final byte var2;
var2 = -3;

final short var3 = 32;


final short var4;
var4 = -22;

final int var5 = 100;


final int var6;
var6 = -112;

final long var7 = 20000;


final long var8;
var8 = -11223;

final float var9 = 21.23f;


final float var10;
var10 = -121.23f;

final double var11 = 20000.3223;


final double var12;
var12 = -11223.222;

final boolean var13 = true;


final boolean var14;
var14 = false;

final char var15 = 'e';


final char var16;
var16 = 't';

// Displaying values of all variables

System.out.println("value of var1 : "+var1);


System.out.println("value of var2 : "+var2);
System.out.println("value of var3 : "+var3);
System.out.println("value of var4 : "+var4);
System.out.println("value of var5 : "+var5);
System.out.println("value of var6 : "+var6);
System.out.println("value of var7 : "+var7);
System.out.println("value of var8 : "+var8);
System.out.println("value of var9 : "+var9);
System.out.println("value of var10 : "+var10);
System.out.println("value of var11 : "+var11);
System.out.println("value of var12 : "+var12);
System.out.println("value of var13 : "+var13);
System.out.println("value of var14 : "+var14);
System.out.println("value of var15 : "+var15);
System.out.println("value of var16 : "+var16);
}
}
Input at the time of execution: To get Input at the time of
executionwe need to import the package util. The util package in
Java is a built-in package that contains various utility classes and
interfaces.

import java.util.Scanner; // Import the Scanner class

class bio {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user
input
}
}

------------------------------------------------------

MODIFIERS
Modifier Description

public The code is accessible for all classes

private The code is only accessible within the declared class

protected The code is accessible in the same package and subclasses.

public
public class Main {
public String fname = "Bio";
public String lname = "Tech";
public String email = "Students";
public int start = 20242;
}
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Year: " + myObj.start);
}
}
Private
public class Main {
private String fname = "Bio";
private String lname = "Tech";
private String email = "2022bt.com";
private int start = 2024;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println("Branch Name: " + myObj.fname + " " +
myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Year: " + myObj.start);
}
}
PROTECTED
class Person {
protected String fname = "Bio";
protected String lname = "Tech";
protected String email = "2022bt.com.com";
protected int start = 2024;
}

class Student extends Person {


private int graduationYear = 2026;
public static void main(String[] args) {
Student myObj = new Student();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("start: " + myObj.start);
System.out.println("Graduation Year: " + myObj.graduationYear);
}
}
Exercise for Integer
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
System.out.println("After Swapping\nz = "+z+"\ny = "+y);
}
}
Output:
Enter z and y 5 10
Before Swapping
z = 5
y = 10
After Swapping
z = 10
y = 5

Control Statement - IF Loop


Calculate the largest of three numbers: The largest of the three
numbers entered by the user is calculated.

import java.util.Scanner;
class Largest
{
public static void main(String args[])
{
int a,b,c;
System.out.println("Enter three integers ");
Scanner sct = new Scanner(System.in);
a = sct.nextInt();
b = sct.nextInt(); //User Input
c = sct.nextInt();
if ( a > b && a > c ) // Condition check for Largest number
System.out.println("1st number is largest.");
else if ( b > a && b > c )
System.out.println("2nd number is largest.");
else if ( c > a && c > b )
System.out.println("3rd number is largest.");
else
System.out.println("Number are not distinct.");
}
}

-------------------------------------------------------------

Factorial Calculation and a basic loop structure: The factorial of a


number entered by the user is calculated.

import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n,c, fact = 1;
System.out.println("Enter a number");
Scanner sct = new Scanner(System.in);
n = sct.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ ) // Calculating Factorial
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
-------------------------------------------------------------------

Program to calculate Reverse of a number

import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, rev = 0;
System.out.println("Enter the number to reverse ");
Scanner sct = new Scanner(System.in);
n = sct.nextInt(); //User Input
while( n != 0 )// Reversing a Number Entered
{
rev = rev * 10;
rev = rev + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+rev);
}
}
--------------------------------------------------------------

Program to calculate Reverse of a String

import java.util.*;
class ReverseString
{
public static void main(String args[])
{
String original, reverse = "";
Scanner sct = new Scanner(System.in);
System.out.println("Enter string to reverse");
original = sct.nextLine(); //String input from user
int length = original.length();
for ( int i = length - 1 ; i>= 0 ; i-- ) // Reversing the String
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
}
}
-----------------------------------------------------------------

Retrieve a Substring in a String

import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String str, sub;
int i, c, length;
Scanner sct = new Scanner(System.in);
System.out.println("Enter string to print all it's substrings:");
str = sct.nextLine(); // User input
length = str.length();
System.out.println("Substrings of \""+str+"\" are :-");
for( c = 0 ; c < length ; c++ )// Calculating all the substring
possible
{
for( i = 1 ; i<= length - c ; i++ )
{
sub = str.substring(c, c+i);
System.out.println(sub);
}
}
}
}
--------------------------------------------------------

Control Statement
SWITCH CASE
public class Main {

public static void main(String[] args) {

int day = 4;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:
System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

Control Statement - While

public class Main {

public static void main(String[] args) {

int i = 0;
while (i < 5) {

System.out.println(i);

i++;

Control Statement - Break Statement

public class Main {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

System.out.println(i);

JAVA STRINGS

public class LengthExample{

public static void main(String args[]){

String s1="Biotech";

String s2="Java";

System.out.println("string length is: "+s1.length());//10 is the len


gth of javatpoint string
System.out.println("string length is: "+s2.length());//6 is the leng
th of python string

}}

public class LengthExample2 {

public static void main(String[] args) {

String str = "Biotechstudents";

if(str.length()>0) {

System.out.println("String is not empty and length is: "


+str.length());

str = "";

if(str.length()==0) {

System.out.println("String is empty now: "+str.length());

The length() method is also used to reverse the string.

class LengthExample3

// main method

public static void main(String argvs[])

String str = "Welcome To Javaclass Biostudents ";


int size = str.length();

System.out.println("Reverse of the string: " + "'" + str + "'" + " i


s");

for(int i = 0; i < size; i++)

// printing in reverse order

System.out.print(str.charAt(str.length() - i - 1));

The length() method can also be used to find only the white spaces
present in the string. Observe the following example.

public class LengthExample4

// main method

public static void main(String argvs[])

String str = " Welcome To Biotech Java Class ";

int sizeWithWhiteSpaces = str.length();

System.out.println("In the string: " + "'" + str + "'");

str = str.replace(" ", "");

int sizeWithoutWhiteSpaces = str.length();

// calculating the white spaces

int noOfWhieSpaces = sizeWithWhiteSpaces - sizeWithoutWhiteSpaces;


System.out.print("Total number of whitespaces present are: " + noOfW
hieSpaces);

Output:

In the string: ' Welcome To JavaTpoint '


Total number of whitespaces present are: 4

public class ReplaceExample1{

public static void main(String args[]){

String s1=" wabsita";

String replaceString=s1.replace('a','e');//replaces all occurrences of


'a' to 'e'

System.out.println(replaceString);

}}

public class ReplaceExample2{

public static void main(String args[]){

String s1="my name is khan my name is java";

String replaceString=s1.replace("is","was");//replaces all occurrences


of "is" to "was"

System.out.println(replaceString);

}}

public class ReplaceExample3 {

public static void main(String[] args) {

String str = "oooooo-hhhh-oooooo";

String rs = str.replace("h","s"); // Replace 'h' with 's'

System.out.println(rs);
rs = rs.replace("s","h"); // Replace 's' with 'h'

System.out.println(rs);

public class ReplaceExample4

// main method

public static void main(String argvs[])

String str = "For learning Java, JavaTpoint is a very good site.";

int size = str.length();

System.out.println(str);

String target = null;

// replacing null with JavaTpoint. Hence, the NullPointerException


is raised.

str = str.replace(target, "JavaTpoint ");

System.out.println(str);

Methods Description
contains() Checks whether the string contains a substring.
substring() Returns the substring of the string.
join() Joins the given strings using the delimiter.
Replaces the specified old character with the
replace()
specified new character.
Replaces all substrings matching the regex
replaceAll()
pattern.
replaceFirst() Replaces the first matching substring.
Returns the character present in the specified
charAt()
location.
getBytes() Converts the string to an array of bytes.
Returns the position of the specified character
indexOf()
in the string.
compareTo() Compares two strings in the dictionary order.
compareToIgnoreCase() Compares two strings, ignoring case differences.
trim() Removes any leading and trailing whitespaces.
format() Returns a formatted string.
split() Breaks the string into an array of strings.
toLowerCase() Converts the string to lowercase.
toUpperCase() Converts the string to uppercase.
Returns the string representation of the
valueOf()
specified argument.
toCharArray() Converts the string to a char array.
Checks whether the string matches the given
matches()
regex.
Checks if the string begins with the given
startsWith()
string.
endsWith() Checks if the string ends with the given string.
isEmpty() Checks whether a string is empty or not.
Returns the canonical representation of the
intern()
string.
Checks whether the string is equal to
contentEquals()
charSequence.
hashCode() Returns a hash code for the string.
subSequence() Returns a subsequence from the string.

Worked Out Exercise


import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp, b;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
b = z;
System.out.println("After Swapping z = "+z+"\ny = "+y);
System.out.println("B value is" + b);
}
}
STRING OPERATIONS
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();

System.out.println("Length: " + length);


}
}
-----------------------------------------------------------

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

// create first string


String first = "Biotech";
System.out.println("First String: " + first);

// create second
String second = "Students";
System.out.println("Second String: " + second);

// join two strings


String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);


}
}
---------------------------------------------------

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

// create 3 strings
String first = "AEBDGF";
String second = "AEBDGF";
String third = "JDGFTRH";

// compare first and second strings


boolean result1 = first.equals(second);

System.out.println("Strings first and second are equal: " +


result1);

// compare first and third strings


boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " +


result2);
}
}
------------------------------------------------

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

// create a string using new


String name = new String("Java String");

System.out.println(name); // print Java String


}
}
--------------------------------------------------

Format Specifier
import java.util.*;

class GFG {

public static void main(String args[])

// create Formatter class object

Formatter formatter = new Formatter();

// + sign specifier

formatter = new Formatter();

formatter.format("%+d", 111);

System.out.println(formatter);

// + sign specifier

// on - sign, it will have no effect

formatter = new Formatter();

formatter.format("%+d", -111);

System.out.println(formatter);

}
}

import java.util.*;

public class GFG {


public static void main(String args[])
{

// create Formatter class object


Formatter formatter = new Formatter();

// comma Specifier
formatter = new Formatter();
formatter.format("%, d", 1000000);
System.out.println(formatter);

// comma Specifier
formatter = new Formatter();
formatter.format("%, .3f", 32659526566.4521);
System.out.println(formatter);
}
}
-----------------------

// Java program to demonstrate


// the left justification format specifiers.

import java.util.*;

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

// create Formatter class object


Formatter formatter = new Formatter();

// right justify by default


formatter = new Formatter();
formatter.format("|%20.4f|", 1234.1234);
System.out.println(formatter);

// left justify
formatter = new Formatter();
formatter.format("|%-20.4f|", 1234.1234);
System.out.println(formatter);
}
}
-------------------------------------------

Inheritance

Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
The code is only accessible in the same package. This is used when
default
you don't specify a modifier.
The code is accessible in the same package and subclasses. You will
protected
learn more about subclasses and superclasses in the Inheritance
--------------------------------------

class Employee

float salary=40000;

class Programmer extends Employee

int bonus=10000;

public static void main(String args[])

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

-------------------------------------------------------------

Inheritance
class Bio {

// field and method of the parent class

String name;

public void BT() {

System.out.println("This is Java");

}
// inherited

class SVCE extends Bio {

// new method in subclass

public void display() {

System.out.println("Hi " + name);

class Main {

public static void main(String[] args) {

// create an object of the subclass

SVCE svc = new SVCE();

// access field of superclass

svc.name = "Bio Students";

svc.display();

// call method of superclass

// using object of subclass

svc.BT();

abstract class Main {

public String dname = "Bio";

public int year = 2024;

public abstract void study(); // abstract method

// Subclass (inherit from Main)

class Student extends Main {

public int graduationYear = 2024;

public void study() { // the body of the abstract method is provided


here
System.out.println("Studying all day long");

class Second {

public static void main(String[] args) {

// create an object of the Student class (which inherits


attributes and methods from Main)

Student myObj = new Student();

System.out.println("Name: " + myObj.dname);

System.out.println("Year: " + myObj.year);

System.out.println("Graduation Year: " + myObj.graduationYear);

myObj.study(); // call abstract method

Java Arrays
public class Main {

public static void main(String[] args) {

String[] bname = {"Enzyme", "Food", "Processing", "COVID"};

System.out.println(bname[0]);

----------------------------------------------

public class Main {

public static void main(String[] args) {

String[] bname = {"Enzyme", "Food", "Processing", "COVID"};

int[] mynum = {10, 20, 30, 40};

bname[0] = "Food";

System.out.println(mynum[2]);

System.out.println(bname[0]);
System.out.println(bname.length);

public class Main {

public static void main(String[] args) {

String[] bname = {"Enzyme", "Food", "Processing", "COVID"};

for (int i = 0; i < bname.length; i++) {

System.out.println(bname[i]);

public class Main {

public static void main(String[] args) {

String[] bname = {"Enzyme", "Food", "Processing", "COVID"};

for (String i : bname) {

System.out.println(i);

public class Main {

public static void main(String[] args) {

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

// Get the length of the array

int length = ages.length;

// Loop through the elements of the array

for (int age : ages) {

sum += age;
}

// Calculate the average by dividing the sum by the length

avg = sum / length;

// Print the average

System.out.println("The average age is: " + avg);

public class Main {

public static void main(String[] args) {

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

// Get the length of the array

int length = ages.length;

// Create a 'lowest age' variable and assign the first array


element of ages to it

int lowestAge = ages[0];

// Loop through the elements of the ages array to find the lowest
age

for (int age : ages) {

// Check if the current age is smaller than the current 'lowest


age'

if (lowestAge > age) {

// If the smaller age is found, update 'lowest age' with that


element

lowestAge = age;

// Output the value of the lowest age

System.out.println("The lowest age in the array is: " +


lowestAge);
}

Calling Method in Java:


public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Biotech");

public static void main(String[] args) {

myMethod("Food");

myMethod("Genomics");

myMethod("Enzymes");

public class Main {

static void myMethod(String fname, int bio) {

System.out.println(fname + " belongs to " + bio);

public static void main(String[] args) {

myMethod("Food", 4);

myMethod("Genomics", 8);
myMethod("Enzyme", 6);

Overloading
public class Main {

static int MethodInt(int x, int y) {

return x + y;

static double MethodDouble(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = MethodInt(8, 5);

double myNum2 = MethodDouble(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

Separators
public class Main {

public static void main(String[] args) {

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x

System.out.println(x);

} // The block ends here


// Code here CANNOT use x

public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]);

Interfaces
interface Gene {

public void gene1(); // interface method (does not have a body)

public void disease(); // interface method (does not have a body)

class Genetic implements Gene {

public void gene1() {

System.out.println("The gene is BRCA1");

public void disease() {

System.out.println("breast cancer");

class Main {

public static void main(String[] args) {

Genetic geno = new Genetic();

geno.gene1();

geno.disease();

}
------------------------------------------------------------

interface Bio {

public void dept(); // interface method (does not have a body)

public void course(); // interface method (does not have a body)

class SVCE implements Bio {

public void dept() {

System.out.println("The dept is Bio");

public void course() {

System.out.println("BT22032");

class Main {

public static void main(String[] args) {

SVCE myclass = new SVCE();

myclass.dept();

myclass.course();

interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method

public void getArea(int length, int breadth) {


System.out.println("The area of the rectangle is " + (length *
breadth));

class Main{

public static void main(String[] args) {

Rectangle r1 = new Rectangle();

r1.getArea(5, 6);

Rectangle r2 = new Rectangle();

r2.getArea(10, 16);

Java Applets

Applets are small Java applications which can be accessed on an


Internet server, transported over the Internet, and can be installed
and run automatically as part of a web document.

The applet can create a graphical user interface after a user gets
an applet. It has restricted access to resources so that complicated
computations can be carried out without adding the danger of viruses
or infringing data integrity.

Any Java applet is a class that extends the class of


java.applet.Applet.

There is no main() methods in an Applet class. Using JVM it is


regarded. The JVM can operate an applet application using either a Web
browser plug-in or a distinct runtime environment.

JVM generates an applet class instant and invokes init() to


initialize an applet.

There are many advantages of applet. They are as follows:

 It works at client side so less response time.


 Secured
 It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It


provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is


invoked only once.
2. public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is
invoked only once.
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}

import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

=====================================================================

Worked Out examples In class

import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp, b;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
b = z;
System.out.println("After Swapping z = "+z+"\ny = "+y);
System.out.println("B value is" + b);
}
}
---------------------------------------------

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

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();

System.out.println("Length: " + length);


}
}
-----------------------------------------------------------
class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
System.out.println("First String: " + first);

// create second
String second = "Programming";
System.out.println("Second String: " + second);

// join two strings


String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);


}
}
---------------------------------------------------

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

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);

System.out.println("Strings first and second are equal: " +


result1);

// compare first and third strings


boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " +


result2);
}
}
------------------------------------------------

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

// create a string using new


String name = new String("Java String");

System.out.println(name); // print Java String


}
}
--------------------------------------------------
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "AEBCDGA";
String second = "BDEFGS";
String third = "AEBCDGA";
// compare first and second strings
boolean result1 = first.equals(second);
boolean result3 = second.equals(third);
System.out.println("Strings first and second are equal: " +
result1);
System.out.println("Whether String Second & Third is equal: \n" +
result3);
// compare first and third strings
boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " +


result2);
}
}

-----------------------------------------------------------------

import java.util.Scanner; // Import the Scanner class

class bio {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user
input
}
}

-----------------------------------------------------------------

class variablescope
{
public static void main(String args[])
{
int x;
for (x = 10; x > 4; x--)
{
System.out.println(x);
}
System.out.println(x+1);
}
}

import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int z, y, temp, b;
System.out.println("Enter z and y");
Scanner sct = new Scanner(System.in); //User inputs two numbers
z = sct.nextInt(); //User inputs two numbers
y = sct.nextInt();
System.out.println("Before Swapping\nz = "+z+"\ny = "+y);
temp = z; //Swapping is done
z = y;
y = temp;
b = z;
System.out.println("After Swapping z = "+z+"\ny = "+y);
System.out.println("B value is" + b);
}

-----------------------------------------------------------------

import java.util.Scanner;
class Largest
{
public static void main(String args[])
{
int a,b,c;
System.out.println("Enter three integers ");
Scanner sct = new Scanner(System.in);
a = sct.nextInt();
b = sct.nextInt(); //User Input
c = sct.nextInt();
if ( a > b && a > c ) // Condition check for Largest number
System.out.println("1st number is largest.");
else if ( b > a && b > c )
System.out.println("2nd number is largest.");
else if ( c > a && c > b )
System.out.println("3rd number is largest.");
else
System.out.println("Number are not distinct.");
}
}
---------------------------------------------------------------
import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String str, sub;
int i, c, length;
Scanner sct = new Scanner(System.in);
System.out.println("Enter the Gene to print all it's substrings:");
str = sct.nextLine(); // User input
length = str.length();
System.out.println("Length" + length);
System.out.println("Substrings of \""+str+"\" are :-");
for( c = 0 ; c < length ; c++ )// Calculating all the substring
possible
{
//for( i = 1 ; i<= length - c ; i++ )
//{
sub = str.substring(c, c+1);
System.out.println(sub);
//}
}
}
}

---------------------------------------------------------------

You shall try

Searching using Linear Search Technique


import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner sct = new Scanner(System.in);
System.out.println("Enter number of elements");
n = sct.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++) //User input of array values
{
array[c] = sct.nextInt();
}
System.out.println("Enter value to find"); //User input of number to
Search
search = sct.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) // element is present
{
System.out.println(search + " present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* element is absent */
System.out.println(search + " not present inside array.");
}
}

Output
Enter number of elements 5
Enter 5 integers 8 9 7 5 0
Enter value to find 5
5 present at location 4.

Search using Binary Search Technique

The binary search is quick and is used in sorted array. The binary
search starts the element search from middle of the array and proceeds
further up or down the array depending on the mid value of the array.

import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner sct = new Scanner(System.in);
System.out.println("Enter number of elements");
n = sct.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
{
array[c] = sct.nextInt();
}
System.out.println("Enter value to find");
search = sct.nextInt();
first = 0; // Basic binary search
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) +
".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
if ( first > last ){
System.out.println(search + " is not present in the list.\n");
}
}
}

Output

Enter number of elements 5

Enter 5 integers 3 5 7 8 9

Enter value to find 8

8 present at location 4.

Prepared By: Dr. R. Anitha, Prof.& Head/ CSE, SVCE

You might also like