Web programming
Web programming
• Since the private members of a class may only be accessed by other parts of program
through the class’ public methods, we can ensure that no improper actions take
place.
inheritance
Inheritance is the process by which one object acquires the properties of another object.
For example, a Dog is part of the classification Mammal, which in turn is part of the Animal
class. Without the use of hierarchies, each object would need to define all of its
characteristics explicitly. However, by use of inheritance, an object need only define those
qualities that make it unique within its class. It can inherit its general attributes from its
parent. Thus, inheritance makes it possible for one object to be a specific instance of a more
general case.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation.
For eg, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run
after it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell
is at work in both situations. The difference is what is being smelled, that is, the type of data
being operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that
requires three types of stacks. One stack is used for integer values, one for floating-point
values, and one for characters. The algorithm that implements each stack is the same, even
though the data being stored differs
Object
Any entity that has state and behavior is known as an object. It can be either physical or
logical.
For example: chair, pen, table, keyboard, bike etc.
For example, we can define a class called “Student” and create three instances of the class
“Student” for “John”, “Priya” and “Anil”.
The following figure shows three instances of the class Student, identified as “John”, “Priya”
and “Anil”
abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals
with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
Abstraction means simple things like objects, classes, and variables represent more complex
underlying code and data. It avoids repeating the same work multiple times. In java, we use
abstract class and interface to achieve abstraction.
abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it cannot
be instantiated. So we cannot create an object of an abstract class. Also, an abstract class can
contain abstract as well as concrete methods.
To use an abstract class, we have to inherit it from another class where we have to provide
implementations for the abstract methods there itself, else it will also become an abstract
class.
interface:
Interface in Java is a collection of abstract methods and static constants. In an interface, each
method is public and abstract but it does not contain any constructor. Along with abstraction,
interface also helps to achieve multiple inheritance in Java.
So an interface is a group of related methods with empty bodies.
encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
It means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the
methods and variables of a class are well hidden and safe.
inheritance
This is a special feature of Object Oriented Programming in Java. It lets programmers create
new classes that share some of the attributes of existing classes.
For eg, a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived class)
A class which inherits the properties is known as ‘Child class’ whereas a class whose
properties are inherited is known as ‘Parent class’.
Inheritance is classified into 4 types:
single inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.
Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.
multilevel inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.
Here, class B inherits the properties and behavior of class A and class C inherits the
properties of class B. Class A is the parent class for B and class B is the parent class for C.
So, class C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical inheritance
When a class has more than one child class (sub class), then such kind of inheritance is
known
as hierarchical inheritance.
Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of
inheritance can only be achieved through the use of the interfaces.
Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms. In other
words, polymorphism allows us to define one interface or method and have multiple
implementations.
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
• Run time polymorphism
• Compile time polymorphism
run time polymorphism:
In Java, runtime polymorphism refers to a process in which a call to an overridden method
is resolved at runtime rather than at compile-time. Method overriding is an example of run
time polymorphism.
compile time polymorphism:
In Java, compile time polymorphism refers to a process in which a call to an overloaded
method is resolved at compile time rather than at run time. Method overloading is an example
of compile time polymorphism.
CHARACTERISTICS OF JAVA
simple :
• Java is Easy to write and more readable.
• Java has a concise, cohesive set of features that makes it easy to learn and use.
• Most of the concepts are drawn from C++, thus making Java learning simpler.
secure :
• Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable :
• Java programs can execute in any environment for which there is a Java run-time
system.
• Java programs can run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
• Java programming is object-oriented programming language.
• Like C++, java provides most of the object oriented features.
• Java is pure OOP Language. (while C++ is semi object oriented)
robust :
• Java encourages error-free programming by being strictly typed and performing
runtime checks.
multithreaded :
• Java provides integrated support for multithreaded programming.
architecture-neutral :
• Java is not tied to a specific machine or operating system architecture.
• Java is machine independent.
interpreted :
• Java supports cross-platform code through the use of Java bytecode.
• Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
• Bytecodes are highly optimized.
• JVM can execute bytecodes much faster .
distributed :
• Java is designed with the distributed environment.
• Java can be transmitted over internet.
Non-primitive data types include Classes, Interfaces and Arrays which we will learn in
coming tutorials.
Sample Program:
package classTwoVariables;
System.out.println(byteDataType);
System.out.println(shortDataType);
System.out.println(intDataType);
System.out.println(longDataType);
System.out.println(floatDataType);
System.out.println(doubleDataType);
System.out.println(charDataType);
System.out.println(booleanDataType);
}
}
Output:
127
128
32768
2147483648
20.99
4.99999999E7
M
True
VARIABLES
A variable is the holder that can hold the value while the java program is executed. A variable
is assigned with a datatype. It is name of reserved area allocated in memory. In other words,
it is a name of memory location. There are three types of variables in java: local, instance and
static.
A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable’s memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.
Before using any variable, it must be declared. The following statement expresses the
basic form of a variable declaration –
datatype variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java’s data types and variable is the name of the variable. To declare
more than one variable of the specified type, use a comma-separated list.
Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaratrion initializes a byte type variable B.
Types of Variable
There are three types of variables in java:
• local variable
• instance variable
• static variable
Local variable
• Local variables are declared inside the methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.
instance variable
• A variable declared inside the class but outside the method, is called instance
variable.
Instance variables are declared in a class, but outside a method, constructor or any
block.
• A slot for each instance variable value is created when a space is allocated for an
object in the heap.
• Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the
class. It is recommended to make these variables as private. However, visibility for
subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values.
○ numbers, the default value is 0,
○ Booleans it is false,
○ Object references it is null.
• Values can be assigned during the declaration or within the constructor.
• Instance variables cannot be declared as static.
Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.
static variable
• Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables. However, most static variables are declared
public since they must be available for users of the class.
• Default values are same as instance variables.
○ numbers, the default value is 0;
○ Booleans, it is false;
○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
10
20
70
40
50
OPERATORS
Operator in java is a symbol that is used to perform operations. Java
provides a rich set
of operators to manipulate variables.For example: +, -, *, / etc.
All the Java operators can be divided into the following groups −
• Arithmetic Operators :
Multiplicative : * / %
Additive : + -
• Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
• Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
Shift operator: << >> >>>
• Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
• Assignment Operators: =
• Ternary operator: ? :
• Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr –expr
Logical Operators
The following are the logical operators supported by java.
Example:
A=true;
B=false;
assignment Operators
The following are the assignment operators supported by Java
b -= 1;
e *= 2;
f /= 2;
System.out.println(“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}
}
ternary Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The
goal of the operator is to decide, which value should be assigned to the variable. The operator
is written as –
variable x = (expression) ? value if true : value if false
Following is an example −
Example:
public class example
{
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
}
}
unary Operators
Unary operators use only one operand. They are used to increment, decrement or negate
a value.
CONTROL FLOW
Java Control statements control the flow of execution in a java program, based on data values
and conditional logic used. There are three main categories of control flow statements;
selection statements
The selection statements checks the condition only once for the program execution.
if statement:
The if statement executes a block of code only if the specified expression is true. If the
value is false, then the if block is skipped and execution continues with the rest of the
program.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
The following program explains the if statement.
public class programIF{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println(“a > b”);
if (a < b)
System.out.println(“b < a”);
}
}
After the controlling expression, there is a code block that contains zero or more labeled
cases. Each label must equate to an integer constant and each must be unique. When the
switch statement executes, it compares the value of the controlling expression to the values
of each case label.
The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case
label values match, then none of the codes within the switch statement code block will be
executed.
Java includes a default label to use in cases where there are no matches. A nested switch
within a case block of an outer switch is also allowed. When executing a switch statement,
the flow of the program falls through to the next case. So, after every case, you must insert a
break statement.
break;
case 2:System.out.println(“b is the greatest”);
break;
case 3:System.out.println(“c is the greatest”);
break;
default:System.out.println(“Cannot be determined”);
}
}
}
iteration statements
Iteration statements execute a block of code for several numbers of times until the condition
is true.
While statement
The while statement is one of the looping constructs control statement that executes a
block of code while a condition is true. The loop will stop the execution if the testing
expression evaluates to false. The loop condition must be a boolean expression. The syntax of
the
while loop is
while (<loop condition>)
<statements>
for Loop
The for loop is a looping construct which can execute a set of instructions for a specified
number of times. It’s a counter controlled loop.
• initialization statement executes once before the loop begins. The <initialization>
section can also be a comma-separated list of expression statements.
• test expression. As long as the expression is true, the loop will continue. If this
expression is evaluated as false the first time, the loop will never be executed.
continue statement
A continue statement stops the current iteration of a loop (while, do or for) and causes
execution to resume at the top of the nearest enclosing loop. The continue statement can be
used when you do not want to execute the remaining statements in the loop, but you do not
want to exit the loop itself.
The syntax of the continue statement is
It is possible to use a loop with a label and then use the label in the continue statement.
The label name is optional, and is usually only used when you wish to return to the outermost
loop in a series of nested loops.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Advantage of Method
o Code Reusability
o Code Optimization
0
null
advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy
types of methods
There are two types of methods in Java programming:
• Standard library methods (built-in methods or predefined methods)
• User defined methods
standard library methods
The standard library methods are built-in methods in Java
programming to handle tasks
such as mathematical computations, I/O processing, graphics, string
handling etc. These methods are already defined and come along with
Java class libraries, organized in packages.
In order to use built-in methods, we must import the corresponding
packages
java.lang.Math
All maths related methods are defined in this class
acos()
exp()
abs()
log()
sqrt()
pow()
java.lang.String
All string related methods are defined in this class
charAt()
concat()
compareTo()
indexOf()
toUpperCase()
java.awt
contains classes for
graphics
add()
setSize()
setLayout()
setVisible()
Example:
Program to compute square root of a given number using built-in
method.
public class MathEx {
public static void main(String[] args) {
System.out.print(“Square root of 14 is: “ + Math.sqrt(14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413
user-defined methods
The methods created by user are called user defined methods.
Every method has the following.
• Method declaration (also called as method signature or method
prototype)
• Method definition (body of the method)
• Method call (invoke/activate the method)
method declaration
The syntax of method declaration is:
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by
method. It will be void if the method returns nothing. method_name
indicates the unique name assigned to the method. parameter_list
specifies the list of values accepted by the method.
method Definition
Method definition provides the actual body of the method. The
instructions to complete a specific task are written in method
definition. The syntax of method is as follows:
Syntax:
modifier return_type method_name(parameter_list){
// body of the method
}
Here,
Modifier – Defines the access type of the method i.e accessibility region
of method in the application
return_type – Data type of the value returned by the method or void if
method returns nothing
method_name – Unique name to identify the method. The name must
follow
the rules of identifier
parameter_list – List of input parameters separated by comma. It must
be
like
datatype parameter1,datatype parameter2,……
List will be empty () in case of no input parameters.
method body – block of code enclosed within { and } braces to perform
specific task
The first line of the method definition must match exactly with the
method prototype. A
method cannot be defined inside another method.
method call
A method gets executed only when it is called. The syntax for method
call is.
syntax:
method_name(parameters);
When a method is called, the program control transfers to the method
definition where the actual code gets executed and returns back to the
calling point. The number and type of parameters passed in method
call should match exactly with the parameter list mentioned in method
prototype.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
advantages of Inheritance:
• Code reusability - public methods of base class can be reused in
derived classes
• Data hiding – private data of base class cannot be altered by
derived class
• Overriding--With inheritance, we will be able to override the
methods of the baseclass in the derived class
Example:
// Create a superclass.
class BaseClass{
int a=10,b=20;
public void add(){
System.out.println(“Sum:”+(a+b));
}
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub(){
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its superclass*/
obj.add();
obj.sub();
}
}
Sample Output:
Sum:30
Difference:-10
types of inheritance
Single Inheritance :
In single inheritance, a subclass inherit the features of one superclass.
example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
}
}
Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.
Example:
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
class Add3 extends Add2{
public void sum3(){
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
public class Main
{
public static void main(String[] args) {
Add3 obj=new Add3();
obj.sum2();
obj.sum3();
}
}
Sample Output:
Sum of 2 nos.:30
Sum of 3 nos.:60
hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
Triangle obj1=new Triangle();
obj1.triArea();
}
}
Sample Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
Java does not allow multiple inheritance:
• To reduce the complexity and simplify the language
• To avoid the ambiguity caused by multiple inheritance
For example, Consider a class C derived from two base classes A and B. Class C inherits
A and B features. If A and B have a method with same signature, there will be ambiguity to
call method of A or B class. It will result in compile time error.
class A{
void msg(){System.out.println(“Class A”);}
}
class B{
void msg(){System.out.println(“Class B “);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Sample Output:
Compile time error
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
If you are not using any IDE, you need to follow the syntax given below:
1. import package.*;
2. import package.classname;
3. fully qualified name.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
Interfaces
methods.
Uses of interface:
by using interface.
Syntax:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
• The java file must have the same name as the interface.
• The methods that are declared have no bodies. They end with a semicolon after the
parameter list. They are abstract methods; there can be no default implementation of any
method specified within an interface.
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations. They are implicitly final
and static, meaning they cannot be changed by the implementing class. They must also be
initialized.
Sample Code:
The following code declares a simple interface Animal that contains two methods called
Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, the ‘implements’ clause is included in a class definition and then the
Syntax:
// class-body
• If a class implements more than one interface, the interfaces are separated with a
comma.
• If a class implements two interfaces that declare the same method, then the same
• The type signature of the implementing method must match exactly the type
signature
rules
• A class can extend only one class, but can implement many interfaces.
• An interface can extend another interface, in a similar way as a class can extend
another class.
Sample Code 1:
System.out.println(“Mammal eats”);
System.out.println(“Mammal travels”);
return 0;
m.eat();
m.travel();
}
Output:
Mammal eats
Mammal travels
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.
2) Unchecked Exception
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
JavaExceptionExample.java
here are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
1. String s=null;
2. System.out.println(s.length());//NullPointerException
A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
A scenario where ArrayIndexOutOfBoundsException occurs
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Multithreading in Java
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU. Multitasking can be achieved in two
ways:
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
console.
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference
variable
Output:
java
strings
example