Sunteți pe pagina 1din 14

UNIT I JAVA FUNDAMENTALS

Java Data types – Class – Object – I / O Streams – File Handling concepts – Threads –
Applets – Swing Framework – Reflection

1.Simple Program of Java


Program – simple.java
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

Compile by: javac Simple.java

Run by: java Simple

Output:
hellojavatpoint

2. Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
3.Object in Java
• An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc.
• An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
• identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user.
Class in Java
• A class is a group of objects which have common properties.
• A class in Java can contain:
• fields
• methods
• constructors
• blocks
• nested class and interface
• Syntax to declare a class:
class<class_name>
{
field;
method;
}

Program
class Student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

Output:

101
Sonoo
4. I/O Stream
• Stream defined as a sequence of data.
– InPutStream − used to read data from a source.
– OutPutStream − used for writing data to a destination.
1. Byte Stream : for handling input and output of byte(8-bit bytes).
2. Character Stream : for handling input and output of characters(16-bit unicode).
Standard Streams
• Standard Input − keyboard -represented as System.in.
• Standard Output − -computer screen - represented as System.out.
• Standard Error − error data -computer - represented as System.err.

Some important Byte stream classes.


Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data
type

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.


PrintStream Output Stream that contain print() and println() method

Some important Character stream classes.


Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

5. Java FileOutputStream example

import java.io.FileOutputStream;
public class Example
{
public static void main(String args[])
{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.

Java FileInputStream example

package com.javatpoint;

import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}
}
Output:

Welcome to javaTpoint

Java FileReader Example

In this example, we are reading the data from the text file testout.txt using Java FileReader
class.

package com.javatpoint;

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to javaTpoint.

Output:

Welcome to javaTpoint.

Java FileWriter Example

In this example, we are writing the data in the file testout.txt using Java FileWriter class.

package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}
catch(Exception e)
{ System.out.println(e); }
System.out.println("Success...");
}
}

Output:

Success...

testout.txt:

Welcome to javaTpoint.
6.Thread
• Thread is a lightweight sub-process, a smallest unit of processing.
• Multithreading in java is a process of executing multiple threads simultaneously.
• used to achieve multitasking.
• threads share a common memory area.
• used in games, animation etc.
Life cycle of a Thread (Thread States)
• life cycle of the thread in java is controlled by JVM.
• Thread States are
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

Java Thread by extending Thread class


Class Thread
{
public void run()
{
System.out.println("thread is running...");
}
}
class Multi extends Thread
{

public static void main(String args[])


{
Multi t1=new Multi();
t1.start();
}
}
Output:

thread is running...

Thread Priority
• 3 constants defined in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY

Example of priority of a Thread:


class TestMultiPriority1 extends Thread{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
7. Applet
• Applet is a Java program that can be embedded into a web page.
• It runs inside the web browser and works at client side.
• Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a
web server.
• Applets are used to make the web site more dynamic and entertaining.
• All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
• Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer.
• JDK provides a standard applet viewer tool called applet viewer.
• In general, execution of an applet does not begin at main() method.
• Output of an applet window is not performed by System.out.println(). Rather it is handled
with various AWT methods, such as drawString().
Life cycle of an applet :
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
• public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
Features of Applets over HTML

– Displaying dynamic web pages of a web application.


– Playing sound files.
– Displaying documents
– Playing animations
– Displaying image
– EventHandling
How to run an Applet?
• There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
• Simple example of Applet by html file:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Helloworld",150,150);
}
}
8.Swing
• Swing Framework contains a set of classes that provides more powerful and flexible GUI
components than those of AWT.
• Swing provides the look and feel of modern Java GUI.
• Swing library is an official Java GUI tool kit released by Sun Microsystems.
• It is used to create graphical user interface with Java.
• Swing classes are defined in javax.swing package and its sub-packages.
• Main Features of Swing Toolkit
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls

Swing Classes
• JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout,
FlowLayout.
• JFrame : JFrame is Swing's version of Frame and is descended directly
from Frame class.
• JWindow : This is Swing's version of Window and has descended directly
from Window class.
• JLabel : is used to create text labels.
• JButton : JButton class provides the functioning of push button.
– JButton allows an icon, string or both associated with a button.
• JTextField : JTextFields allow editing of a single line of text.
Creating a JFrame
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
9.Java Reflection API
Java Reflection is a process of examining or modifying the run time behavior of a class at run
time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.
Where it is used
The Reflection API is mainly used in:
o IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
o Debugger
o Test Tools etc.
Creating your own appletviewer

As you know well that appletviewer tool creates a frame and displays the output of applet in the
frame.You can also create your frame and display the applet output.

Example that works like appletviewer tool

Let's see the simple example that works like appletviewer tool. This example displays applet on
the frame.

import java.applet.Applet;
import java.awt.Frame;
import java.awt.Graphics;

public class MyViewer extends Frame{


public static void main(String[] args) throws Exception{
Class c=Class.forName(args[0]);

MyViewer v=new MyViewer();


v.setSize(400,400);
v.setLayout(null);
v.setVisible(true);

Applet a=(Applet)c.newInstance();
a.start();
Graphics g=v.getGraphics();
a.paint(g);
a.stop();

}
//simple program of applet

import java.applet.Applet;
import java.awt.Graphics;

public class First extends Applet


{

public void paint(Graphics g)


{
g.drawString("Welcome",50, 50);
}
}

S-ar putea să vă placă și