Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
87 views

Java Important Points Textbook: Notebook: First Notebook Created: 6/9/2018 1:48 PM Updated: 6/12/2018 4:49 PM Author

This document provides an overview of important concepts in Java programming, including: - Java buzzwords like simple, secure, portable, etc. - Naming conventions for Java classes and files. The class name should match the file name and have the .java extension. - The main method signature and how it is the entry point for all Java programs. - Common Java statements, keywords, operators, data types, literals and how to use them. - Control flow structures like if/else, for loops, switch statements. - Arrays and multi-dimensional arrays. - Comments in Java code. So in summary, this document covers fundamental Java concepts, syntax

Uploaded by

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

Java Important Points Textbook: Notebook: First Notebook Created: 6/9/2018 1:48 PM Updated: 6/12/2018 4:49 PM Author

This document provides an overview of important concepts in Java programming, including: - Java buzzwords like simple, secure, portable, etc. - Naming conventions for Java classes and files. The class name should match the file name and have the .java extension. - The main method signature and how it is the entry point for all Java programs. - Common Java statements, keywords, operators, data types, literals and how to use them. - Control flow structures like if/else, for loops, switch statements. - Arrays and multi-dimensional arrays. - Comments in Java code. So in summary, this document covers fundamental Java concepts, syntax

Uploaded by

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

Java important points textbook

Notebook: First Notebook


Created: 6/9/2018 1:48 PM Updated: 6/12/2018 4:49 PM
Author: abinshoby@gmail.com

The Java Buzzwords


• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic

Byconvention, the name of that class should match the name of the file that holds the program. You should also make
sure that the capitalization of the filename matches the class name.
When Java source code is compiled, each individual class is put into its own output file named after the class and using
the .class extension. This is why it is a good idea to give your Java source files the same name as the class they
contain—the name of the source file will match the name of the .class file.When you execute java as just shown, you
are actually specifying the name of the class that you want to execute. It will automatically search for a file by that
name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.
3 types of comments 1)single line 2)multiline 3)documentation comment
documentation comment begin with /** and ends with */
In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program
is started.
The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is
necessary since main( ) is called by the Java Virtual Machine before any objects are made.
args receives any command-line arguments present when the program is executed.
System.out.print() doesnot put newline character at the end after printing but System.out,println() put newline at the
end after printing.
Control statements
if statement
condition statement;
if( )
for loop
initialization; condition; iteration statement
for( ) ;
Identifiers
They must not begin with a number, lest they be confused with a numeric literal.
-,+,* etc cannot be used
Primitive datatypes
• Integers This group includes byte(1byte), short(2 byte), int(4 byte), and long(8 bytes), which are for whole-
valued
signed numbers.
• Floating-point numbers This group includes float(4 bytes) and double(8 bytes), which represent
numbers with fractional precision
• Characters This group includes char, which represents symbols in a character set,
like letters and numbers.
• Boolean This group includes boolean, which is a special type for representing
true/false values
System.out.println("10 > 9 is " + (10 > 9));//output 10 > 9 is true
0x7ffffffffffffffL or 9223372036854775807L is the largest long.// integer literal
6.022E23, 314159E–05, and 2e+100.//floating point literal D or d is attached for double and f or F attached at end for
float
For octal notation, use the backslash followed by the three-digit number. For example, ‘\141’ ‘a’.
is the letter
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, ‘\u0061’ is the ISO-
Latin-1‘a’ ‘\ua432’
because the top byte is zero. is a Japanese Katakana character.
Examples of string literals
“Hello World”
“two\nlines”
“\”This is in quotes\”“
When one type of data is assigned to another type of variable, an automatic type conversion will take place if the
following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type. so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion(sometimes called a narrowing conversion,) . It has this general form:
(target type value
- )
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

int[] nums, nums2, nums3; // create three arrays

creates three array variables of type int. It is the same as writing


int nums[], nums2[], nums3[]; // create three arrays

normal right shift >> preserves the sign bit but >>> add 0 at the msb after shift

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be
sure that a division operation will be valid before evaluating it:

if (denom != 0 && num / denom > 10)


exception when denom is zero. If this line of code were written using the single & version of AND, both sides would be
evaluated, causing a run-time exception when denom is zero. It is standard practice to use the short-circuit forms of AND and
OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are
exceptions to this rule. For example, consider the following statement:
if(c==1 & e++ < 100) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

Highest
() [] .(dot)
++ – – ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest

Control statements
Selection
control statements can be put into the following categories: selection, iteration, and jump. statements allow your
program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration
statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion.

In switch case if there is no break then all the conditions after the statement that has no break is evaluated and
executed
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
for each version of for loop
// The for-each loop is essentially read-only.
class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
The first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect
on the underlying array nums, as the second for loop illustrates. The output, shown here, proves this point:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
In 2d array
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
Jump Statements
They are break,continue,return
java supports goto by using labelled break
The general form of the labeled break statement is shown here:
break label;
A label is any valid Java identifier followed by a colon.
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Running this program generates the following output:
Before the break.
This is after second block.
Labelled continue is also supported
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The continue statement in this example terminates the loop counting j and continues with the next iteration of the
loop counting i. Here is the output of this program:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
Diff betw argument and parameter

parameter is the variable that recieves the value passed to a method and the value passed when method is invoked is
called argument.

Instance variable hiding(same name for local variable and instance variable): solution use this keyword
Finalization: means use of finalize() function to perform some action before destroying the objects(before garbage
collection)
syntax:
protected void finalize( )
{
// finalization code here
}
static keyword
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in the
next chapter.)
First static instance variables created then static block is executed;
As you can see, the size of each array is displayed. Keep in mind that the value of length has nothing to do with the
number of elements that are actually in use. It only reflects the number of elements that the array is designed to hold.
Nested class
A nested class has access to the members, including private members, of the class in which it is nested.
There are two types of nested classes: static and non-static . A static nested class is one that has the static modifier
applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer
to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all
of the variables and methods of its outer class and may refer to them directly in the same way that other non-static
members of the outer class do.
You can, however, create an instance of Inner class outside of Outer class by qualifying its name with Outer, as in
Outer.Inner
anonymous inner classes , which are inner classes that don’t have a name.
Strings
String are immutable;
definition of string functions
boolean equals(String object )
int length( )
char charAt(int index )
Variable length arguments
method that takes a variable number of arguments is called a variable-arity method , or simply avarargs method . This
feature is called varags
Avariable-length argument is specified by three periods (...). For example, here is how vaTest( ) is written using a
vararg:
static void vaTest(int ... v) {
inside vaTest( ), v is accessed using the normal array syntax. Here is the preceding program rewritten using a vararg
// Demonstrate variable-length arguments.
class VarArgs {
// vaTest() now uses a vararg.
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Notice how vaTest() can be called with a
// variable number of arguments.
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}
conditions of varags
int doIt(int a, int b, double c, int ... vals) { //correct
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!
ambiguity is problem in varags when two overloaded varags are defined and a zero argument function of the same
name is called.
Inheritance
That is, when a reference to a subclass object is assigned to a superclass reference variable, you will have access only
to those parts of the object defined by the superclass
for method overriding subclass and super class must have the function with same name and type signature ,if type
signature is different then method overloading take place
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than
compile time.Dynamic method dispatch is important because this is how Java implements run-time polymorphism.
In other words, it is the type of the object being referred to (not the type of the reference variable) that determines
which version of an overridden method will be executed
Advantage of method overriding
code reuse
run time polymorphism
robustness
uses of final
1)declare constants
2)prevent overriding
Methods declared as final can sometimes provide a performance enhancement: The compiler is free to inline calls to
them because it “knows” they will not be overridden by a subclass. When a small final method is called, often the Java
compiler can copy the bytecode for the subroutine directly inline with the compiled code of the calling method, thus
eliminating the costly overhead associated with a method call. Inlining is only an option with final methods. Normally,
Java resolves calls to methods dynamically, at run time. This is called late binding. However, since final methods cannot
be overridden, a call to one can be resolved at compile time. This is called early binding.
3)prevent inheritance;class is declared final

Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of
any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array.
Packages
Packages are containers for classes that are used to keep the class name space compartmentalized.
Private No Modifier Protected Public
Same class Yes Yes Yes Yes
Same
package
subclass

No Yes Yes Yes

Same
package
non-subclass

No Yes Yes Yes

Different
package
subclass

No No Yes Yes

Different
package
non-subclass

No No No Yes

Interfaces
When you implement an interface method, it must be declared as public.
If a class includes an interface but does not fully implement the methods defined by that interface, then that class must
be declared as abstract.
An interface can be declared a member of a class or another interface. Such an interface is called amember interface or
anested interface
A nested interface can be declared as public, private, or protected. This differs from a top-level interface, which
must either be declared as public or use the default access level
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface, it must provide implementations for all methods
defined within the interface inheritance chain. Following is an example:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Exception handling
An exception is an abnormal condition that arises in a code sequence at run time.
All exception types are subclasses of the built-in class Throwable
Athrows clause lists the types of exceptions that a method might throw
Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the
program does not specify a throws clause to declare this fact, the program will not compile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, you need to make two changes. First, you need to declare that throwOne( ) throws
IllegalAccessException. Second, main( ) must define a try/catch statement that catches this exception. The
corrected example is shown here:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Chained Exception
The chained exception feature allows you to associate another exception with an exception.
To allow chained exceptions, two constructors and two methods were added to Throwable. The constructors are
shown here:
Throwable(Throwable causeExc )
Throwable(String msg causeExc
, Throwable )
The getCause( ) method returns the exception that underlies the current exception. If there is no underlying
exception, null is returned. The initCause( ) method associates causeExc with the invoking exception and returns a
reference to the exception. Thus, you can associate a cause with an exception after the exception has been created.
// Demonstrate exception chaining.
class ChainExcDemo {
static void demoproc() {
// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
The output from the program is shown here:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
MultiThreading
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
there are two distinct types of multitasking: processbased and thread-based.
In processbased multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
In athread-based multitasking environment, the thread is the smallest unit of dispatchable code.
Advantages of multithread over multi process
Processes are heavyweight tasks that require their own separate address spaces. Interprocess communication is
expensive and limited. Context switching from one process to another is also costly. Threads, on the other hand, are
lightweight. They share the same address space and cooperatively share the same heavyweight process.Interthread
communication is inexpensive, and context switching from one thread to the next is low cost. While Java programs
make use of processbased multitasking environments, process-based multitasking is not under the control of Java.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can
be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates,
because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at
which the computer can process it. Even local file system resources are read and written at a much slower pace than
they can be processed by the CPU. And, of course, user input is much slower than the computer.
Monitor is used for thread synchronization
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
output
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
//currentThread return reference to currently executing thread. here 5 is the priority which is default for main and main
is the group to which the thread belongs.
A thread group is a data structure that controls the state of a collection of threads as a whole.
definition of fns
static void sleep(longmilliseconds ) throws InterruptedException
static void sleep(longmilliseconds, nanoseconds
int ) throws InterruptedException
final void setName(String threadName )
final String getName( )
using runnable
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
output
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
main thread must be the last thread to finish running.
using extend
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
definitions of fns
final boolean isAlive( )
final void join( ) throws InterruptedException
level
final void setPriority(int )
final int getPriority( )
// Demonstrate thread priorities.
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
output
Low-priority thread: 4408112
High-priority thread: 589626904
synchronization
synchronized( object ){
// statements to be synchronized
}
eg:
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods.
• wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
definitions
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
other definitions
final void suspend( )
final void resume( )
final void stop( )
The following program demonstrates these methods:
// Using suspend() and resume().
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
output
New thread: Thread[One,5,main]
One: 15
New thread: Thread[Two,5,main]
Two: 15
One: 14
Two: 14
One: 13
Two: 13
One: 12
Two: 12
One: 11
Two: 11
Suspending thread One
Two: 10
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
Suspending thread Two
One: 10
One: 9
One: 8
One: 7
One: 6
Resuming thread Two
Waiting for threads to finish.
Two: 5
One: 5
Two: 4
One: 4
Two: 3
One: 3
Two: 2
One: 2
Two: 1
One: 1
Two exiting.
One exiting.
Main thread exiting.

//another

// Suspending and resuming a thread the modern way.


class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
I/O
A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the
Java I/O system.
Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example,
when reading or writing binary data. Character streams provide a convenient means for handling input and output of
characters. They use Unicode and, therefore, can be internationalized.
System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input,
which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default.
However, these streams may be redirected to any compatible I/O device. System.in is an object of type
InputStream; System.out and System.err are objects of type PrintStream.
definitions
FileInputStream(String fileName ) throws FileNotFoundException
FileOutputStream(String fileName ) throws FileNotFoundException
void close( ) throws IOException
int read( ) throws IOException
void write(int byteval ) throws IOException //FileOutputStream
Strings
The String, StringBuffer, and StringBuilder classes are defined in java.lang .All are declared final, which means
that none of
these classes may be subclassed.
forms of string constructor
String(byte asciiChars [ ])
String(byte asciiChars startIndex numChars
[ ], int , int )
String(char chars startIndex numChars
[ ], int , int )
String(String strObj )
String(char chars [ ])
other fns
void getChars(int sourceStart sourceEnd target
, int , char targetStart
[ ], int ) sourceStart
// Here, specifies the index
of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring.
byte[ ] getBytes( )//There is an alternative to getChars( ) that stores the characters in an array of bytes. This method
is called getBytes( ), and it uses the default character-to-byte conversions provided by the platform.
char[ ] toCharArray( )
boolean regionMatches(int startIndex str2 str2StartIndex numChars
, String , int , int )//The regionMatches( ) method
compares a specific region inside a string with another specific region in another string.
boolean regionMatches(boolean ignoreCase startIndex
, int str2 str2StartIndex
, String , int numChars
, int )
boolean startsWith(String ) str
boolean endsWith(String ) str
indexOf( ) Searches for the first occurrence of a character or substring.
lastIndexOf( ) Searches for the last occurrence of a character or substring.
String substring(int startIndex endIndex
, int )
String substring(int startIndex )
String concat(String ) str
String replace(char original replacement
, char )
String replace(CharSequence original replacement
, CharSequence )
static String valueOf(double num )
static String valueOf(long num )
static String valueOf(Object ) ob
static String valueOf(char chars [ ])
static String valueOf(char chars startIndex
[ ], int numChars
, int )
String toLowerCase( )
String toUpperCase( )
String[ ] split(String regExp)
String[ ] split(String regExp, int max)
StringBuffer
constructors used
StringBuffer( )
StringBuffer(int size )
StringBuffer(String ) str
StringBuffer(CharSequence chars )
other fns of stringbuffer
int length( )//current length
int capacity( )//total alloted capacity
void ensureCapacity(int capacity ) //set capacity
void setLength(int len ) //set length
char charAt(int where )
void setCharAt(intwhere ch , char )
void getChars(intsourceStart sourceEnd target
, int , char targetStart
[ ], int )
StringBuffer append(String )str
StringBuffer append(int num )
StringBuffer append(Object obj )
index
StringBuffer insert(int str
, String )
index ch
StringBuffer insert(int , char )
index
StringBuffer insert(int obj
, Object )
StringBuffer reverse( )
StringBuffer delete(intstartIndex endIndex
, int )
StringBuffer deleteCharAt(int loc )
StringBuffer replace(intstartIndex endIndex
, intstr , String )
startIndex
String substring(int )
startIndex endIndex
String substring(int , int )
int indexOf(String str, int startIndex)
int indexOf(String str)
Here is an example:
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
output
buffer = Hello
length = 5
capacity = 21
StringBuilder
J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called
StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means
that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are
using multithreading, you must use StringBuffer rather than StringBuilder.
Applet
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes
provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for
window-based activities.
Methods
init( )
The init( ) method is the first method to be called. This is where you should initialize variables. This method is called
only once during the run time of your applet.
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init(
) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).
paint( )
The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several
reasons. For example, the window in which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins
execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint() method
has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics
environment in which the applet is running. This context is used whenever output to the applet is required.
stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to
another page, for example. When stop( ) is called, the applet isprobably running. You should use stop( ) to suspend
threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user
returns to the page.
destroy( )
The destroy( ) method is called when the environment determines that your applet needs to be removed completely
from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always
called before destroy( ).
Overriding update( )
In some situations, your applet may need to override another method defined by the AWT, called update( ). This
method is called when your applet has requested that a portion of its window be redrawn. The default version of
update( ) simply calls paint( ). However, you can override the update( ) method so that it performs more subtle
repainting. In general, overriding update( ) is a specialized technique that is not applicable to all applets, and the
examples in this book do not override update( ).
definition of fns
void drawString(String message x y
, int , int )
void setBackground(Color newColor )
void setForeground(Color newColor )
color available
Color.black
Color.magenta
Color.blue
Color.orange
Color.cyan
Color.pink
Color.darkGray
Color.red
Color.gray
Color.white
Color.green
Color.yellow
Color.lightGray
Color getBackground( )
Color getForeground( )
void repaint( )
void repaint(intleft top width height
, int , int , int )
void repaint(long maxDelay )
void repaint(long maxDelay x y width
, int , int , int height maxDelay
, int )// specifies the maximum number of milliseconds
that can elapse before update( ) is called.
showStatus( )
URL url = getCodeBase()
AppletContext ac = getAppletContext();
showDocument( )//load another url
general applet html code
< APPLET
[CODEBASE = codebaseURL ]
CODE =appletFile
alternateText
[ALT = ]
[NAME =appletInstanceName ]
WIDTH = pixels HEIGHT =pixels
[ALIGN =alignment ]
[VSPACE = pixels ] [HSPACE =pixels ]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue >]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue >]
...
HTML Displayed in the absence of Java
[ ]
</APPLET>
Event Handling
Delegation event model
standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an
event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns. The advantage of this design is that the application
logic that processes events is cleanly separated from the user interface logic that generates those events. Auser
interface element is able to “delegate” the processing of an event to a separate piece of code. In the delegation event
model, listeners must register with a source in order to receive an event notification. This provides an important benefit:
notifications are sent only to listeners that want to receive them.
Events
In the delegation model, an eventis an object that describes a state change in a source
Event Sources
Asource is an object that generates an event
When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as
multicasting the event.general form of multicasting :
public void add Type Listener( TypeListener )el
unicasting:
public void add Type Listener( Type el
Listener ) throws java.util.TooManyListenersException
Here, Type el
is the name of the event, and is a reference to the event listener. When such an event occurs, the
registered listener is notified. This is known as unicasting the event.
EventObject, which is in java.util. It is the superclass for all events.
EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of
the event. Its general form is shown here:
Object getSource( )
getID( ) method can be used to determine the type of the event. The signature of this method is shown here:
int getID( )
ActionEvent class has these three constructors:
ActionEvent(Object src , int type cmd
, String )
ActionEvent(Object src , int type cmd
, String , intmodifiers )
ActionEvent(Object src , int type cmd
, String , longwhen modifiers
, int )
The method getWhen( ) returns the time at which the event took place. This is called the event’s timestamp.
The
getWhen( ) method is shown here:
long getWhen( )
Swing
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
other close options
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
There is no drawCircle() method use drawOval(x,y,r,r)
import event class separately
implement itemStateChanged() for itemlistener
close all jdbc connection
getButton() is used for getting mouse button clicked .1 for left 3 for right. 0 for no button
setBackground() for setting color
this.addListener(this) can be used in applet for graphics based listening
class for jdbc thin: oracle.jdbc.driver.OracleDriver
url-"jdbc:oracle:thin:@"+servername
no of components should be specified in gridlayout
checkboxgroup cant be added
Layouts are not defned in swing class so awt should be imported
The TextListener Interface
This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text field. Its general
form is shown here:

void textChanged(TextEvent te)


The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is invoked. When a component
loses keyboard focus, focusLost( ) is called. Their general forms are shown here:

void focusGained(FocusEvent ) fe
void focusLost(FocusEvent )fe
The ComponentListener Interface
This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. Their general forms
are shown here:

void componentResized(ComponentEvent ) ce
void componentMoved(ComponentEvent ) ce
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( ) is invoked. Their general forms are shown here:

void componentAdded(ContainerEvent ) ce
void componentRemoved(ContainerEvent ) ce
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is
shown here:

void itemStateChanged(ItemEvent ie)


The WindowFocusListener Interface
This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called when a window
gains or loses input focus. Their general forms are shown here:

void windowGainedFocus(WindowEvent )we


void windowLostFocus(WindowEvent )we
Swing additional
The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. These containers do not inherit JComponent.
They do, however, inherit the AWT classes Component and Container.
do
The second type of containers supported by Swing are lightweight containers. Lightweight containers inherit JComponent. An
example of a lightweight container is JPanel, which is a general-purpose container.
Files
while finding lemgth it should be casted to int (in filereader,.)
in buffered writer constructor the values passed is either filewriter object or buffered writer object
buffered reader can insert newline using newLine() method and it can read a line of characters compared to filereader
and filewriter
argument to printwriter() constructer can be filename in strings,file object or filewriter writer object
print() and println() methods of printwriter prints the actual integer values but not ascii .in case of write() it prints
corresponding ascii. pint() and println() can print boolean and double values but not character array.
in fileoutputstream the content to be written is converted to bytes using content.getBytes() fn and then print that value
if main class is made abstract then it will work
method overloading donot depend on return type
class ex14{public static void main(String args[]){
int a=0;int b=1;int c=2;
if(a!=0&& b/a>10){
System.out.println("hello");}
else
System.out.println("else");

}}
//short circuiting effect no error at output
float array should be initialized using 'f' ie
float f5[]={1.0f,2.0f,3.0f}; otherwise compile time error since it will be treated as double

You might also like