#FlowLayout
Explore tagged Tumblr posts
Text
hi
Scrollbar ScrollPane Type Component (a widget) Container (a container that can hold components)Scrollbar: Just the scroll bar, standalone.
ScrollPane: A container that can show scrollbars when needed for its content.
Java Swing, a Container is a component that can hold and organize other components (like buttons, text fields, etc.). It is part of the AWT hierarchy but is also used in Swing through classes like JPanel, JFrame, and JDialog, which are all containers.
Here's a simple Swing layout design using a JFrame with a combination of BorderLayout and FlowLayout. It includes a header, footer, center area, and side panel.
FlowLayout Default for: JPanel
Arranges: Left to right, wraps to next line.
BorderLayout Default for: JFrame
Divides into 5 regions: North, South, East, West, Center
GridLayout Arranges: Components in a rectangular grid.
All cells are equal in size.
BoxLayout Arranges: Components either vertically (Y_AXIS) or horizontally (X_AXIS).
Usage:
GridBagLayout Most flexible, but complex.
Allows components to span multiple rows/columns and align precisely.
FlowLayout Simple row layout Low Low BorderLayout App-like UI with sections Medium Low GridLayout Equal-sized grid Medium Low BoxLayout List-like vertical/horizontal stack Medium Medium GridBagLayout Complex form-like layout High High CardLayout Switching panels (tabs/wizards)
Using layout managers provides flexibility, portability, and maintainability when building GUIs. Here's a breakdown of their key advantages:
Platform Independence Layout managers adapt to different screen sizes and resolutions automatically.
You don't need to manually set pixel positions for components.
Without Layout Manager (using null layout): You're responsible for absolute positioning and sizing (setBounds()).
Not responsive or portable.
Breaks with different screen DPI or user settings.
Scrollbar vs ScrollPane Scrollbar:
A standalone component (widget).
Just the scroll bar itself; does not contain other components.
ScrollPane:
A container that can hold another component and adds scrollbars as needed.
Manages content overflow automatically.
Container in Java Swing A Container can hold and organize other components like buttons, text fields, panels, etc.
Examples of Containers in Swing:
JPanel
JFrame
JDialog
Containers come from the AWT hierarchy, but are heavily used in Swing as well.
Why Use Layout Managers? Platform Independence:
Layout managers automatically adjust to different screen sizes and resolutions.
Avoids Manual Positioning:
No need to manually set x, y, width, height via setBounds().
Responsiveness:
UIs adapt to font changes, screen DPI settings, window resizing, etc.
Maintainability:
Easier to modify layouts without breaking the UI across different devices.
Drawback of NOT Using Layout Managers Using null layout (no layout manager):
You must manually set component positions and sizes.
Non-responsive: Breaks on different screen sizes and settings.
Not portable: UI may look fine on one machine, but terrible on another.
FlowLayout
Arranges: Left to right, wraps to next line.
Notes: Default for JPanel.
BorderLayout
Arranges: Divides into 5 regions — North, South, East, West, Center.
Notes: Default for JFrame.
GridLayout
Arranges: Components in a rectangular grid with equal-sized cells.
Notes: Simple and uniform layout.
BoxLayout
Arranges: Components stacked vertically (Y_AXIS) or horizontally (X_AXIS).
Notes: Good for list-like or linear layouts.
GridBagLayout
Arranges: Highly flexible, components can span multiple rows/columns.
Notes: Complex but powerful for fine-tuned layouts.
CardLayout
Arranges: Allows switching between multiple panels (like cards).
Notes: Useful for building tabbed panels, step-by-step wizards.
Quick Comparison of Layout Managers FlowLayout
Use Case: Simple row layout.
Flexibility: Low.
Complexity: Low.
BorderLayout
Use Case: Application-like UI with structured sections.
Flexibility: Medium.
Complexity: Low.
GridLayout
Use Case: Uniform grid with equal-sized components.
Flexibility: Medium.
Complexity: Low.
BoxLayout
Use Case: Vertical or horizontal stacking of components.
Flexibility: Medium.
Complexity: Medium.
GridBagLayout
Use Case: Complex, form-like layouts with precise control.
Flexibility: High.
Complexity: High.
CardLayout
Use Case: Switching between multiple panels (like tabs).
Flexibility: Medium.
Complexity: Medium.
Event Dispatch Thread (EDT) in Java Swing is the special thread responsible for handling all GUI events — like button clicks, screen repaints, key presses, and mouse movements. Swing is not thread-safe — meaning you should only update the UI from one thread, and that thread is the EDT.
Key Rules: Create and update GUI components on the EDT.
Never do long-running tasks (like file or network access) on the EDT — it freezes the UI.
Creating GUI on EDT (best practice): java Copy Edit SwingUtilities.invokeLater(() -> { // Safe to create GUI components here JFrame frame = new JFrame("EDT Example"); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); });
EDT handles all UI updates and events.
Always use invokeLater() or SwingWorker to interact with the UI safely.
Never block the EDT — it makes your GUI unresponsive.
Using SwingWorker The built-in SwingWorker handles threading and result-passing for you.
// 1) Define a SwingWorker that returns your data type SwingWorker, Void> worker = new SwingWorker<>() { @Override protected List doInBackground() throws Exception {
Using ExecutorService + invokeLater If you need a pool of threads or more control:
ExecutorService dbPool = Executors.newFixedThreadPool(2);
Use background threads (SwingWorker, ExecutorService, CompletableFuture).
Update Swing components only on the EDT (invokeLater(), done(), or thenAcceptAsync).
Java Swing, a component's preferred size determines how much space it wants to occupy, and layout managers usually respect this when arranging components.
MVC (Model-View-Controller) – Primary Swing Pattern Swing uses a lightweight version of MVC.
Model – Holds data (e.g., TableModel, ListModel)
View – The UI component (e.g., JTable, JList)
Controller – Often combined into the View via event listeners
Observer Pattern Used in event handling — listeners observe changes and respond.
Example: ActionListener, ChangeListener, PropertyChangeListener
Composite Pattern UI components and containers follow this pattern.
JPanel can contain JButton, JLabel, etc., and be treated as a single component.
Singleton Pattern Often used for a central app window or config manager.
develop a JTable in Java Swing, you can either use:
Simple data + column arrays (quick setup), or
Custom TableModel (for more control, e.g., editable cells, dynamic data).
JTable with DefaultTableModel (editable & dynamic)
. Custom TableModel (for full control) If you want non-editable columns or custom data source (like a database), extend AbstractTableModel. Use a Custom TableModel (AbstractTableModel) This gives you full control over:
Data source (could be a list, database, etc.)
Column behavior (e.g., types, editable columns) if your table data changes frequently (like from a database, real-time updates, or user interaction), you should use a custom AbstractTableModel with a List-based backend. This approach gives you:
Clean separation of data and UI
Easy updates (add, remove, modify rows)
Fine control over column behavior (e.g., editable or read-only)
create a JTable with dynamic columns at runtime — meaning the columns can change while the application is running (e.g., based on user action or data changes).
Custom TableModel for Dynamic Columns
You can call setColumns(…) at any time to dynamically change column headers and structure.
Rows can be added using addRow(…) with values matching the new column layout.
The table refreshes itself with fireTableStructureChanged().
Cell Click / Selection Event Use a ListSelectionListener to detect row selection:
To handle mouse clicks in a JTable, such as detecting double-clicks, right-clicks, or clicks on specific cells, use a MouseListener or MouseAdapter.
display different cells in different colors based on data, you can override the prepareRenderer() method in JTable. This lets you customize cell background and foreground colors dynamically depending on the cell's content or row/column inde
What You Can Customize: c.setBackground(Color.X) – change background
c.setForeground(Color.Y) – change text color
You can also change font, borders, tooltips, etc.
Steps to Update Cell Background Based on Data and Repaint Assuming you're customizing cell colors with prepareRenderer():
Change the underlying data in your TableModel
model.setValueAt("Failed", rowIndex, colIndex);
Then trigger a repaint of the table
table.repaint();
Ensure the TableModel supports editing If you're using DefaultTableModel, editing is enabled by default.
If you're using a custom AbstractTableModel, override: Implement setValueAt() in Custom TableModel If you're using a custom model, this method must actually update the data:
sort data in a JTable, you can use the built-in TableRowSorter, which works with any TableModel (like DefaultTableModel or AbstractTableModel).
Features of TableRowSorter Click on a column header to sort ascending/descending
Can sort numerically or alphabetically
You can programmatically control sorting:
Sorting for Custom TableModel Works the same way as long as your getValueAt() returns proper data types (Integer, String, etc.) — not Strings for everything.
To implement flushing (auto-refresh) every 3 seconds in a JTable, you can use a javax.swing.Timer. This is Swing-safe and fires events on the Event Dispatch Thread (EDT).
Flush from a database query
Flush based on web API call
Conditional flushing (if flag is dirty)
0 notes
Link
A bi-directional layout framework for iOS
1 note
·
View note
Text
Flowlayout margins

#Flowlayout margins how to
An alternative to using CardLayout is using a A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. The CardLayout class lets you implement an area that contains different components at different times.
#Flowlayout margins how to
It respects the components' requested maximum sizes and also lets you align components.įor further details, see How to Use BoxLayout. The BoxLayout class puts components in a single row or column. JToolBar must be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions.įor further details, see How to Use BorderLayout. All extra space is placed in the center area. Using Top-Level Containers explains, the content pane is the main container in all frames, applets, and dialogs.) A BorderLayout places components in up to five areas: top, bottom, left, right, and center. If you are interested in using JavaFX to create your GUI, seeĮvery content pane is initialized to use a BorderLayout. Otherwise, if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. Note: This lesson covers writing layout code by hand, which can be challenging.

0 notes
Text
Flowlayout margins

It has a scroll direction, a section - Inset (the margins for a section), an itemSize along with a. Then bottom margin of Button1 comes (5 pixels), followed by top margin of Button2 (another 5 pixels). Vertically, first button starts at Y5 and ends above Y28. Introduce itemsĪdd the following to the root item ’ s build. Configuration of a flow layout is very simple. FlowLayoutPanel.PreferredSize (85, 99) As expected, Left property of all buttons is 5, which is width of the left margin (same amount of space is left on the right of each button). The principle is to measure all sub-items, just like the one in the Andrexml layout, and to measure and place sub-items according to direction, spacing, alignment. Note: Setter function for property contentsMargins. On most platforms, the margin is 11 pixels in all directions. By default, QLayout uses the values provided by the style. FlowLayout (QWidget parent, int margin0, int spacing-1). void QLayout:: setContentsMargins (const QMargins &margins) Sets the margins to use around the layout. Horizontal, horizontalAlignment : Alignment. Inheritance diagram for casa::FlowLayout: Public Member Functions. In the constructor we call setContentsMargins() to set the left, top, right and bottom margin. */ fun FlowLayout ( modifier : Modifier = Modifier, orientation : Orientation = Orientation. :: The maximum number of lines (or columns) * Spacing up vertically between sub-grades and sub-levels * Horizontal spacing of sub-levels and sub-levels * The direction of the will be arranged laterally, and the emissions will continue laterally in the next row. :: Line-lined layout with automatic line breaks

0 notes
Text
Flowlayout margins

#FLOWLAYOUT MARGINS CODE#
#FLOWLAYOUT MARGINS CODE#
Next, the code defines a FlowLayout class that inherits ViewGroup. After clicking on Item, by clicking on the callback of the event, the Text clicking on item is displayed. The onLayout() method lays out all childViews, which need to be passed into the position of the upper and lower four points of the childView.Ĥ. The onMeasure() method calculates the width and height of all child Views, and then calculates FlowLayout's own width and height according to the width and height of child Views.ģ. We only need to be able to recognize margin at present, so we use Margin Layout Params.Ģ. A flow layout works with the collection view’s delegate object to determine the size. Cells can be the same sizes or different sizes. Items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row containing as many cells as will fit. For FlowLayout, we need to specify Layout Params. A flow layout is a type of collection view layout. Firstly, the figure above:Īs shown in the figure, it is such an effect. Android does not provide a streaming layout, but in some cases, streaming layout is still very suitable for use. If the current row has insufficient space left, it adds to the next row, which is also called streaming layout. The horizontal and vertical inner margins, within which the parents. Gets or sets the distance between the top-left corner of the smallest rectangle containing. This article implements FlowLayout, what FlowLayout? The control automatically adds View to the right according to the width of ViewGroup. FlowLayout is a decorator which automatically arranges views inside a container. Initializes a new instance of the FlowLayout class.

0 notes
Text
Flowlayout java stackoverflow

Calling up the add method without “direction” corresponds a call with BorderLayout.CENTER. This is done using one of the Class constants NORTH, SOUTH, WEST, EAST predefined in BorderLayout and CENTER. When adding components to a container using the add method the second parameter can also be used to determine the area into which the Component is to be inserted. The following constructors of the BorderLayout class are available:Ĭreates a BorderLayout object with the default setting (0 spaces between the areas).Ĭreates a BorderLayout object with horizontal or vertical Distances of h and v pixels between the areas. Accordingly, the size of the there added component adapted. While the size of the components in the north and South by their usual height and that of the components in the west and east is determined by its usual width, the size of the central area may vary according to the size of the container. In each of these five areas a component can be inserted, making a total of five components may appear. To divide the container area into the five areas “North”, “South”, “West”, “East” and “Center” are used Object of the class BoderLayout as layout manager. You change with the Mouse the width of our frame, so there is only space for one label per line If you start the Testing class, then initially (accordingly the space required by the relatively large labeled labels) only ever two of the Labels in one line. The predefined constants LEFT (for left-justified), RIGHT (for right-justified) and CENTER (for centered alignment) as final class variables of the class FlowLayout available. Public FlowLayout (int align, int h, int v)Ĭreates a FlowLayout object with an alignment according to align and horizontal and vertical distances of h and v pixels. In the class FlowLayout we find the following constructors:Ĭreates a FlowLayout object with the default settings (centered Alignment of the lines, 5-pixel spacing).Ĭreates a FlowLayout object with an alignment according to align and the Standard setting for the distances. The size of the components is not changed. Between the components there is a distance of 5 pixels horizontally and vertically. The orientation of the components the line is centered by default. That is, the components are so long in the order their insertion from left to right side by side until there is no more space for the next component is available and started with a new line which is then filled in the same way. “Flowing” means here that the components are inserted into the container line by line from left to right Be observed. To arrange the components in a container in a fluid manner, one uses an object of the class FlowLayout as a layout manager. The only exception is the JPanel class (a Component that we will get to know in my next article). The standard layout in the container classes is BorderLayout discontinued. There are also some specialized ones Layout variants such as BoxLayout, CardLayout, GridBagLayout or overlay layout. The three most frequently used layout managers are FlowLayout, BorderLayout and GridLayout with them, we will therefore be in the deal with the following sections. I would appreciate your support in this way! What are the different types of layout manager in java? I may make a commission if you buy the components through these links. The layout managers distribute the entire space the container area depends on the components entered, whereby (each according to layout) is partially inserted space or components in their Size adjusted or not displayed at all. Java provides numerous classes that implement this interface and ultimately differ in that they divide the container area into different Divide areas. This Layout Manager interface therefore defines methods which are necessary for the arrangement of AWT and Swing components. We have already seen that a layout manager can arrange the various Components in a container and such a layout Manager through an object of a class that implements the Layout Manager interface, is produced. 2 What are the different types of layout manager in java?.

0 notes
Text
명품 자바 에션셜 황기태
chapter 01자바 시작 1.1 컴퓨터와 프로그래밍 1.2 자바의 출현과 WORA 1.3 개발 도구와 자바 플랫폼 1.4 자바 프로그램 개발 과정 1.5 이클립스를 이용한 자바 프로그램 개발 1.6 자바 응용프로그램의 종류 1.7 자바의 특징 요약 Open Challenge 연습문제 chapter 02자바 기본 프로그래밍 2.1 자바 프로그램의 구조 2.2 식별자 2.3 자바의 데이터 타입 2.4 자바의 키 입력 2.5 연산자 2.6 조건문 요약 Open Challenge 연습문제 chapter 03반복문과 배열 그리고 예외 처리 3.1 반복문 3.2 continue 문과 break 문 3.3 자바의 배열 3.4 다차원 배열 3.5 메소드의 배열 리턴 3.6 자바의 예외 처리 요약 Open Challenge 연습문제 chapter 04클래스와 객체 4.1 객체 지향과 자바 4.2 자바 클래스 만들기 4.3 생성자 4.4 객체 배열 4.5 메소드 활용과 객체 치환 4.6 객체의 소멸과 가비지 컬렉션 4.7 접근 지정자 4.8 static 멤버 4.9 final 요약 Open Challenge 연습문제 chapter 05상속 5.1 상속의 개념 5.2 클래스 상속과 객체 5.3 protected 접근 지정 5.4 상속과 생성자 5.5 업캐스팅과 instanceof 연산자 5.6 메소드 오버라이딩 5.7 추상 클래스 5.8 인터페이스 요약 Open Challenge 연습문제 chapter 06모듈과 패키지 개념, 자바 패키지 활용 6.1 패키지 6.2 패키지 만들기 6.3 모듈 개념 6.4 자바 JDK에서 제공하는 패키지 6.5 Object 클래스 6.6 Wrapper 클래스 6.7 String과 StringBuffer 클래스 6.8 StringTokenizer 클래스 6.9 Math 클래스 요약 Open Challenge 연습문제 chapter 07컬렉션과 제네릭 7.1 컬렉션과 제네릭 개념 7.2 제네릭 컬렉션 활용 7.3 제네릭 만들기 요약 Open Challenge 연습문제 chapter 08자바 GUI 스윙 기초 8.1 자바의 GUI 8.2 자바 GUI 패키지 8.3 스윙 GUI 프로그램 만들기 8.4 컨테이너(Container)와 배치(Layout) 8.5 FlowLayout 배치관리자 8.6 BorderLayout 배치관리자 8.7 GridLayout 배치관리자 8.8 배치관리자 없는 컨테이너 요약 Open Challenge 연습문제 chapter 09자바의 이벤트 처리 9.1 이벤트 기반 GUI 프로그래밍 9.2 이벤트 객체 9.3 사용자 이벤트 리스너 작성 9.4 어댑터(Adapter) 클래스 9.5 Key 이벤트와 KeyListener 9.6 Mouse 이벤트와 MouseListener, MouseMotionListener 요약 Open Challenge 연습문제 chapter 10스윙 컴포넌트 활용 10.1 스윙 컴포넌트 소개 10.2 JLabel로 문자열과 이미지 출력 10.3 JButton으로 버튼 만들기 10.4 JCheckBox로 체크박스 만들기 10.5 JRadioButton으로 라디오버튼 만들기 10.6 JTextField로 한 줄 입력 창 만들기 10.7 JTextArea로 여러 줄의 입력 창 만들기 10.8 JListE로 리스트 만들기 10.9 JComboBoxE로 콤보박스 만들기 10.10 메뉴 만들기 10.11 팝업 다이얼로그 요약 Open Challenge 연습문제 chapter 11그래픽 11.1 스윙 컴포넌트 그리기 11.2 Graphics 11.3 도형 그리기와 칠하기 11.4 이미지 그리기 11.5 repaint()와 그래픽 응용 요약 Open Challenge 연습문제 chapter 12자바 스레드 기초 12.1 멀티태스킹 12.2 자바 스레드 만들기 12.3 스레드 종료 12.4 스레드 동기화 요약 Open Challenge 연습문제 chapter 13입출력 스트림과 파일 입출력 13.1 자바의 입출력 스트림 13.2 문자 스트림과 텍스트 파일 입출력 13.3 바이트 스트림과 바이너리 파일 입출력 13.4 File 클래스 13.5 파일 복사 응용프로그램 작성 요약 Open Challenge 연습문제 chapter 14자바 소켓 프로그래밍 14.1 TCP/IP 기초 14.2 소켓 프로그래밍 14.3 서버-클라이언트 채팅 프로그램 만들기 14.4 수식 계산 서버-클라이언트 만들기 실습 요약 Open Challenge 연습문제 CHECK TIME 정답
1 note
·
View note
Photo

i need complete and acurate answers for following questions i need complete and acurate answers for following questions ATTACHMENT PREVIEW Download attachmentWeek 3 Homework AssignmentCreate a Word document containing the answers to all the problems given below.1.Write a statement to create a JFrame object with a title of “My GUI Application”.2.Given the object you created in question 1,write a statement to specify the window size tobe 300 pixels wide and 400 pixels high?3.What would you need to do to the object from question 1 to make sure that theapplication containing the object terminated when the object’s window was closed?4.Write a Java statement to make the window associated with the object from question 1visible.5.Explain how a BorderLayout manages its display area.6.Explain how a FlowLayout manages its display area.7.Write a Java statement to have the object from question 1 manage its display area bydividing it into 3 rows which have 4 columns each.8.The frame object from question 1 uses a BorderLayout by default.
0 notes
Text
JAVA Interview Questions and Answers
java interview questions for freshers experienced developers
1. What is Java? Java is a object-oriented programming language originally developed by Sun Micro systems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. 2. What are the supported platforms by Java Programming Language? Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Red hat Linux, Ubuntu, Cent OS, etc. 3. List any five features of Java? Some features include Object Oriented Platform Independent Robust Interpreted Multi-threaded 4. Why is Java Architectural Neutral? It’s 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. 5. What is a singleton class? Give a practical example of its usage. A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class. The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues. 6. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 7. What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management. 8. What is meant by Inheritance and What are its advantages? Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses. 9. What is the difference between superclass and subclass? A super class is a class that is inherited whereas sub class is a class that does the inheriting. 10. What is an abstract class? An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
JAVA Interview Questions 11. What are the states associated in the thread? Thread contains ready, running, waiting and dead states. 12. What is synchronization? Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time. 13. What is deadlock? When two threads are waiting each other and can’t precede the program is said to be deadlock. 14. What is an applet? Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser 15. What is the lifecycle of an applet? init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet’s page. destroy() method - Can be called when the browser is finished with the applet. 16. Define How do you set security in applets? using setSecurityManager() method 17. What is a layout manager and What are different types of layout managers available in java AWT? A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout 18. What is JDBC? JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications. 19. What are drivers available? JDBC-ODBC Bridge driver Native API Partly-Java driver JDBC-Net Pure Java driver Native-Protocol Pure Java driver 20. What is stored procedure? Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. 21. What is the Java API? The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. 22. Why there are no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables due to following reasons: The global variables breaks the referential transparency Global variables creates collisions in namespace. 23. What are Encapsulation, Inheritance and Polymorphism? Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 24. What is the use of bin and lib in JDK? Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages. 25. What is method overloading and method overriding? Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding. 26. What is the difference between this() and super()? this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor. 27. What is Domain Naming Service(DNS)? It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server. 28. What is URL? URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path. 29. What is RMI and steps involved in developing an RMI object? Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application. 30. What is RMI architecture? RMI architecture consists of four layers and each layer performs specific functions: a) Application layer - contains the actual object definition. b) Proxy layer - consists of stub and skeleton. c) Remote Reference layer - gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer - responsible for handling the actual machine-to-machine communication. 31. What is a Java Bean? A Java Bean is a software component that has been designed to be reusable in a variety of different environments. 32. What are checked exceptions? Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. 33. What are runtime exceptions? Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. 34. What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). 35. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection. 36. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 37. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 38. What is mutable object and immutable object? If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …) 39. What is the purpose of Void class? The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. 40. What is JIT and its use? Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem. 41. What is nested class? If all the methods of a inner class is static then it is a nested class. 42. What is HashMap and Map? Map is Interface and Hashmap is class that implements that. 43. What are different types of access modifiers? public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. 44. What is the difference between Reader/Writer and InputStream/Output Stream? The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented. 45. What is servlet? Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. 46. What is Constructor? A constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Constructor is invoked whenever an object of its associated class is created. 47. What is an Iterator ? The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a Collection. Iterators are a generic way to go through all the elements of a Collection no matter Define How it is organized. Iterator is an Interface implemented a different way for every Collection. 48. What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements. 49. What is memory leak? A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected. 50. What is the difference between the prefix and postfix forms of the ++ operator? The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. 51. What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 52. What will happen to the Exception object after exception handling? Exception object will be garbage collected. 53. Difference between static and dynamic class loading. Static class loading: The process of loading a class using new operator is called static class loading. Dynamic class loading: The process of loading a class at runtime is called dynamic class loading. Dynamic class loading can be done by using Class.forName(….).newInstance(). 54. Explain the Common use of EJB The EJBs can be used to incorporate business logic in a web-centric application. The EJBs can be used to integrate business processes in Business-to-business (B2B) e-commerce applications.In Enterprise Application Integration applications, EJBs can be used to house processing and mapping between different applications. 55. What is JSP? JSP is a technology that returns dynamic content to the Web client using HTML, XML and JAVA elements. JSP page looks like a HTML page but is a servlet. It contains Presentation logic and business logic of a web application. 56. What is the purpose of apache tomcat? Apache server is a standalone server that is used to test servlets and create JSP pages. It is free and open source that is integrated in the Apache web server. It is fast, reliable server to configure the applications but it is hard to install. It is a servlet container that includes tools to configure and manage the server to run the applications. It can also be configured by editing XML configuration files. 57. Where pragma is used? Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers. 58. Briefly explain daemon thread. Daemon thread is a low priority thread which runs in the background performs garbage collection operation for the java runtime system. 59. What is a native method? A native method is a method that is implemented in a language other than Java. 60. Explain different way of using thread? A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance. 61. What are the two major components of JDBC? One implementation interface for database manufacturers, the other implementation interface for application and applet writers. 62. What kind of thread is the Garbage collector thread? It is a daemon thread. 63. What are the different ways to handle exceptions? There are two ways to handle exceptions, By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. 64. Define How many objects are created in the following piece of code? MyClass c1, c2, c3; c1 = new MyClass (); c3 = new MyClass (); Answer: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized. 65.What is UNICODE? Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other. 66. Can a constructor have different name than a Class name in Java? Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method. 67. What will be the output of Round(3.7) and Ceil(3.7)? Round(3.7) returns 4 and Ceil(3.7) returns 4. 68: Can we use goto in Java to go to a particular line? In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line. 69. Can a dead thread be started again? In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread. 70. Is the following class declaration correct? public abstract final class testClass { // Class methods and variables } The above class declaration is incorrect as an abstract class can’t be declared as Final. 71. Is JDK required on each machine to run a Java program? JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required. 72. Which object oriented Concept is achieved by using overloading and overriding? Polymorphism 73. Is it possible to define a method in Java class but provide it’s implementation in the code of another language like C? Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately. 74. Define How destructors are defined in Java? In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced. 75. Can a variable be local and static at the same time? No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error. 76. Can we have static methods in an Interface? Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java. 77. In a class implementing an interface, can we change the value of any variable defined in the interface? No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later. 78. Is it correct to say that due to garbage collection feature in Java, a java program never goes out of memory? Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources. So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that. 79. Can we have any other return type than void for main method? No, Java class main method can have only void return type for the program to get successfully executed. Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status) 80. I want to re-reach and use an object once it has been garbage collected. Define How it’s possible? Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again. 81. In Java thread programming, which method is a must implementation for all threads? Run() is a method of Runnable interface that must be implemented by all threads. 82. I want to control database connections in my program and want that only one thread should be able to make database connection at a time. Define How can I implement this logic? This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time. 83. Can an Interface extend another Interface? Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface. 84. I want my class to be developed in such a way that no other class (even derived class) can create its objects. Define How can I do so? If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only. 85. Define How objects are stored in Java? In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects. 86. Define How can we find the actual size of an object on the heap? In java, there is no way to find out the exact size of an object on the heap. 87. Which of the following classes will have more memory allocated? Class Three methods, four variables, no object Class B: Five methods, three variables, no object Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class. 88. What happens if an exception is not handled in a program? If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing. 89. I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body? If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this(). 90. What’s meant by anonymous class? An anonymous class is a class defined without any name in a single line of code using new keyword. For example, in below code we have defined an anonymous class in one line of code: public java.util.Enumeration testMethod() { return new java.util.Enumeration() { @Override public boolean hasMoreElements() { // TODO Auto-generated method stub return false; } @Override public Object nextElement() { // TODO Auto-generated method stub return null; } 91. Is there a way to increase the size of an array after its declaration? Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size ( no of items), we should prefer vector over array. 92. If an application has multiple classes in it, is it okay to have a main method in more than one class? If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only. 93. I want to persist data of objects for later use. What’s the best approach to do so? The best way to persist data for future use is to use the concept of serialization. 94. What is a Local class in Java? In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined. 95. String and StringBuffer both represent String objects. Can we compare String and StringBuffer in Java? Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error. 96. Which API is provided by Java for operations on set of objects? Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap. 97. Can we cast any other type to Boolean Type with type casting? No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type. 98. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 99. Define How does a try statement determine which catch clause should be used to handle an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. 100. What will be the default values of all the elements of an array defined as an instance variable? If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. Basic JAVA Questions with Answers pdf download 101. What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 102. What is Serialization and deserialization? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 103. What are use cases? It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. 104. Explain the use of sublass in a Java program? Sub class inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation. 105. How to add menushortcut to menu item? If there is a button instance called b1, you may add menu short cut by calling b1.setMnemonic('F'), so the user may be able to use Alt+F to click the button. 106. Can you write a Java class that could be used both as an applet as well as an application? Yes, just add a main() method to the applet. 107. What is the difference between Swing and AWT components? AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. 108. What's the difference between constructors and other methods? Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times. 109. Is there any limitation of using Inheritance? Yes, since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation. 109. When is the ArrayStoreException thrown? When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown. 110. Can you call one constructor from another if a class has multiple constructors? Yes, use this() syntax. 111. What's the difference between the methods sleep() and wait()? The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread. 112. When ArithmeticException is thrown? The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations. 113. What is a transient variable? A transient variable is a variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization, 114. What is synchronization? Synchronization is the capability to control the access of multiple threads to shared resources. synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race. 115. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. 116. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. 117. The immediate super class of the Applet class? Panel is the immediate super class. A panel provides space in which an application can attach any other component, including other panels. 118. Which Java operator is right associative? The = operator is right associative. 119. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. 120. If a variable is declared as private, where may the variable be accessed? A private variable may only be accessed within the class in which it is declared. 121. What is the purpose of the System class? The purpose of the System class is to provide access to system resources. 122. List primitive Java types? The eight primitive types are byte, char, short, int, long, float, double, and boolean. 123. What is the relationship between clipping and repainting under AWT? When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. 124. Which class is the immediate superclass of the Container class? Component class is the immediate super class. 125. What class of exceptions are generated by the Java run-time system? The Java runtime system generates RuntimeException and Error exceptions. 126. Under what conditions is an object's finalize() method invoked by the garbage collector? The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. 127. How can a dead thread be restarted? A dead thread cannot be restarted. 128. Which arithmetic operations can result in the throwing of an ArithmeticException? Integer / and % can result in the throwing of an ArithmeticException. 129. Variable of the boolean type is automatically initialized as? The default value of the boolean type is false. 130. What are ClassLoaders? A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. 131. What is the difference between an Interface and an Abstract class? An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. 132. What will happen if static modifier is removed from the signature of the main method? Program throws "NoSuchMethodError" error at runtime . 133. Can try statements be nested? Yes 134. What is the default value of an object reference declared as an instance variable? Null, unless it is defined explicitly. 135. Can a top level class be private or protected? No, a top level class can not be private or protected. It can have either "public" or no modifier. 136. Why do we need wrapper classes? We can pass them around as method parameters where a method expects an object. It also provides utility methods. 137. What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. 138. Is it necessary that each try block must be followed by a catch block? It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block. 139. When a thread is created and started, what is its initial state? A thread is in the ready state as initial state after it has been created and started. 140. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. 141. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 142. What is runtime polymorphism or dynamic method dispatch? Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. 143. What is Dynamic Binding(late binding)? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. 144. Can constructor be inherited? No, constructor cannot be inherited. 145. What are the advantages of ArrayList over arrays? ArrayList can grow dynamically and provides more powerful insertion and search mechanisms than arrays. 146. Why deletion in LinkedList is fast than ArrayList? Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node. 147. How do you decide when to use ArrayList and LinkedList? If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used. 148. What is a Values Collection View ? It is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map. 149. What is dot operator? The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package. 150. Where and how can you use a private constructor? Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.T 151. What is type casting? Type casting means treating a variable of one type as though it is another type. Q: Describe life cycle of thread? A thread is a execution in a program. The life cycle of a thread include:Newborn state Runnable state Running state Blocked state Dead state 152. What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. 153. Which method of the Component class is used to set the position and size of a component? setBounds() method is used for this purpose. 154. What is the range of the short type? The range of the short type is -(2^15) to 2^15 - 1. 155. What is the immediate superclass of Menu? MenuItem class 156. Does Java allow Default Arguments? No, Java does not allow Default Arguments. 157. Which number is denoted by leading zero in java? Octal Numbers are denoted by leading zero in java, example: 06 158. Which number is denoted by leading 0x or 0X in java? Hexadecimal Numbers are denoted by leading 0x or 0X in java, example: 0XF 159. Break statement can be used as labels in Java? Yes, an example can be break one; 160. Where import statement is used in a Java program? Import statement is allowed at the beginning of the program file after package statement. 161. Explain suspend() method under Thread class> It is used to pause or temporarily stop the execution of the thread. 162. Explain isAlive() method under Thread class? It is used to find out whether a thread is still running or not. 163. What is currentThread()? It is a public static method used to obtain a reference to the current thread. 164. Explain main thread under Thread class execution? The main thread is created automatically and it begins to execute immediately when a program starts. It ia thread from which all other child threads originate. 165. Life cycle of an applet includes which steps? Life cycle involves the following steps: Initialization Starting Stopping Destroying Painting 166. Why is the role of init() method under applets? It initializes the applet and is the first method to be called. 167. Which method is called by Applet class to load an image? getImage(URL object, filename) is used for this purpose. 168. Define code as an attribute of Applet? It is used to specify the name of the applet class. 169. Define canvas? It is a simple drawing surface which are used for painting images or to perform other graphical operations. 170. Define Network Programming? It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network. 171. What is a Socket? Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. 172. Advantages of Java Sockets? Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic. 173. Disadvantages of Java Sockets? Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way. 174. Which class is used by server applications to obtain a port and listen for client requests? java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests 175. Which class represents the socket that both the client and server use to communicate with each other? java.net.Socket class represents the socket that both the client and server use to communicate with each other. 176. Why Generics are used in Java? Generics provide compile-time type safety that allows programmers to catch invalid types at compile time. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types. 177. What environment variables do I need to set on my machine in order to be able to run Java programs? CLASSPATH and PATH are the two variables. 178. Is there any need to import java.lang package? No, there is no need to import this package. It is by default loaded internally by the JVM. 179. What is Nested top-level class? If a class is declared within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Nested top-level class is an Inner class. 180. What is Externalizable interface? Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. 181. If System.exit (0); is written at the end of the try block, will the finally block still execute? No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. 182. What is daemon thread? Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. 183. Which method is used to create the daemon thread? setDaemon method is used to create a daemon thread. 184. Which method must be implemented by all threads? All tasks must implement the run() method 185. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars 186. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar . 187. What is the difference between the size and capacity of a Vector? The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time. 188. Can a vector contain heterogenous objects? Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object. 189. What is an enumeration? An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection. 190. What is difference between Path and Classpath? Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files. 191. Can a class declared as private be accessed outside it's package? No, it's not possible to accessed outside it's package. 192. What are the restriction imposed on a static method or a static block of code? A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance. 240. Can an Interface extend another Interface? Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface. 241. Which object oriented Concept is achieved by using overloading and overriding? Polymorphism 242. What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. 243. What is Downcasting? It is the casting from a general to a more specific type, i.e. casting down the hierarchy. 244. What are order of precedence and associativity and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left. 245. If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. 246. What is the difference between inner class and nested class? When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class. 247. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. 248. What is constructor chaining and how is it achieved in Java? A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement. 249. Can a double value be cast to a byte? Yes, a double value can be cast to a byte. 250. How does a try statement determine which catch clause should be used to handle an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. Core Java Interview Questions JAVA Online Test Java Interview Questions for Freshers & Experienced #java interview questions for experienced #java interview questions pdf #java interview questions and answers for freshers #java interview questions geeksforgeeks #java interview questions for experienced professionals #java interview questions for 5 years experience #java interview questions and answers for freshers pdf Read the full article
0 notes
Text
SOLVED:The method __________ sets the background color to yellow in JFrame frame.
SOLVED:The method __________ sets the background color to yellow in JFrame frame.
Question 1 (5 points) The method __________ sets the background color to yellow in JFrame frame. Question 1 options: setBackground(Color.YELLOW) frame.setBackGround(Color.yellow) setBackground(Color.yellow) frame.setBackground(Color.YELLOW) Question 2 (5 points) What layout manager should you use so that every component occupies the same size in the container? Question 2 options: FlowLayout any…
View On WordPress
0 notes
Text
FlowLayout — A bi-directional layout framework for iOS http://bit.ly/2OLSU0H #hotproduct
FlowLayout — A bi-directional layout framework for iOS https://t.co/HHXBxC1F6Y #hotproduct
— herrprofessor (@ilprofessoredi) August 6, 2018
from Twitter https://twitter.com/ilprofessoredi August 06, 2018 at 03:39AM via IFTTT
0 notes
Text
What is the most difficult thing in developing an iOS app?
Struggle in iOS app development derives from not accepting things and not getting used to them. Additional to the coding and Xcode, this will take sometimes to acquire, it will be coming up with concepts of apps that you wish to develop and hopefully make money off. There are SDKs that can help you get a better grasp of iOS app development, during your times as a junior developer.
Difficulties in developing an iOS app
1. Most difficult situation would be adding patches to the written code for scope changes by your management. Sometimes code standard cannot be maintained because of scope changes and to meet the schedule.
2. Intermingling with SOAP API is a jiffpuzzling in iOS, in specific SOAP API that questions you to sign the message body with permits.
3. Drifting from one backend to other backend for an app in making has to be allocated with caution. Check numerous times with new backend afore you shift and hit production.
4. If you are not undertaking native iOS app development, may be using certain third party frame works like IONIC or Xamarin its most expected you have to delay for them to apprise their libraries if any update free by apple, furthermore like a great combatant on a crippled horse.
5. The snags would be surely different from developer to developer. Some of the major difficulties applying in iOS are:
Writing unit testable code for iOS app development • Efficient use of GCD or NSOperationQueue • Subclass flowlayout in UICollectionView • Precisely instrument beacon section observing/alternating
6. Autolayout appears to be one of the most complexions with iOS. The uncountable number of constrictions and dealings that one has to designate in the interface builder is as annoying as it is perplexing. Autolayout may be the most difficult to realize while developing on Xcode, but absolutely value it. The similar outline can be demarcated in numerous ways. It is quite active and delivering, and has taken over a lot of code.
7. Debugging issues with provisioning profiles, app signing and uploading to the App store. There are a couple QuickLook plugins* that can help a bit, but this area is still a big headache.
8. Monetizing your app is no less easy. A very small percentage of all app developers rake in most of the revenue, while some large number of great won’t get any attention, and therefore no sales due to the lack of exposure. Apple needs to:
Increase the bar on app tender so that the app store isn’t jam-packed with everyone’s first venture into programming • Remove apps on the apps store that are not vigorously being developed by the developer • Create a more expressive discovery and hunt appliance. Probing for an app or a keyword, shouldn’t outcome in tens or hundreds of apps that are trailing trademarks or brands • Work to readjust the end-users notions of ‘value’ and ‘worth’ so that the developers can price apps at more healthy and sustainable prices equivalent to a starbucks drink or the price of a movie ticket.
Numerous encounters would be down the road, it is all about getting used to them. There are by now many great apps there and individuals are familiarized to them. The next project you obviously take on more inspiring things, until you get more and more familiarity and information under your belt and you can yield whatever you can think of.
Source: https://www.laitkor.com/what-are-the-major-challenges-for-full-time-ios-app-developers-2/
0 notes
Text
1.10.18
.xml file describes structure of data android has 4 seperate source subfolders for projects compared to java having 1 syntax of xml looks familiar to html xml formats data to be interactive with user deliminators of less than greater than sign, just like html: example: //Closes here XML (imported from CSV BELOW) //“avail=winter” == attr are extra things, metadeta 2100 CSV (Export to XML ABOVE) Product Pid, Price, qty, desc 2 100 20 hammer ——————————————————————————————- lots of xml usage, visual interface description ——————————————————————————————- 2nd folder of android studio project folder “java” ——————————————– 3rd folder = “res” //graphics, icons, text, formatting 4 subfolders “layout” has XML – blank screen, divide into sections, spacial layout like java BorderLayout, GridLayout, FlowLayout swing package libraries //write code to respond to events, listeners, when user does an event, need code to respond to it //mouse clicked, has to fit behind the interface //make code respond to things on screen ——————————————————– 4th ——————————————————- Gradle Scripts //lot more import stuff from android packages primarily for compiling into executable ———————————— Java > Class > JVM Java > Class > dex (dalvik exe) > DVM ——————————————————- the area im going to be working in most often is the java first folder (not test), and the res>layout and res>value //Every string should be defined in XML (values>strings.xml file) referred to by name // MyOdometer mipmap - images of different resolutions, a set of different resolution images, automatically picks the right one higher res > close , lower res > far res>drawable > little icons to stick on the screen in seperate places .png file —————————————————— 2454 web system developement 2858 integeration and web services program —————————————————— (opposite order) Linux Kernal Libraries : OpenGL // RES > LAYOUT > .XML > DESIGN (OR TEXT) Choose emulator Virtual Device Configuration ———————– book pg 45 chapter 2 example of tip calculator ———————– powerpoint slide 4 edittext widget button widget textview widget all things on scren are widgets
0 notes
Text
자바 익명클래스와 람다식
요즘 쓸게 별로 없어서.. 이런거라도 올려본다.
아래의 프로그램은 버튼을 누르면 해당 버튼의 텍스트가 출력되는 프로그램이다. 아래로 갈수록 코드가 간결해져 가는 것을 알 수 있음.
일반
package Test_Swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; public class JButtonTest_General extends JFrame implements ActionListener { private JButton button; private JLabel label; JButtonTest_General() { super("JButoon Test"); setLayout(new FlowLayout()); setSize(300, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); //Set Button button = new JButton("Button"); button.setActionCommand(button.getText()); button.addActionListener(this); add(button); //Set JLabel label = new JLabel("Press Button!!"); add(label, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { new JButtonTest_General(); } @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getActionCommand().equals(button.getText())) { label.setText(button.getText()); } } }
익명클래스
package Test_Swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButtonTest_Anonymous extends JFrame { private JButton button; private JLabel label; JButtonTest_Anonymous() { super("JButoon Add"); setLayout(new FlowLayout()); setSize(300, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); //Set Button button = new JButton("Input"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { label.setText(button.getText()); } }); add(button); //Set JLabel label = new JLabel("Press Button!!"); add(label, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { new JButtonTest_Anonymous(); } }
람다
package Test_Swing; import javax.swing.*; import java.awt.*; public class JButtonTest_Lambda extends JFrame { private JButton button; private JLabel label; JButtonTest_Lambda() { super("JButoon Add"); setLayout(new FlowLayout()); setSize(300, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); //Set Button button = new JButton("Input"); button.addActionListener((e) -> { label.setText(button.getText()); }); add(button); //Set JLabel label = new JLabel("Press Button!!"); add(label, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args) { new JButtonTest_Lambda(); } }
1 note
·
View note
Text
vkatz-lib
There is a bunch of useful widgets and navigation classes to make your app clear and simpler. Include features like font from asses via xml, complex background, resizable compound drawables, FlowLayout and SlideMenuLayout (expand menu from any direction), custom backstack (abstract + fragments impl).
from The Android Arsenal http://ift.tt/2yP8zqF
0 notes
Photo

i need complete and acurate answers for following questions i need complete and acurate answers for following questions ATTACHMENT PREVIEW Download attachmentWeek 3 Homework AssignmentCreate a Word document containing the answers to all the problems given below.1.Write a statement to create a JFrame object with a title of “My GUI Application”.2.Given the object you created in question 1,write a statement to specify the window size tobe 300 pixels wide and 400 pixels high?3.What would you need to do to the object from question 1 to make sure that theapplication containing the object terminated when the object’s window was closed?4.Write a Java statement to make the window associated with the object from question 1visible.5.Explain how a BorderLayout manages its display area.6.Explain how a FlowLayout manages its display area.7.Write a Java statement to have the object from question 1 manage its display area bydividing it into 3 rows which have 4 columns each.8.The frame object from question 1 uses a BorderLayout by default.
0 notes