Java Printout New
Java Printout New
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. This tutorial gives a complete understanding of Java. Java is guaranteed to be
Write Once, Run Anywhere.
Java is:
i. Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
ii. Platform independent: Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
iii. Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java
would be easy to master.
iv. Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
v. Architectural-neutral: Java compiler generates an architecture-neutral object file format
which makes the compiled code to be executable on many processors, with the presence of
Java runtime system.
vi. Portable: Being architectural-neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
vii. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
viii. Multithreaded: With Java's multithreaded feature it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
ix. Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is
an incremental and light weight process.
x. High Performance: With the use of Just-In-Time compilers, Java enables high performance.
xi. Distributed: Java is designed for the distributed environment of the internet.
1
xii. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case. If several words
are used to form a name of the class each inner words first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case. Example: public void myMethodName
2
Program File Name - Name of the program file should exactly match the class name. When
saving the file you should save it using the class name Rememberjavaiscasesensitive and
append '.java' to the end of the name.
ifthefilenameandtheclassnamedonotmatchyourprogramwillnotcompile.
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as'MyFirstJavaProgram.java'
public static void main(Stringargs[]) - java program processing starts from the main
method which is a mandatory part of every java program…
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are
two categories of modifiers:
Access Modifiers: default, private, public, protected:
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
o Visible to the package – the default. No modifiers are needed.
o Visible to the class only – private.
o Visible to the world – public.
o Visible to the package and all subclasses – protected.
3
o The final modifier for finalizing the implementations of classes, methods, and
variables.
o The abstract modifier for creating abstract classes and methods.
o The synchronized and volatile modifiers, which are used for threads.
Java Variables:
We would see following type of variables in Java:
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static variables)
Java Arrays:
Arrays are objects that store multiple variables of the same type. However, an array itself is an
object on the heap. We will look into how to declare, construct and initialize in the upcoming
chapters.
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
4
short static strictfp super
volatile while
Comments in Java:
Java supports single-line and multi-line comments very similar to c and c++. All characters available
inside any comment are ignored by Java compiler.
5
ii. Short: 16-bit signed two's complement integer; Min value is -32,768 (-2^15) & Max
value is 32,767 (inclusive)(2^15 -1). Example: short s = 10000, short r = -20000
iii. Int: 32-bit signed two's complement integer; Min value is -2,147,483,648 (-2^31) & Max
value is 2,147,483,647 (inclusive)(2^31 -1). Example: int a = 100000, int b = -200000
iv. Long: 64-bit signed two's complement integer; Min value is (-2^63) & Max value is
(2^63 -1)(inclusive). Example: long a = 100000L, long b = -200000L
v. Float: Single-precision 32-bit IEEE 754 floating point. Float data type is never used for
precise values such as currency. Example: float f1 = 234.5f
vi. Double: Double-precision 64-bit IEEE 754 floating point. Double data type should never
be used for precise values such as currency. Example: double d1 = 123.4
vii. Boolean: Boolean data type represents one bit of information. There are only two
possible values: true and false. Default value is false. Example: boolean one = true
viii. Char: Single 16-bit Unicode character. Min value is '\u0000' (or 0) & Max value is '\uffff'
(or 65,535 inclusive). Char data type is used to store any character. Example: char letterA
='A'
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:
"Hello World"
6
"two\nlines"
"\"This is in quotes\""
Java language supports few special escape sequences for String and char literals as well. They are:
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
7
(3) The Bitwise Operators:
Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now
in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
8
(5) The Assignment Operators:
i. Conditional Operator ( ? : )
Conditional operator is also known 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:
9
Following is the example:
Value of b is : 30
Value of b is : 20
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is the
example:
true
() [] . (dot operator)
Number Methods:
Here is the list of the instance methods that all the subclasses of the Number class implement:
11
value of specified int or Integer.
4 parseInt() 15 sin()
This method is used to get the primitive Returns the sine of the specified double
data type of a certain String. value.
5 abs() 16 cos()
Returns the absolute value of the Returns the cosine of the specified double
argument. value.
6 ceil() 17 tan()
Returns the smallest integer that is greater Returns the tangent of the specified
than or equal to the argument. Returned as double value.
a double.
7 floor() 18 asin()
Returns the largest integer that is less than Returns the arcsine of the specified double
or equal to the argument. Returned as a value.
double.
8 round() 19 acos()
Returns the closest long or int, as indicated Returns the arccosine of the specified
by the method's return type, to the double value.
argument.
9 min() 20 atan()
Returns the smaller of the two arguments. Returns the arctangent of the specified
double value.
10 max() 21 toDegrees()
Returns the larger of the two arguments. Converts the argument to degrees
11 exp() 22 toRadians()
Returns the base of the natural logarithms, Converts the argument to radians.
e, to the power of the argument.
23 random()
Returns a random number.
Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class
implement:
12
SN Methods with Description SN Methods with Description
1 isLetter() 5 isLowerCase()
Determines whether the specified char Determines whether the specified char
value is a letter. value is lowercase.
2 isDigit() 6 toUpperCase()
Determines whether the specified char Returns the uppercase form of the
value is a digit. specified char value.
3 isWhitespace() 7 toLowerCase()
Determines whether the specified char Returns the lowercase form of the
value is white space. specified char value.
4 isUpperCase() 8 toString()
Determines whether the specified char Returns a String object representing the
value is uppercase. specified character valuethat is, a one-
character string.
Creating Strings:
The most direct way to create a string is to write:
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
Below given program is an example of length() , method String class.
13
This would produce the following result:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in:
14
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements;
}
15
public class TestArray {
for(declaration : expression) public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
{
// Print all the array elements
//Statements; for (double element: myList) {
System.out.println(element);
}
}
}}
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
16
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
The syntax of a if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
17
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
default : //Optional
//Statements;
}
18
Java Methods:
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println method, for example, the system actually executes several statements
in order to display a message on the console.
In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
A method definition consists of a method header and a method body. Here are all the parts of a
method:
Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning a
value. In this case, the returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the
method does.
Exceptions Handling:
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1){
//Catch block
}
Java Arrays
An array is a group of variables, all of the same data type that is referred to by a single name. The
values in the group occupy contiguous locations in the computer memory, i.e. the data are stored one
next to each other in the computer memory. Each element in the array is identified by the array name
and a subscript pointing to the particular location within the array.
Score
20 40 10 50 30
Types of Array:
(i) One (Single) dimensional array: with a single row or column.
(ii) Two-dimensional array: with more the one row and column.
Creating one-dimensional array:
The general syntax for creating an array is:
As with single objects, both the declaration and allocation can be combined in a single declaration
with initialization as shown below:
Note: element-type could be any of the primitive data type such as int, float, double, char, etc.
22
Examples:
Note that we can initialize an array explicitly with an initialization list, like this:
Two-dimensional Array:
A two-dimensional array looks like a matrix as shown below:
34 05 -5
-10 -2 24
15 13 -7
a[0][2] = 50; // assigns 50 to the element in row 0 column 2 (1st row 3rd column).
23
PRACTICAL EXERCISES
Comparing print() and println() methods Inputting data into Java programs via
command line
public class Ex1{
public static void main(String[] args){ //program to compute average of 3 nos.
int a, b, c, d; import java.util.Scanner;
a = 2; b=4; c=6; d = 8; Class Avg{
System.out.print(a, b); public static void main(String[] args){
System.out.print(c); Scanner input=new Scanner(System.in);
System.out.println(); //Read in data a, b and c
System.out.println(d); System.out.println(“Enter value for a”);
} float a = input.nextFloat();
}
Output System.out.println(“Enter value for b”);
?? float b = input.nextFloat();
24
Program to print the constants e and π, absolute A sample method to compute factorial of a
of -1234, cos(π/4), sin(π/2), tan(π/4), ln(1), eπ and number.
five random double numbers between 0.0 and
1.1… public int facto(int x){
int ans = 1;
public class MathApp{ for (int i=2; i<=x; i++){
public static void main(String[] args){ ans = ans * i;
System.out.println(“Math.E = ” + Math.E); }
System.out.println(“Math.PI = ” + Math.PI);
System.out.println(“Math.abs(-1234) = ” + return ans;
Math.abs(-1234)); }
System.out.println(“Math.cos(Math.PI/4) = ”
+ Math.cos(Math.PI/4)); Output
System.out.println(“Math.sin(Math.PI/2) = ” + ??
Math.sin(Math.PI/2)); Program to illustrate different arithmetic
System.out.println(“Math.tan(Math.PI/4) = ” + operators
Math.tan(Math.PI/4));
System.out.println(“Math.log (1) = ”+ public class Arith{
Math.log(1)); public static void main(String[] args){
System.out.println(“Math.exp(Math.PI) = ” + int m=25; int n=7;
Math.exp(Math.PI)); System.out.println(“m = ” + m);
System.out.println(“The first five Random System.out.println(“n = ” + n);
numbers from 1 to 100 are …” ); int sum = m+n;
System.out.println(“m + n = ” + sum);
//To generate random numbers… int diff = m-n;
for (int i=0; i<5; ++i) System.out.println(“m - n = ” + diff);
int prod = m*n;
System.out.println(Math.floor(Math.random()*100) System.out.println(“m x n = ” + prod);
+ “ ”); int quotient = m/n;
} System.out.println(“m / n = ” + quotient);
} int remda = m%n;
System.out.println(“m % n = ” + remda);
Output }
?? }
Using printf() method
Output
public class OpOcHex{ ??
public static void main(String[] args){
Exercises:
System.out.printf(“%d\n”, 26); (1) Write a program to compute the area and
System.out.printf(“%e\n”, +0.000026); perimeter of any plane shape and format your
System.out.printf(“%d\n”, -26); outputs to only 2 decimal places.
System.out.printf(“%o\n”, 26);
System.out.printf(“%x\n”, 26); (2) Write a program to compute the formula:
System.out.printf(“%X\n”, 26); ( )
}
} (3) Write a program to print integer numbers
from -100 to 100. The program should also print
Output even, odd and prime integers within that range.
??
25
Check out the output of this code Formatting output with Class Formatter
26
Using SwitchCase statement Program to compute the times table from 1 to
10
//program to determine if a year is leap year...
import java.util.Scanner; class Times{
class LeapYr{ public static void main(String[] args){
public static void main(String[] args){
Scanner inp=new Scanner(System.in); for (int i=1; i<=10; i++){
//Read in data month and year for (int j=1; j<=10; j++){
System.out.println(“1 – Jan, 2 – Feb … 12 - Dec”); int timesAns = i * j;
System.out.println(“|” +timesAns+“\t”);
int month, yr; }// End of innermost loop